Sending JSON Data From Android to a PHP Script

In my previous blog Meet JSON! I talked about how JSON is used in the mainstream. Now, how do we send JSON Objects from Android to a server script written in PHP?

In this tutorial we will pass a JSONObject with our message to our server code written in PHP. Our server reads our JSON, reverse our message, and send it as a reply. I will not be discussing in detail the server code, and the java client code (MainActivity.java) for these are not my main topic in this Blog. I will be merely give emphasis on “Sending” the data.

PHP

Our server code

<?php 

if( isset($_POST["json"]) ) {
     $data = json_decode($_POST["json"]);
     $data->msg = strrev($data->msg);

     echo json_encode($data);

}

For those who don’t understand these lines of PHP code, in our first line we’re saying that if $_POST[“json”] has a value, then we execute. You may want to read about Server and Request variables in PHP. In the next line, we decode the json data inside $_POST[“json”] and catch it. Reverse the String in the “msg” entity of the object, encode and echo.

Our MainActivity.java (ANDROID)

package com.coffeecodes.coffecodesdoodle;

import org.json.JSONException;
import org.json.JSONObject;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;

public class MainActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		try {
			JSONObject toSend = new JSONObject();
			toSend.put("msg", "hello");

			JSONTransmitter transmitter = new JSONTransmitter();
			transmitter.execute(new JSONObject[] {toSend});

		} catch (JSONException e) {
			e.printStackTrace();
		}

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

}

Now I’ll just discuss the important lines which is wrapped in the try block. Observe toSend.put(“msg”, “hello”). looking back to our server code, “msg” is our critical data to be reversed. JSONTransmitter is our class that will be tackled below. Because it is a child of AsyncTask class, the way we execute a command is transmitter.execute(new JSONObject[] {toSend}). In our parameter, I passed an array of JSONObject which only contains 1 object, the toSend.

Let’s have this class that will send JSON object as String to PHP.

JAVA


import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.json.JSONObject;

import android.os.AsyncTask;
import android.util.Log;

public class JSONTransmitter extends AsyncTask<JSONObject, JSONObject, JSONObject> {

    String url = "http://10.0.2.2/coffeeCodes/";

    @Override
    protected JSONObject doInBackground(JSONObject... data) {
        JSONObject json = data[0];
		HttpClient client = new DefaultHttpClient();
		HttpConnectionParams.setConnectionTimeout(client.getParams(), 100000);

		JSONObject jsonResponse = null;
        HttpPost post = new HttpPost(url);
		try {
	        StringEntity se = new StringEntity("json="+json.toString());
	        post.addHeader("content-type", "application/x-www-form-urlencoded");
	        post.setEntity(se);

	        HttpResponse response;
			response = client.execute(post);
			String resFromServer = org.apache.http.util.EntityUtils.toString(response.getEntity());

			jsonResponse=new JSONObject(resFromServer);
			Log.i("Response from server", jsonResponse.getString("msg"));
		} catch (Exception e) {	e.printStackTrace();}

        return jsonResponse;
    }

}

On our class declaration of JSONTransmitter in line 1, we extended the AsyncTask class that passes 3 data types. AsyncTask is used for proper execution of Threads in Android. Inside our diamond operator , the first data type we declared is for the parameters’ type, then for progress and result respectively. In our case, we pass parameters to our JSONTransmitter object in JSONObject type. we broadcast update also in JSONObject, and we return the result in JSONObject.

String url = "http://10.0.2.2/coffeeCodes/";

Yes, it is what it looks like. http://10.0.2.2/coffeeCodes/ is where our server script will be hosted. well usually in web development we use “localhost” instead of 10.0.2.2 . But if we use localhost in this matter, localhost will be referring to your emulator’s system rather than your apache server (or what not). If you don’t have a clue on how we came up with “localhost” and how to put up your server codes, you would want to watch this first.

JSONObject json = data[0];

You might wonder about this first statement in our doInBackground method. The “data” variable is in JSONObject which is in array format. So what we did here is to take the first item in the array. Well that would be our scope of this program, only one JSONObject will be executed, just to make things simple.

HttpClient client = new DefaultHttpClient();

Think of “client” as Harry Potter’s Owl ;). it will be the one to send and execute data that we will build.

HttpPost post = new HttpPost(url);

“post” is our envelope. it carries our JSONObject and other necessary details such as to where we would send out message. In this case, we passed “url” (the class variable) as our send address.

StringEntity se = new StringEntity("json="+json.toString());
post.addHeader("content-type", "application/x-www-form-urlencoded");
post.setEntity(se);

And these are our contents. If you are familiar with HTTP headers, this won’t look like an alien to you. The handler of our json would be the StringEntity se. and if you noticed, we mutated our json to string form and as it would look like, it will be… json = {“msg” : “hello”}

So, let’s do the magic.

HttpResponse response = client.execute(post);
String resFromServer = org.apache.http.util.EntityUtils.toString(response.getEntity());

jsonResponse=new JSONObject(resFromServer);
Log.i("Response from server", jsonResponse.getString("msg"));

client.execute(post); The owl just flew and immediately came back and dropped the reply to your mailbox, “HttpResponse response”. Because we don’t speak Parrseltongue, we need a translator org.apache.http.util.EntityUtils.toString(response.getEntity()). Assuming that it is in JSON format, we then pass the response to our JSON parser JSONObject(resFromServer) and finally output our message to the LogCat.

Screenshot from 2013-10-20 12:21:39

JQuery: Append New HTML Elements and Inherit Event Handlers

Click, loading whole page, click, loading whole page, click, loading whole page

Waiting for a page to load is tiring for you visitor and often the cause of Page Abandonment. With just 4 seconds of loading time, you lose 25% of your visitors according to Google Analytics and KISSMetrics. This is also one of the reasons why Ajax has become an industry standard in web development.

Although we won’t be talking about Ajax in this blog entry, this post will show how to add elements dynamically to your page without loading the whole page again. Implementation is purely done in JQuery and HTML.

<div id="wrap">
    <div class="box" style="width:50px;height:50px;background:#000;"></div>
</div>
<input id="btn" type="button" value="Click Me!" />

Attach this script to the <head> or at the bottom-most part of the page.

$(".box").click( function() { // event triggered if .box is clicked
     $(this).remove(); // remove this element on click
});

$("#btn").click( function() { // run this code if button is clicked
     var html = "<div class='box' style='width:50px;height:50px;background:#000;'></div>"; // or any html element you want
     $("#wrap").append(html); // This line makes the magic
});

Notice that the pre-written html of .box is the only one responding to the click event, the added boxes don’t. That’s because the event handler is not vissible to the appended element. So how to fix it? Let’s apply Event Delegation.

$("#wrap").on("click", ".box", function() { // event is triggered if you click within the #wrap and apply handler to .box
    $(this).remove(); // remove this element on click
});

$("#btn").click( function() { // run this code if button is clicked
    var html = "<div class='box' style='width:50px;height:50px;background:#000;'></div>"; // or any html element you want
    $("#wrap").append(html); // This line makes the magic
});

So what’s the difference? On the first script we attached and event handler to .box (div with class name box). In that manner, the event handler will only be attached to the existing .box upon the reading of the script.

On the other hand,

Attaching an event handler to the parent, which is the #wrap, will propagate the handler to its children whether a newly added one or a static one. This will make all elements inside the #wrap div respond to you event handler.

Thanks for reading.