Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass data from jQuery to PHP for an ajax post

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 to understand how do I pass the data and how do I retrieve the data. I have tried searching for articles for my problem, but I have found none. I believe my problem is very basic.

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

Now I'll post the code for my postContacts action, which isn't a big thing.

function postContacts()
{
$this->autoRender = false;
echo '<script>console.log("post contacts");</script>';
}

But I am confused as to how the data has to be retrieved. Any help is appreciated. I am using cakePHP, so I have had to use autoRender=false; which makes the view optional.

like image 241
macha Avatar asked Nov 17 '10 22:11

macha


People also ask

How pass data from JavaScript to PHP using AJAX?

ajax({ type: "POST", url: 'logtime. php', data: "userID=" + userID, success: function(data) { alert("success!"); } }); }); }); <? php //logtime. php $uid = isset($_POST['userID']); //rest of code that uses $uid ?>

Can jQuery and AJAX be used together?

jQuery provides several methods for AJAX functionality. With the jQuery AJAX methods, you can request text, HTML, XML, or JSON from a remote server using both HTTP Get and HTTP Post - And you can load the external data directly into the selected HTML elements of your web page!

Can AJAX use POST?

post() makes Ajax requests using the HTTP POST method. The basic syntax of these methods can be given with: $. get(URL, data, success); —Or— $.


2 Answers

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"
like image 132
Marcus Whybrow Avatar answered Sep 22 '22 16:09

Marcus Whybrow


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"];
like image 37
mike Avatar answered Sep 22 '22 16:09

mike