Understanding php-json-javascript communication - a test case

Hello all,

By having this…
testeBasico.php


$.post("testeBasico_1.php", {foo: 'bar'}, function(response) {
                if (response.success) {
                    for (var x = 0; x < response.data.length; x++) {
                        alert(response.data[x]);
                    }
                }
            }, "json");

And then, this:
testeBasico_1.php


<?php
echo("ola");

$response = array(
    'success' => TRUE,
    'data'       => array("foo", "bar", "baz")
);

json_encode($response);

?>

I can’t get the “ola” to show on the page when I do a refresh.
I’m getting “bar undefined”.

I do have a lot of simple and quick questions, but I will make just one:
1) Why am I getting “bar undefined” ?

Thanks in advance,
Márcio

I’m trying to echo “ola” on the screen. I’m getting “bar is not defined”.
But, if I change $.post second argument to a string, I get no javascript error, but I still can’t see the echo. :nono:

Shouldn’t the $.post run upon page refresh? What am I missing?

No problem. I’m here to help!
If you need any more assistance, feel free to PM me.

-Zarin

Thanks a lot. I rest my case. :slight_smile:

You really help me out understanding some concepts about this process. :smiley:

Márcio

Answer to post #8 By using dataLength = response.data.length; we are storing at the first loop call our length value into a variable, so we can then use that value without need to verify the length again and again.

Oh! Yes, data comes from the JSON object you created in PHP on the server.


$response = array(
    'success' => TRUE,
    'data'       => array("foo", "bar", "baz")
);
echo json_encode($response);

That’s the code you originally posted to create the JSON object on the server. When your page gets it back, it’s converted back from text into a Javascript Object, which will have the properties you’ve created there - namely, “success” and “data”.

You could just as easily name your data array blabla in the PHP and then you would use response.blabla to reference it in the JS.

No no no. My question is just:
we have done “response.data” to grab the data. We cannot do “response.blabla” to grab the data right?
So, you should know that, data, and not blabla was something that you could use right?

The fact that “response.data.length no longer has to be evaluated every time the loop runs through” and response.data does, it’s something to do with the fact that we use “for in” instead of “for”, or something else? I mean, how do you know that one will be evaluated and other don’t?

I promise I will end this! :s I just… need to ask… I’m feeling like I’m getting somewhere here… thanks again…

  1. Pretty much. Your method works too, both have their flaws. What you should really do is this:

for (var x = 0, dataLength = response.data.length; x < dataLength; x++)

The advantage to this is that response.data.length no longer has to be evaluated every time the loop runs through.

  1. I believe so. Sometimes I can get confused as to what terms are used in javascript, but I believe it’s a property of the response object.

  2. I didn’t, this is really my own mistake. I just kept the code as minimal as possible to get it working when I was having my firebug issue. You SHOULD test whether it’s there or not like this:


if(response.data){

for (var x = 0, dataLength = response.data.length; x < dataLength; x++){
	$('#data').append(response.data[x]+'<br>');
}

}

Thanks a lot really.

The alert is only for testing proposes. I will change just to see what I get.

One SIZE=“1”[/SIZE] last question if you don’t mind, please:

Is

for(x in response.data)

a shorter version of:

for (var x = 0; x < response.data.length; x++)

?

response.data (is it a property of the response object returned) ?

And, how did you know that data was there to be used? And the same goes for the x inside data (array?). (this makes them 4. :s)

Thanks,
Márcio

So, echo will work as a sender here? Is there other senders that send to the browser, without the function of display something into the viewport ?

You do have to echo or print the data. This is just the nature of AJAX calls. If you don’t echo out the data, the web browser won’t see anything when it gets to the page on your server.

Ok… because we are sending something to the browser before the other things that we are really send it right?

Right. When you tell jquery to expect JSON data it wants it in a specific format. If you echo out random information before that, it’s not going to work.

We should append our data. Ok. :s Why doesn’t a simple alert work here?

This is really personal preference, but if you wanted to say, update data on your web page, you would append, or use $.html() to replace some other content. An alert would work as well, if that’s how you decide you want to deliver your data.

I hope this helps!

Firefox 3.6.8 - If I enable firebug all firefox hangs… so I have just disable it.

So:


<?php
$response = array(
    'success' => TRUE,
    'data'    => array("foo", "bar", "baz")
);

echo json_encode($response);

Thanks. So, echo will work as a sender here? Is there other senders that send to the browser, without the function of display something into the viewport ?
Just wondering… (not asking big words here… just some names or buzzwords… to look around).

Ok… because we are sending something to the browser before the other things that we are really send it right?

We should append our data. Ok. :s Why doesn’t a simple alert work here?

Thanks a lot,
Márcio

Is it safe to assume you’re working in firefox?
If so, I’m running into issues here too. Let me show you what I’m doing with your code:

index.php


<DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
	<head>
		<title> </title>
		<link rel="stylesheet" type="text/css" href="http://yui.yahooapis.com/2.8.0r4/build/reset/reset-min.css">
	</head>
	<body>
	<div id='data'></div>
	<script src="/resources/jQuery/latest/jquery.min.js"></script>
	<script language="javascript" type="text/javascript">
	$(document).ready(function(){
		$.post("data.php", function(response) {
				for(x in response.data)
				{
					$('#data').append(response.data[x]+'<br>');
				}
            }, "json");
	});
	</script>
	</body>
</html>


<?php
$response = array(
    'success' => TRUE,
    'data'    => array("foo", "bar", "baz")
);

echo json_encode($response);

With this code, in Firefox 4b4, I’m not getting anything in data, I can’t alert, log or take any actions from my callback.

In Chrome 6 dev, it works exactly as expected. I get this:

foo
bar
baz

I’m not sure why firefox isn’t working for me, perhaps it’s a problem with the beta. If you are using firefox, which version is it?
2nd edit:
Scratch that. Turns out the firebug 1.6 test version is screwing with jquery.
Disabling it made the code act right. So yeah, see my other edit below, that should help.

1st Edit: I forgot to mention that you are not echoing your json_encode. You need to do this to send that data to the browser, and echoing ‘ola’ before it might cause problems there.
If you want anything from a post response to end up on your screen, you need to tell jquery to append your response to an element on the page like this:


$.post("data.php", function(response) {
	$('body').append(response);
});