SitePoint Sponsor

User Tag List

Results 1 to 11 of 11
  1. #1
    SitePoint Wizard
    Join Date
    Feb 2009
    Posts
    1,006
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    understanding php-json-javascript communication - a test case.

    Hello all,


    By having this...
    testeBasico.php
    Code JavaScript:
    $.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 Code:
    <?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&#225;rcio

  2. #2
    SitePoint Wizard
    Join Date
    Feb 2009
    Posts
    1,006
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Thumbs down

    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.

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

  3. #3
    SitePoint Addict Zarin Denatrose's Avatar
    Join Date
    Jan 2009
    Location
    Surrey BC, Canada
    Posts
    309
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    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
    Code:
    <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 Code:
    <?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:
    Code:
    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:
    Code:
    $.post("data.php", function(response) {
    	$('body').append(response);
    });

  4. #4
    SitePoint Wizard
    Join Date
    Feb 2009
    Posts
    1,006
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by Zarin Denatrose View Post
    Is it safe to assume you're working in firefox?
    Firefox 3.6.8 - If I enable firebug all firefox hangs... so I have just disable it.

    So:

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

    echo 
    json_encode($response);
    Quote Originally Posted by Zarin Denatrose View Post
    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,
    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).

    Quote Originally Posted by Zarin Denatrose View Post
    and echoing 'ola' before it might cause problems there.
    Ok... because we are sending something to the browser before the other things that we are really send it right?

    Quote Originally Posted by Zarin Denatrose View Post
    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:
    Code:
    $.post("data.php", function(response) {
    	$('body').append(response);
    });
    We should append our data. Ok. :s Why doesn't a simple alert work here?


    Thanks a lot,
    M&#225;rcio

  5. #5
    SitePoint Addict Zarin Denatrose's Avatar
    Join Date
    Jan 2009
    Location
    Surrey BC, Canada
    Posts
    309
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    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!

  6. #6
    SitePoint Wizard
    Join Date
    Feb 2009
    Posts
    1,006
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks a lot really.

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


    One (3) last question if you don't mind, please:

    1)
    Is
    Code JavaScript:
    for(x in response.data)
    a shorter version of:
    Code JavaScript:
    for (var x = 0; x < response.data.length; x++)
    ?

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

    3)
    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

  7. #7
    SitePoint Addict Zarin Denatrose's Avatar
    Join Date
    Jan 2009
    Location
    Surrey BC, Canada
    Posts
    309
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    1. Pretty much. Your method works too, both have their flaws. What you should really do is this:
    Code JavaScript:
    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.

    2. 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.

    3. 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:
    Code JavaScript:
    if(response.data){
     
    for (var x = 0, dataLength = response.data.length; x < dataLength; x++){
    	$('#data').append(response.data[x]+'<br>');
    }
     
    }

  8. #8
    SitePoint Wizard
    Join Date
    Feb 2009
    Posts
    1,006
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by Zarin Denatrose View Post
    3. 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:
    Code JavaScript:
    if(response.data){
     
    for (var x = 0, dataLength = response.data.length; x < dataLength; x++){
    	$('#data').append(response.data[x]+'<br>');
    }
     
    }
    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...
    Last edited by oikram; Aug 25, 2010 at 04:31. Reason: added one more questionS

  9. #9
    SitePoint Addict Zarin Denatrose's Avatar
    Join Date
    Jan 2009
    Location
    Surrey BC, Canada
    Posts
    309
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Oh! Yes, data comes from the JSON object you created in PHP on the server.

    PHP Code:
    $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.

  10. #10
    SitePoint Wizard
    Join Date
    Feb 2009
    Posts
    1,006
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks a lot. I rest my case.

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

    M&#225;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.

  11. #11
    SitePoint Addict Zarin Denatrose's Avatar
    Join Date
    Jan 2009
    Location
    Surrey BC, Canada
    Posts
    309
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    No problem. I'm here to help!
    If you need any more assistance, feel free to PM me.

    -Zarin


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •