Link to home
Start Free TrialLog in
Avatar of Crazy Horse
Crazy HorseFlag for South Africa

asked on

JSON response using Ajax/jQuery/PHP

So, I am really trying to get my head around JSON and I have tried this which works but I wanted to know if there is a better way to do it or if this okay. I am actually playing around with developing a hybrid mobile app which uses a php and mysql backend. I have to use ajax to retrieve data and I want to also use JSON.

This is the jQuery/Ajax. The double dollar signs are not a typo, that is the correct syntax for the application but it is identical to jQuery as far as I know.

$$( "#submit" ).click(function(e){
		$$.ajax({
			url:"content.php",
			type:"POST",
			dataType:"json",
			success: function(data) {
				var len = data.length;
				for(var i = 0; i<len; i++) {;
					var user_name = data[i].user_name;
					$$( "#phpcontent" ).append(`
					<li class="item-content">
						<div class="item-inner">
						<div class="item-title">${user_name}</div>
						</div>
					</li>
					`);
				}
			}
		});
	});

Open in new window


This is the php for content.php

$stmt = $link->prepare("SELECT `user_name` FROM `users` ORDER BY `user_name` DESC");
$stmt->execute();
$result = $stmt->get_result();
$numRows = $result->num_rows;
if($numRows > 0) {
	while($row = $result->fetch_assoc()) {
		$user_name = sanitize($row['user_name']);
		
		$return_array[] = array(
		
			"user_name" => $user_name
		
		);
	}
}
$stmt->close();
echo json_encode($return_array);

Open in new window


What I have noticed in all the examples I have looked at is that the database results have to be put into an array in order to use json_encode. Am I correct in saying that or is it just a coincidence that every example I looked at did that?
Avatar of Leonidas Dosas
Leonidas Dosas
Flag of Greece image

Yes we made a PHP array and encoded it to json data object via json_encode function.
I am actually playing around with developing a hybrid mobile app
Clarification on terminology - a hybrid mobile app is one that uses html / css / javascript but is wrapped in a container that installs as a native app would and which has access to underlying hardware.

With respect to a JSON return - in JavaScript (and PHP) arrays and objects strongly overlap.

In JavaScript - you can access an object as an array so
var data = {
   name: "Fred"
};
var name = data.name; // is the same as
var name = data['name']; // this

Open in new window


With JSON and JavaScript we usually have two types of return
a) A single instance of an object representing data we are interested in
b) An array of objects representing a list of items we are interested in

In the case of a) it can be represented as an object or an array
In the case of b) it can be an array of arrays or an array of objects
SOLUTION
Avatar of Dave Baldwin
Dave Baldwin
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
As others have said, if you have a list of items, then that is represented as an array in PHP. You then json_encode that array and loop through it in your jQuery.

If you just had one item returned from your db, then you would just json_encode that and access the properties within your jquery without having to loop through anything (although even a complex single object in PHP may still be represented as an array of properties).

You could potentially simplify your jquery code by using the built in each function. Something like this:

success: function(data) {
    $.each(response, function(i, item) {
        $( "#phpcontent" ).append(
            $("<li/>").text(item.user_name);
        );
    });
}

Open in new window

SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
There are very good reasons for using JSON strings - the main one being that they are almost universally used and supported. If you are using jQuery AJAX then jQuery will parse the JSON string into a JavaScript object for you.

Can't see any merit in using another format - personally in this instance I would just render the HTML on the server and send it back as one long string.
I agree with Julian.  If I only have one HTML element to fill with the AJAX response, I will send HTML formatted data.  If however, I have a need for multiple separate data items in separate HTML elements then I might use JSON because it encapsulates the elements fairly neatly.  And the data is easy to 'extract' and use where you need it.
Avatar of Crazy Horse

ASKER

So, in my instance are you saying (Dave and Julian) that I should just use:

$( "#phpcontent" ).html(data);

Open in new window


and then echo out the values in the php query instead of using json_encode() ?
Exactly
Sorry if I am stating the obvious or taking longer to understand than a normal person, but would you then use the JSON method if you wanted to display more user details like first name, last name, email address, contact number etc?
I would only use JSON if I had to parse it to different and separate elements on the page.  If it all goes in one element like a single <div>, I would format it in PHP and send the whole thing back as one item.  

I do other weird things though.  On some of my pages, I use PHP to generate javascript to display on the page.  And of course, images can be delivered with PHP so you can keep track of users and IP addresses.
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thanks so much to everyone for your comments. I'm going to have to split the points up for everyone as everyone made a contribution. Of course, my least favorite part is having to choose a "best" solution now. Dear EE, when will you let me choose more than one "best" answer?