Buck
Buck

Reputation: 187

Serialize an ajax array

I have an array make from some input value get with jQuery like this

var ingredient = [];
text.each(function(){
    ingredient.push($(this).val());
});

and send with ajax like this

$.ajax({
    url: "update_recipe.php",
    type: "post",
    data: ingredient,
    dataType: "html",
    success : function(code_html, statut){
        console.log(code_html);
        console.log(statut);
    },
    error : function(resultat, statut, erreur){
        console.log("La requête n'a pas aboutie...");
        console.log(resultat);
        console.log(statut);
        console.log(erreur);
    }
    });

but when i need to get the array with php, $_POST is NULL...
Do you have an idea of how can i send this array ?

thanks

Upvotes: 1

Views: 1770

Answers (2)

guest271314
guest271314

Reputation: 1

You can create a query string having "key=value" pairs where "key" is the name attribute value of the element, instead of pushing only value to an array.

var ingredient = "";

text.each(function(i) {
    ingredient += this.name + "=" + this.value + (i < text.length ? "&" : "");
});

Upvotes: 1

siddhesh
siddhesh

Reputation: 563

//with ajax

//JS

var data = $("#form :input").serializeArray();
data = JSON.stringify(data);
post_var = {'action': 'process', 'data': data };
$.ajax({.....etc

// PHP

$data = json_decode(stripslashes($_POST['data']),true);
print_r($data); // this will print out the post data as an associative array

Upvotes: 0

Related Questions