0

I want to pass an array from Jquery to PHP.

My jquery:

var jsonFormat = JSON.stringify(myArray);

$.post("myPHPFile.php", jsonFormat).done(function(data) {
    $('.foo').append(data);
});

I see myArray in the browser console as expected

My PHP:

<?php

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, DELETE, PUT, OPTIONS');
//echo json_decode(array('success' => 'yes'));


if ($_SERVER['REQUEST_METHOD']=="POST"){

    $jsonFormat = $_POST['jsonFormat']; 

    echo $jsonFormat;

}
?> 

In the browser console I get status 200 ok, but no response. I am expecting to see the array as a response.

1
  • try to print_r($_POST) and see the parameters that posted, actually there might be no parameter by this jsonFormat as you expect Commented Jul 28, 2013 at 8:13

2 Answers 2

2

You have passed PHP a request with a JSON body, but you are trying to treat it as application/x-www-form-urlencoded data, not application/json data.

Use $.post("myPHPFile.php", { myData: myArray }) and $_POST['myData'] instead. jQuery will encode the data as application/x-www-form-urlencoded then (it will even default to using PHP's unusual naming conventions).

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

Comments

0

I would do something similar to this:

Jquery

$.post("myPHPFile.php", myArray.serialize(), function(data) {
    $(".foo").append(data);
}, "json");

myArray.serialize() turns your array into a string that will be posted to your PHP file like this: var1=text&var2=text

PHP

<?php
    $var1 = $_POST['var1'];
    $var2 = $_POST['var2'];
    // repeat for each variable being posted.

    // your php code that does whatever it will do with the variables.

    // data to return to Jquery will be put back into an array like this:
    $return['var3'] = $var3;
    $return['var4'] = $var4;

    echo json_encode($return);
    unset($_POST);
?>

The data returned is datatype = json which can be accessed in your Jquery code like this: data.var3 data.var4

2 Comments

I am getting serialize is not a function
Well it is a function, so maybe you were using it wrong. Certainly doesn't require a downvote, because the code does work. I use it to submit form variables in my jquery scripts. Reference: api.jquery.com/serialize

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.