3

I have a JSON array that I'm passing to PHP. Eventually I'll be passing and receiving alot more from my PHP file but for the moment this is it. Right now it's recieving 1 array and sending back that same array, no problem. I can loop through the data in Javascript but how do I loop through the array I pass to my PHP file? I get errors with foreach and a for loop didn't seem to help any. Suggestions?

Javascript

var fullName = ["John Doe", "Jane Doe"];

$(window).load(function(){
    getList();
});

function getList(){
    $.getJSON(
        "names.php",
        {names : JSON.stringify(fullName)},
        function(data) 
        {
            for(var i = 0; i < data.test.length; i++)
            {
                window.alert(data.test[i]);
            }
        }
      );
}

PHP

<?php
    $names=json_decode($_REQUEST['names']);

foreach($names as $name)
{
    echo $name;
}

    $data['test'] = $names;
    echo json_encode($data);

The foreach errors out on the foreach line telling me "Warning: Invalid argument supplied for foreach()"

25
  • Which error do you get with that for-loop? And also please post the received JSON (inspect it at the network panel of your dev tools) Commented Feb 26, 2013 at 21:11
  • 1
    In your PHP, $names should be an array. What's the problem with reading it? Commented Feb 26, 2013 at 21:13
  • 1
    Invalid argument? To what? Is it a PHP or a JS error? Please post the exact error message, including the line it points to. Commented Feb 26, 2013 at 21:14
  • 2
    var_dump($names) - is it an array? is there anything? Commented Feb 26, 2013 at 21:26
  • 1
    success in jquery just means that the script was called without any problems. It does not mean there are no errors in the script itself. Commented Feb 26, 2013 at 21:29

6 Answers 6

1

json_decode() doesn't return an array. To get it to do so you'd need to do json_decode($_REQUEST['names'], true)

http://php.net/manual/en/function.json-decode.php

Sign up to request clarification or add additional context in comments.

1 Comment

that's true, but as the sample data looks like it's already an array.
0

There seems to be something strange going on when using:

{names : JSON.stringify(fullName)}

As you are sending key - value pairs using GET or POST, you probably need to encode the value correctly.

You could do that using:

{names : encodeURIComponent(JSON.stringify(fullName))}

1 Comment

Still no luck with that. My var_dumps still show NULL. Maybe I need to use a different ajax method.
0

EDIT: jQuery is being insane again.

$.getJSON("names.php?names=" + encodeURIComponent(JSON.stringify(fullName)), function(data)
        {
                for(var i = 0; i < data.test.length; i++)
                {
                        window.alert(data.test[i]);
                }
        }
);

The problem was it was adding each item in the array as seperate value to URI.

1 Comment

No luck with this either. It even breaks the alerts that would otherwise work (even though it shouldn't)
0

Try

$names=json_decode($_POST['names']); // or $_GET

instead of

$names=json_decode($_REQUEST['names']);

Sometimes $_REQUEST can be empty because of php.ini conf. SEE request_order

Comments

0

Try this, In your javascript function replace below line with

 {names : JSON.stringify(fullName)},

with

"{names :"+ JSON.stringify(fullName) +"}",

debug test

var fullName = ['John Doe', 'Jane Doe'];
console.log({names : JSON.stringify(fullName)});
// gives Object { names="["John Doe","Jane Doe"]"}

but with

console.log("{names :"+ JSON.stringify(fullName) +"}");
// gives {names :["John Doe","Jane Doe"]}

// so i guess second is correct json string to pass

3 Comments

When I use the console.log as suggested I do get {names :["John Doe","Jane Doe"]} but in my PHP i'm still getting Nulls when I var_dump.
Ok, try one step back, we will remove full name array for a time being and just pass {names : "my test name1"}, and check if you get correct value in php script. if you get correct value that means we have identified an issue with array to json string. otherwise there some other issues
Still nothing in PHP, all nulls. There gotta be something really wrong but I've used a similar script before. I'm just going to try from scratch with the ajax method mentioned below...
0
/* client-side */
$.ajax({

   /* the request's method: */
   type: 'GET',

   /* the request's location: */
   url:'/names.php',

   /* the request's fields: */
   data: JSON.stringify({names: fullName}),

   /* the request's content-type : */
   contentType: 'application/json; charset=utf-8',

   /* the response's content-type: */
   dataType:'json',

   /* the callback function */ 
   success: function(json){

     if(json.length > 0){
         $.each(json, function(i, v){

            console.info(v);

         });
      }
      else {
         alert('wtf?!');
      }
});

/* server-side */
$req=array_merge($_GET, $_POST);

// die(print_r($req));

$names=json_decode($req['names']);
header('content-type: application/json; charset=utf8;');
echo json_encode($names);

Alternatively one could set the request-method for the request, I'm just a little lazy and with that array_merge() it just doesn't matter if the request was a POST or GET (well, function $.ajax defaults to GET). Best practice is to use FireBug and checkout it's net-panel, especially the XHR tab. Probably the question should have been: "How to use a XHR debugger?" because there's nothing tricky about this at all.

It seems that the jQuery API has been slightly updated (see the Deprecation Notice):

http://api.jquery.com/jQuery.ajax/

https://getfirebug.com

6 Comments

If FireBug doesn't work ... you must be missing something fundamental. This code and above posted codes should both "work" - at least log anything to JS console.
besides "doesn't work" isn't considered an error description... while you're not telling where exactly the request bugs out - this is only guessing around. at least it's an example how to create the proper headers for request & response... and FireBug (should) display in detail what happens.
Have you ever used a JS debugger, seriously?? It's all somewhat obvious when setting watches for certain variables and some breakpoints, e.g. on callback.
just set a watch on $ or jQuery ... and you can inspect jQuery itself
I suppose I must admit that the problem doesn't seem to be with the Jquery at all and with the PHP. Good rant through.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.