0

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

2 Answers 2

1

=.=" It's working now.

ajax:

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

php

echo $_POST['firstName'] . "+" . $_POST['lastName'];
Sign up to request clarification or add additional context in comments.

Comments

0

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);

4 Comments

Hi Kris, is there any way for a PHP to get this object 'data'? data: function (data) { data.firstName = $('#firstName').val(); }
Hi Kuan, see the PHP example I gave toward the end. You would declare the variable $ajaxData and set it equal to $_POST['data']. This is a JSON-encoded string. Then, you would call the native PHP function json_decode() and pass in the variable, like this: $userData = json_decode($ajaxData, true); This creates an associative array with the data you gave it from the POST request.
Hi Kris, i find out the ans, it works this way too: data: { firstName = $('#firstName').val(), lastName = $('#lastName').val() }
Yes, this creates a single JavaScript object and you would then be able to access it in PHP by using $_POST['firstName']. However, I still recommend encoding your data in JSON as this makes it much easier to work with larger datasets you may be sending to the backend. For small data sets like this, you can send a single object, but you will reach difficulty if you need to send more complex datasets.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.