kuan
kuan

Reputation: 13

php: How to access the ajax data object

I have a silly question, how do I get the post value (

 $.ajax({
 type: "POST",
 url: "b.php",
 data: function (data) { 
                data.firstName = $('#firstName').val(); 
                data.lastName = $('#lastName').val(); 
                }
});

I guess it's not $_POST['firstName'] or $_POST['data']...

Thanks for helping

Upvotes: 0

Views: 538

Answers (2)

kuan
kuan

Reputation: 13

=.=" It's working now.

ajax:

 $.ajax({
 type: "POST",
 url: "b.php",
 data: { 
        firstName = $('#firstName').val(),
        lastName = $('#lastName').val()
        }
});

php

echo $_POST['firstName'] . "+" . $_POST['lastName'];

Upvotes: 1

Kris Osterhout
Kris Osterhout

Reputation: 16

Your $_POST object will contain an array with the name 'data', as you are passing a JavaScript object.

I would recommend creating a JavaScript object and then using JSON.stringify() to pass to PHP. Try something like this:

JavaScript/jQuery

let ajaxData = {
   firstname: $('#firstName').val(),
   lastName: $('#lastName').val()
};

let ajaxString = JSON.stringify(ajaxData);

$.ajax({
 type: "POST",
 url: "b.php",
 data: { data: ajaxString }
});   

Then, in your PHP controller, you would do something like this:

PHP

$ajaxData = $_POST['data'];
$userData = json_decode($ajaxData, true); //Decodes JSON data and creates associative array.

You can check the structure using vardump($userData);

Upvotes: 0

Related Questions