Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have 2 pages which are file.xhtml and submit-exec.php. I am passing my javascript array from the xhtml file to the php using ajax. I found several tutorials online but none of them settled my problems. I am still wondering is it possible any problem with xhtml?

the array:

var array = [];
array.push({ name: "name", value: document.forms["form"]["name"].value});
array.push({ name: "email", value: document.forms["form"]["email"].value});
array.push({ name: "mobile", value: document.forms["form"]["mobile"].value});

file.xhtml

$.ajax({ //to run exec in background
    type: 'POST',
    url: 'submit-exec.php',
    data: {'data' : array},

    success: function(){
        alert("ok");
    }
});

submit-exec.php

$myArray = $_POST['data'];

print_r($myArray);

Anyone can help me?

Thanks!

share|improve this question
3  
You've posted some code that, aside from array being undefined, works. What's the problem? What happens that differs from what you expect to happen? –  Quentin Oct 14 at 6:22
 
You need to JSONify your data before sending (data: {'data' : array.serialize()} - I think) and then convert back to an object that php understands (json_decode($_POST{'data']) ). –  jeff Oct 14 at 6:44
add comment

closed as unclear what you're asking by Quentin, Johannes Kuhn, Chris Kempen, Phil Hannent, Pavel Janicek Oct 14 at 10:20

Please clarify your specific problem or add additional details to highlight exactly what you need. As it's currently written, it’s hard to tell exactly what you're asking.If this question can be reworded to fit the rules in the help center, please edit the question.

2 Answers

up vote 1 down vote accepted

You can simply send an object (I don't change the variable name "array" to fit your ajax, but you definitily should)

var array = {name: document.forms["form"]["name"].value, email: document.forms["form"]["email"].value, mobile: document.forms["form"]["mobile"].value}  

no need to convert to string

share|improve this answer
add comment

Object can't be send through POST. So, to make your code works you must convert your array to string & convert it back to array at server side. For example:

data: {'data' : array.join(',')},

And at server side, convert it back to array by using explode:

$myArray = explode(",", $_POST['data']);
share|improve this answer
add comment

Not the answer you're looking for? Browse other questions tagged or ask your own question.