Pass data from jQuery to PHP for an ajax post

后端 未结 3 1989
闹比i
闹比i 2020-11-29 09:45

Hello I am a newbie working with jQuery and Ajax. I am trying submit data to the server using Jquery POST method. And the data that I am passing is a string. Now I am unable

相关标签:
3条回答
  • 2020-11-29 10:17

    The data param is supposed to be an object that has keys and values.

    var data = {
        hiddenContact: document.getElementById('hiddenContact').value
    }
    $.post('/callcenter/admin/postContacts', data);
    

    Then in PHP you can retrieve it like this:

    $hiddenContact = $_POST["hiddenContact"];
    

    I'm not a big CakePHP user but I believe the CakePHP version is like this:

    $hiddenContact = $this->params["hiddenContact"];
    
    0 讨论(0)
  • 2020-11-29 10:22

    With jQuery post you can define a callback function which is executed when the data is returned:

    $.post('/callcenter/admin/postContacts', data, function(returnedData) {
        // do something here with the returnedData
        console.log(returnedData);
    });
    

    The data should be in the form:

    {name: 'value', anotherName: 'another value'}
    

    which equates to the post names on the PHP end accessible in plain PHP like this:

    echo $_POST['name'];           # prints "value"
    echo $_POST['anotherName'];    # print "another value"
    
    0 讨论(0)
  • 2020-11-29 10:28
    //javascript
    if(step==1)
    {
       var data = {'MyFieldName':document.getElementById('hiddenContact').value};
       $.post('/callcenter/admin/postContacts', data, function(returnData){
          alert('The server said ' + returnData);
       });
    }
    
    //read the post in php
    <?
       echo 'Your ajax post data was '. $_POST['MyFieldName'];
    ?>
    
    0 讨论(0)
提交回复
热议问题