skip to Main Content

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


  1. Chosen as BEST ANSWER

    =.=" It's working now.

    ajax:

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

    php

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

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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search