intA
intA

Reputation: 2671

Passing JavaScript array using AJAX

I'm very new to ajax and I'm trying to pass an array that I have created in javascript called markers over to a PHP page when the user clicks the submit button. At the time of submission the array exists and is within scope. The code below is what is trying to do that. When I click the submit button I get sent to the php page and "failed" is printed (part of my code) meaning the array was not passed. I believe the error occurs in the ajax code and I'm not sure where it is coming from, any help is greatly appreciated!

The javascript/ajax stuff:

function submit_tour(){
    var input = JSON.stringify(markers);
    //var input = $(this).serialize();
    var sent = $.ajax({
            type: "POST",
            data: input,
            dataType: 'JSON',
            url: "test_portal2.php"
            }).done(function() {window.alert("done");})
            .fail(function() {window.alert("failed");});
    window.alert("" + input);
}

The HTML button that is supposed to send the array:

<form name="toursubmit" action="test_portal2.php" onsubmit="submit_tour()">
<input type="submit" value="Submit">
</form>

The PHP that catches it (in the test_portal.php file):

$ans = json_decode($sent);
echo $ans;
if ($ans != NULL){
    echo "works";
    echo $ans;
}
else {
    echo 'failed';
}

Upvotes: 1

Views: 173

Answers (3)

Mike Brant
Mike Brant

Reputation: 71384

A couple of things to point out.

First, you need to prevent the default POST action within your submit_tour() function, otherwise the synchronous POST will happen.

Second, you need to specify the contentType value in your AJAX call as application/json.

Third, if you are actually POSTing JSON to PHP and using application/json as the ContentType, then you will need to get the JSON data in PHP by accessing the raw input like this:

$json = file_get_contents('php://input');
$obj = json_decode($json);

This is because $_POST is only auto-generated for form-encoded content types.

Upvotes: 3

MasNotsram
MasNotsram

Reputation: 2273

You don't need this in a form tag. The code is submitting the form and not running the JS.

Remove the form tag, or put this: submit_tour(); in onsubmit on the form instead, and return false.

Upvotes: 0

Hanky Panky
Hanky Panky

Reputation: 46900

When you send

var input = JSON.stringify(markers);

And markers has no value

<input type="hidden" id="markers" name="markers">     // No value anywhere

Then it will surely be Null :)

Also do you populate your $sent variable from a value in $_POST ? don't see that happening

Upvotes: 1

Related Questions