2

I'm tring to post an array to PHP file using JSON. It does not work. The problem is nothing happens. If I decomment datatype:"json" then I get the alert (but without data).

This is my jquery code

var arr = new Array();
arr.push('1','Brussels|25');
arr.push('2','Antwerp|40');
$.ajax({
  type: "POST",
  contentType: "application/json; charset=utf-8",
  url: "jsondecode.php",
  data: JSON.stringify(arr),
  dataType: "json",
  success: function(data){alert(data);},
  failure: function(errMsg) {
    alert(errMsg);
  }
});

And this is my PHP code (jsondecode.php);

 <?php
 $array = json_decode($_POST["arr"]);
 foreach($array as $el){
    $el_array=explode('|',$el);
    echo"City=".$el_array[0]." And Age = ".$el_array[1]."";
 }

 ?>

Does somebody know a useful tutorial on this?

3
  • 1
    What does "does not work" mean exactly? Commented Aug 21, 2013 at 10:12
  • What do you mean with "does not work"? Commented Aug 21, 2013 at 10:12
  • Nothing happens. If I uncomment dataType:"json", I get the alert but without the data Commented Aug 21, 2013 at 10:34

4 Answers 4

4

You have to post the data in this format to retrieve like $_POST["arr"]

data: { arr : JSON.stringify(arr) },
Sign up to request clarification or add additional context in comments.

4 Comments

I did now but $_POST["arr"] is still empty
@MichaelV Check in console what data is sending to jsondecode.php.
Indeed, unless I delete the dataType:'json' line no data is sent
@MichaelV yes you have to delete this line because you are receiving data in text format not in JSON format, dataType:'json' is used to get the response in JSON format.
3

What the heck are you trying? It looks as if you are trying to put key-value-pairs to the JavaScript-Array with arr.push('1', 'Brussels|25'); expecting an array containing "Brussels|25" under the key "1" - but watch out, you are creating this array: ["1", "Brussels|25", "2", "Antwerp|40"].

If you want to send json, send json-data:

var arr= [{  
    "city" : "Brussels",  
    "age" : 25  
},{  
    "city" : "Antwerp",  
    "age" : 40  
}];  

then your ajax call:

$.ajax({
   type: "POST",
   url: "jsondecode.php",
   data: {arr: JSON.stringify(arr)},
   success: function(data){
        console.log("success:",data);},
   failure: function(errMsg) {
        console.error("error:",errMsg);
   }
});

So you don't need to explode the data server-sided.

The server-sided script:

<?php
$data = json_decode($_POST["arr"]);
// will echo the JSON.stringified - string:
echo $_POST["arr"];
// will echo the json_decode'd object
var_dump($data);
//traversing the whole object and accessing properties:
foreach($data as $cityObject){
    echo "City: " . $cityObject->city . ", Age: " . $cityObject->age . "<br/>";
}
?>

Hope, this helps you now.

@edit: By the way, use console.log() or console.error() instead of alert. Alert will cause scripts to pause until you click on ok and you cannot see objects in an alert.

@2nd edit: the script is now tested, I removed unnecessary code and added the server-sided code

6 Comments

OK I used this code I just changed data: {arr: JSON.stringify(arr)}, to data{:jsonarry: JSON.stringify(arr}, but still it doesn't work, nothing is written to the console logo When I deleted the data Type: "json" line I get a success response (but no data)
Have you adjusted your php-script to your change? Try echoing something in the jsondecode.php - file to be sure, that you are loading the correct script and it definitely echoes something.
I put following in the php script echo"postarr=".$_POST["jsonarray"]; in console I only see the message 'sucess: postarr=' so without the data
This shows you, that there is no "jsonarray" - key in $_POST. Try a var_dump($_POST); in your php script.
I get an empty array as response "success: array(0) { }"
|
1

Replace :

$array = json_decode($_POST["arr"]);

By:

 $array = json_decode($_POST["arr"], true);

Comments

0

Worked for me:

JS:

$.ajax({
    type: "POST",
    contentType: "application/json; charset=utf-8",
    url: "jsondecode.php",
    data: JSON.stringify({"1": "Brussels", "2": "Antwerp"}),
    success: function(data){alert(data);},
    failure: function(errMsg) {
        alert(errMsg);
    }
});

PHP:

<?php
$p = file_get_contents('php://input');
$x = json_decode($p, true);
echo $x["1"];
?>

Comments

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.