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 – Part 2

Read Part 1 here. Part 1 covers how to get a user’s geolocation to dynamically generate the weather according to the user’s location.

Part 2 is about using the user’s location to get the local weather forecast.

I used OpenWeatherMap‘s API to get the weather information. You’ll need to sign up (it’s free!) and get an API key: http://openweathermap.org/appid

  1. Sign up and get an API key from OpenWeatherMap.
  2. This is an example of the URL (API call) you will use to get weather info:
    http://api.openweathermap.org/data/2.5/weather?lat=33.7708&lon=-84.2931&units=imperial&APPID={APIKEY}

    This is the URL to OpenWeatherMap API:

    http://api.openweathermap.org/data/2.5/weather?

    You can use a city name, city ID, or longitude & latitude coordinates. I decided to use the longitude and latitude for more accurate weather.

    This is where you put the latitude and longitude coordinates.

    lat=11.111&lon=-11.111

    The longitude and latitude coordinates were derived from Part 1:

    {"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,}

    You can also toggle Celsius and Fahrenheit with

    &units=

    Celsius: units=metric
    Fahrenheit: units=imperial

    Read more here.

    In place of {APIKEY} paste your OpenWeatherApp API key. You can find your key when you log into your account and go to the API Keys tab.

  3. Test your API call with Postman by placing the full URL ( http://…APPID=&#8230;..) in as a GET request. You should get a response similar to something like this:
    {"coord":{"lon":139,"lat":35},
    "sys":{"country":"JP","sunrise":1369769524,"sunset":1369821049},
    "weather":[{"id":804,"main":"clouds","description":"overcast clouds","icon":"04n"}],
    "main":{"temp":289.5,"humidity":89,"pressure":1013,"temp_min":287.04,"temp_max":292.04},
    "wind":{"speed":7.31,"deg":187.002},
    "rain":{"3h":0},
    "clouds":{"all":92},
    "dt":1369824698,
    "id":1851632,
    "name":"Shuzenji",
    "cod":200}

    Play around with different locations and when it is successful, you can go to the next step!

  4. Start writing your JavaScript function! We need to create an AJAX call to get the data returned from the API and store it in our own variables so we can use the information. I used the jQuery .ajax function.
    function getWeather(url) {
    	$.ajax({
    		url : url,
    		dataType : "json",
    		success : function(data) {		
    			var temp = data['main']['temp'];
    			var image = data['weather'][0]['icon'];
    			var desc = data['weather'][0]['description'];
    			var humidity = data['main']['humidity'];
    			var rain = data['weather'][0]['main'];
                            var sunset = new Date((data['sys']['sunset'])*1000);
                            sunset = sunset.toString().slice(16,21);
                            document.getElementById('image').src="http://openweathermap.org/img/w/" + image + ".png";
    			$('#temp').html(temp);
    			$('#desc').html(desc);
    			$('#wind').html(rain);
                            $('#sunset').html(sunset);
                            $('#humidity').html(humidity + "%");
    		}
    	});
    }

    The sunset variable is storing the sunset UNIX number and converting it to a readable format according to the user’s timezone.

    I am passing in the parameter to getWeather the URL saved as Weather in Part 1. It’s the URL you use to make the weather API call.

To load OpenWeatherMap’s weather icons, use this img source format:

http://openweathermap.org/img/w/" + image + ".png";

Where:

var image = data['weather'][0]['icon'];

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

Source for how to get the weather icons here: https://openweathermap.desk.com/customer/portal/questions/13287488-weather-icon-id

Another weather API you can use: forecast.io

Github Pages

Did you know that you can use Github Pages to host your websites live?

It’s free and easy to setup whether you are on Windows or Mac.

There are two different types of Github Pages, one for Users & Organizations, and one for Projects. Each User & Organization can only have ONE Github Page. With each Github Page, you can have unlimited Project Pages. Project Pages are located as a subpath to the User Page (http://username.github.io/projectpage). To get more information about the similarities and differences, click here.

To set up a User Page, you first will need to create a new repository called username.github.io (where username is your Github username). This will be the URL of your website.

Then follow the instructions located here: https://pages.github.com/

To read about setting up a custom domain, go here.
Adding a CNAME file to your repository (for custom domains), go here.

Free Code Camp

A friend recommended a new free coding resource for learning full-stack development called Free Code Camp. I’ve been trying out their lessons the past two days to see how they are. I’m very impressed with their community, network, organization, and support. They don’t teach Ruby and Ruby on Rails, which is what I’ve been learning the past few months. Instead they focus more on JavaScript and Node.js.

This is what their curriculum looks like:

800 Hours of Practice:

    800 Hours of  Real World Work Experience:

  • 100-hour Nonprofit Project
  • 200-hour Nonprofit Project #1
  • 200-hour Nonprofit Project #2
  • 300-hour Nonprofit Project

I really love the idea that you can work on some real-world non-profit projects after you complete their lessons. It’s great to get real experience and add a project to your portfolio. I don’t know any other free or paid coding school that gives you such a great opportunity.

Their HTML and CSS portion was fairly easy to go through and it was a great review since I had learned it earlier in the year. Their jQuery and JavaScript lessons use Codecademy, so you will still need to go between the two websites. I’m currently going through the Free Code Camp JavaScript so we’ll see how their subsequent lessons fair.

Free Code Camp is also on LinkedIn as an education institute and they encourage you to add them to your LinkedIn profile. Also check out Free Code Camp on Github. They are also on Facebook. I joined the Atlanta chapter.