-2

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.

NavidIvanian
  • 347
  • 5
  • 15

1 Answers1

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.

P. Jensen
  • 34
  • 4
  • So,What can I use instead of `.serialize()`?? – NavidIvanian Sep 06 '15 at 15:20
  • use `JSON.stringify( my_array )` in javascript my friend. And in PHP you do `json_decode($_POST['question'], true)`. Here: http://stackoverflow.com/questions/6937144/sending-javascript-object-to-php-via-ajax http://php.net/manual/en/function.json-decode.php – P. Jensen Sep 06 '15 at 15:35
  • So you stringify your data in JavaScript to Json, send it to PHP, decode the Json into an array, go mark P. jensen's anwser as a good anwser. And he saw that everything was well. – P. Jensen Sep 06 '15 at 15:38
  • Dude, don't be lazy. If you don't learn it by researching and writing it yourself, you will never remember it. Use the links I gave you. – P. Jensen Sep 06 '15 at 15:39
  • Can I use `JSON.stringify()` in Jquery.post?? – NavidIvanian Sep 06 '15 at 15:41
  • Made an example, try to adopt it into your own project. – P. Jensen Sep 06 '15 at 15:51
  • you know,my form includes several inputs and I want to send the inputs with name question into `function.php`. I hope you understand my purpose.So that I think it isn't a good way to send the whole form to `function.php`. btw I edited my post.Please take a look at it again – NavidIvanian Sep 06 '15 at 15:56
  • Selectors should work in jQuery aswell `$(':input')` and such. Does not have the anwser right now, will maybe anwser later. – P. Jensen Sep 06 '15 at 16:05