So,I send an array of inputs:
<input type="text" placeholder="Question" name="question[]" value="" />
<input type="text" placeholder="Question" name="question[]" value="" />
with this Jquery code:
$.post("function.php",{Question:$("[name^='question']").serialize()},function(data){
$("#construct").append(data);
alert('done');
});
but when I try to echo the variables of array it prints incorrect
PHP(function.php):
$Question=htmlentities($_POST['Question'],ENT_QUOTES,"UTF-8");
echo $Question[0]."<br>";
echo $Question[1]."<br>";
Now imagine that we enter "Hello" and "Bye" in the input So it should return "Hello" and "Bye" but it returns "q" and "u" instead.
The var_dump out put is:
string(39) "question%5B%5D=Hello&question%5B%5D=Bye"
Edit 1
if I use .serialize() I always get "q" and "u" but if I use .val() I get the first and second letter of each word
Edit 2
I even tried the PHP code without htmlentities() but the result is the same as before.
1 Answer 1
You serialized your input in JavaScript so the input coming in PHP is a string, not an array. So you need to decode it into an array. Using JSON is a good approach.
EXAMPLE for the lazy:
JavaScript
var normalArray = $('#FormID').serializeArray();
var jsonArray = JSON.stringify(normalArray);
$.post("function.php",{
data: jsonArray
});
PHP
$normalArray = json_decode($_POST['data'], true);
This example is not tested, but it should work in general.
8 Comments
.serialize()??JSON.stringify( my_array ) in javascript my friend. And in PHP you do json_decode($_POST['question'], true). Here: stackoverflow.com/questions/6937144/… php.net/manual/en/function.json-decode.php JSON.stringify() in Jquery.post??
var_dump(($_POST['Question']);in your questionvar_dumpoutput