Hi I have problems with the script below. The problem I think lies on data that need to be sent to php via AJAX.
jQuery
$(\'.send\').live(\"click\",
You need to JSON encode the data being sent.
It should look something like: '{"id":"' + $(this).attr('id') + '"}'
You can use ,
$('.send').click(function(){
Insted of
$('.send').live("click", function(){
There is an error showing
TypeError: Object [object Object] has no method 'live'(live is deprecated)
There are a few issues present in the code in the question.
Don't use .live()
. It was deprecated in jQuery 1.7 and removed entirely in jQuery 1.9 (the latest release version). Instead, use .on()
:
$('.send').on('click', function() {
...
});
Or, if you actually need the event delegation:
$(document).on('click', '.send', function() {
...
});
When setting the data
property in your object literal passed as an argument of $.ajax()
, you have two options: a string or an object literal. So either:
data: {id: this.id},
or
data: 'id=' + this.id,
Note that I'm using this.id
, not $(this).attr('id');
. Why? Because it avoids unnecessary usage of jQuery, and because .attr()
isn't the correct function - you want the id
property, so you should use .prop()
(though, again, don't use jQuery unless you need to).
Finally, you haven't closed the call to .click()
, so you need to add a );
to the end of your posted code.
The entire thing should look something like this:
$('.send').on("click", function () {
$.ajax({
url: 'foobar.php',
type: 'post',
data: 'id=' + this.id,
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success: function (data) {
switch (data.status) {
case "a":
alert(data.text);
break;
case "b":
alert(data.text);
break;
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("error: " + textStatus);
}
})
});
I will put my comment as an answer.
Apart from using a deprecated jQuery API, what others didn't point out is the following:
What you are doing in the below line:
contentType: 'application/json; charset=utf-8',
is that you are promising the server that the HTTP entity will be a JSON-string, which is not the case. It is actually the usual percentile-encoded string. (a=b&c=d&e=f
).
If you remove that line, the browser sends a default value Content-Type as application/x-www-url-form-encoded
. That would trigger PHP to parse the HTTP entity as such and give you as the $_REQUEST
array properly populated.
change this
data: 'id=' + $(this).attr('id'),
to
data: {id : $(this).attr('id')},
also use on
here, live
is deprecated
$('.send').on("click", function(){