Passing a PHP Array through AJAX

If you are creating dynamic elements on your page, you will need to be able to send information to and from the browser. There’s lots of documentation on how to POST data using AJAX to the server side. What if you want to return an array of data back to the browser?

$.ajax({
    url: "<?php echo site_url('test/urlGoesHere/'); ?>",
    type: 'POST',
    data: form_data,
    dataType:"json",
    success: function(data) {
        alert(data[0]);
   }

Marking the dataType as json here is key.

In your PHP file, use json_encode to send your array:

print json_encode($my_array);

If you don’t want to save the array into a variable, you can also just write the array between the json_encode parantheses:

print json_encode(array("name"=>$name,"title"=>"Ms."));

Then in your AJAX success, you can access the array elements this way:

data.name[0]; //the first name element
data.title;  // "Ms."
data[0];

If this was your array: array("Jack", "Mr."), then your AJAX data can be handled like this:

$.ajax({
    url: "",
    type: 'POST',
    data: form_data,
    dataType:"json",
    success: function(data) {
        var name = data[0];
        var title = data[1];
        alert('Name: ' + name + ', Title: ' + title);
   }
Advertisements

Show the Local Weather

This is Part 1 explaning the steps I took to complete the Show the Local Weather challenge from FreeCodeCamp‘s Intermediate Front-End Development Projects section. Part 1 consists of getting a user’s geolocation dynamically. Part 2 Part 2 will be about how to use OpenWeatherMap’s API in your app.

I used Postman to check API connectivity and to get the JSON objects. You can also simply use your browser to do the checks.

  1. First I created the site layout for my weather app using Bootstrap. This way I could play with where I wanted the person’s location to appear and how I wanted to show the weather. I used HTMLshell to quickly paste the usual tags.
  2. I created an empty CSS file and an empty JS file and included the links in my main index.html file.
  3. Then I wanted to add a button that could toggle Celsius and Fahrenheit. I needed to add JavaScript to be able to toggle the action when a user clicks the toggle button.
  4. After getting the button to work, I focused on how to get the user’s location. I used http://freegeoip.net/ to grab a user’s IP address and use that to determine their location. It’s less accurate than Google’s Geolocation, but you can scroll to the bottom to read why that isn’t so simple to implement in Chrome since Spring this year.I knew I was using JSON so I used the url:
    freegeoip.net/json/

    When passing this url, freegeoip will automatically grab the user’s IP and return a JSON object similar to this:

    {"ip":"8.8.8.8",
    "country_code":"US",
    "country_name":"United States",
    "region_code":"NY",
    "region_name":"New York",
    "city":"New York City",
    "zip_code":"10128",
    "time_zone":"America/New_York",
    "latitude":40.7142700,
    "longitude":-74.0059700,}

    If you are using Postman, you can play around with what the response is by sending a GET to:

    //location info for freecodecamp.com
      freegeoip.net/json/freecodecamp.com
    
    //location info for your location
      freegeoip.net/json/
    
    //location info for yahoo.com
      freegeoip.net/json/yahoo.com
  5. Once you are successfully able to get the JSON object info, you can start creating your AJAX call in your JS file. I created a function called getLocation() to contain the information. I used the jQuery function $.ajax to get the data. Can also reference this. Make sure to include the jQuery link in the <head> of your html file or it won’t work!
     https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js

    This is the $.ajax template:

    $.ajax({
      dataType: "json",
      url: url,
      data: data,
      success: success
    });

    This is what my function looks like:

    var locateUser = 'http://freegeoip.net/json/';
    
    function getLocation() {
      $.ajax({
        url : locateUser,
        dataType : "json",
        success : function(data) {
        var country =data['country_code'];
        var region = data['region_code'];
        var city = data['city'];
        var latitude = data['latitude'];
        var longitude = data['longitude'];
        $('#location').html(city + ', ' + region);
        var Weather = "http://api.openweathermap.org/data/2.5/weather?lat=" + latitude + "&lon=" + longitude + "&APPID=" + OpenWeatherKey;
    getWeather(Weather);
        }
      });
    }

    The ‘#location’ id is tied to the <div> where I want the City, Region to appear on my website.

  6. The next step is to grab the weather for the location data you just stored!

Read Part 2: Getting the Weather Information here.

Final Product: http://sunsplat.github.io/fcc_weather/index.html

Note: When attempting to complete this challenge, do not use Google’s Geolocation as since May 2016, they require do not work over insecure domains (must use HTTPS). Free SSL here.

If you insist on trying to implement Google’s Geolocation, you can sign up for an API key here: https://console.developers.google.com. Then follow Udacity’s really great tutorial on using it: https://www.udacity.com/course/google-maps-apis–ud864.

Keep in mind that Chrome and Safari (webkit browsers) do not allow Geolocation API for files that are local. Geolocation WILL work in Internet Explorer as of this posting.


Another weather API you can use: forecast.io
Another IP geolocation API: http://ipinfo.io/


See https://developers.google.com/web/updates/2016/04/geolocation-on-secure-contexts-only for details.

https://www.chromium.org/Home/chromium-security/education/tls#TOC-TLS-Resources-for-Developers-and-Site-Operators

https://mobiforge.com/news-comment/no-https-then-bye-bye-geolocation-in-chrome-50

https://developers.google.com/maps/documentation/geocoding/start?csw=1#reverse