Cesar Cesar - 11 months ago 60
jQuery Question

Manage form-data + other variable sent via ajax to php

My question is probably basic, but there is the question:

I have a javascript function which sends an array via ajax to process some information...

var second = $('form.contact').serialize();
var arry = {keystatus: varId, keyname: second}

In php, I added the data sent via ajax a array and wrote an echo to see in ajax success, displaying via console.log.

What do I get:

enter image description here

My php script:

$name = strip_tags($_POST['keystatus']);
$email = strip_tags($_POST['keyname']);

$teste['nome'] = $name;
$teste['email'] = $email;

echo json_encode($teste);

I needed to find a way to get separate, for example:

$_POST['keyname']['nome'] -> (in this example) discovery
$_POST['keyname']['email'] -> discovery@discovery.com
$_POST['keyname']['usuario'] -> discovery

Answer Source

You are currently adding the form data as a serialized string to an object, which you send. That's why it looks the way it does.

You can either build a new object with all data and send that object with ajax:

var data = {
    keystatus: varId,
    keyname: {
        nome: $("#the_nome_input").val(),
        email: $("#the_email_input").val(),
        usuario: $("#the_usuario_input").val()

Or you can add the extra value (since it only seems to be one) as a hidden input field in your form:

// Add this to the form
<input type="hidden" value="" name="keystatus" id="keystatus" />

// In your js, add
$("#keystatus").val(varId); // Sets the value
var data = $("form.contact").serialize();

...now you can send data to your back end using ajax.

If you want to fetch your data like this: $_POST['keyname']['nome'] and use the second alternative, then you need to rename your input fields to: name="keyname[nome]", name="keyname[email]" and name="keyname[usuario]".

That will give you the correct data structure and values.