0

I used this Code to send a form + a variable to a php-script.

function upload() {
  var test = "test";
  var infos = $('form').serialize() + '&' + test;
  $.post("ajax.php", { infos: infos }).done(function (data) {
    alert(data);
  });
}

now the PHP-Code:

$data = $_POST['infos'];
echo $data;

returns: formfield1=value1&formfield2=value2&formfield3=value3&test

All values are in this variable... But how i can use them seperatly with PHP?

For example:

$data = $_POST['formfield1'];

didn't worked :(

1
  • explode() Commented Apr 29, 2015 at 12:45

4 Answers 4

2

Use jQuery's serializeArray(). It will return you with array of objects that contain 2 properties: name and value. You can then parse it and pass it as data.

It could look like this

var formdata = = $('form').serializeArray();
var infos = { };
for (var i = 0; i < formdata.length; i++) {
    infos[formdata[i].name] = formdata[i].value;
}

// To add separate values, simply add them to the `infos`
infos.newItem = "new value";

$.post("ajax.php", infos).done(function (data) {
    alert(data);
});

Then in PHP, you'll retrieve values using $_POST["formfield1"].

Sign up to request clarification or add additional context in comments.

1 Comment

Simply add them to the infos object infos.testItem = "test"
0

Try to explode them with -

$data = $_POST['infos'];
$form_data = explode('&', $data);
$posted_data = array();

foreach ($form_data as $value) {
    list($key, $val) = explode('=', $value);
    $posted_data[$key] = $val;
}

var_dump($posted_data);

Comments

0

You can use the parse_str method to convert the query string into an array.

In your case, you can do something like this:

parse_str($_POST['infos'], $data); // $data['formfield1'], $data['formfield2'], $data['formfield3'] have the values you need

More details here: http://php.net/manual/en/function.parse-str.php

Comments

0

// here is the jquery part

 function upload() {
      var test = "test";
      var infos = $('form').serialize() + '&' + test;
      $.post("ajax.php", { infos: infos },function (data) {
        alert(data); // the fetched values are alerted here.
      });
    }

//the php part is here

$data = $_POST['infos'];
$field_seperator='&';
$val_seperator='=';
$form_data_val=explode($field_seperator,$data);
    foreach($form_data_val AS $form_vals){
       $vals=explode($val_seperator,$form_vals);
       echo $vals[1];// here the value fields of every form field and the test is fetched.
    }

try this .

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.