I have the below function in my WordPress functions file, and if I run it as below without the two parameters it works fine, but when I pass the parameters the error handler in the jQuery returns status 500.
If I don't pass the parameters to the PHP function I get status 200 from jQuery, but it's coming from the error handler, and not from the success handler. Why so?
function subscribe_funk(){//$payment_method, $customer_handle){
return "This is a test";
die();
}
It gets called from this ajax:
function subscribe(data) {
jQuery.ajax({
url: PT_Ajax.ajaxurl,
type: "POST",
data: {'action': 'subscribe_funk', 'payment_method': data.payment_method, 'customer_handle': data.customer},
cache: false,
dataType: 'json',
beforeSend: function(){
console.log('Before send subscribe');
},
complete: function(){
},
success: function (response) {
console.log('Message from success handler: ');
console.log(response);
},
error: function(xhr, status, error){
console.log("Message from error handler:")
var errorMessage = xhr.status + ': ' + xhr.statusText
console.log(errorMessage);
}
});
}
Your function expects 2 parameters, however WP/ajax is not passing them directly.
You need to fetch them from $_POST array yourself:
function subscribe_funk(){
$payment_method = $_POST['payment_method'];
$customer_handle = $_POST['customer_handle'];
return "This is a test";
die();
}
Also, you may want to sanitize the post data with sanitize_text_field() or similar function.
Here is a relevant thread in WP StackExchange: how to pass parameters from jQuery ajax to a PHP function
Related
I am trying to send form data using ajax. But there's an error in ajax operation and only "error" callback function is executed.
Here's what I tried:
$("#issue_submit").click(function (e) {
console.log("clicked on the issue submit");
e.preventDefault();
// Validate the form
var procurementForm = $("#it_procuremet_form");
if($(procurementForm).valid()===false){
return false;
}
// Show ajax loader
appendData();
var formData = $(procurementForm).serialize();
// Send request to save the records through ajax
var formRequest = $.ajax({
url: app.baseurl("itprocurement/save"),
data: formData,
type: "POST",
dataType: "json"
});
formRequest.done(function (res) {
console.log(res);
});
formRequest.error(function (res, err) {
console.log(res);
});
formRequest.always(function () {
$("#overlay-procurement").remove();
// do somethings that always needs to occur regardless of error or success
});
});
Routes are defined as:
$f3->route('POST /itprocurement/save', 'GBD\Internals\Controllers\ITProcurementController->save');
Also I added :
$f3->route('POST /itprocurement/save [ajax]', 'GBD\Internals\Controllers\ITProcurementController->save');
I tried returning a simple string to the ajax call at the controller class.
ITProcurementController.php :
public function save($f3)
{
echo 'Problem!';
return;
$post = $f3->get('POST');
}
But only 'error' callback is executed. I cannot locate what is wrong. Please Help.
You are specifying that you expect json back:
// Send request to save the records through ajax
var formRequest = $.ajax({
url: app.baseurl("itprocurement/save"),
data: formData,
type: "POST",
// Here you specify that you expect json back:
dataType: "json"
});
What you send back is not json:
echo 'Problem!';
return;
This is an unquoted string, which is not valid json.
To send valid json back, you would need:
echo json_encode('Problem!');
return;
You could also remove the dataType attribute, depending on your needs.
I'm using jquery multiselect plugin and I want to perform an ajax request on a select/deselect event.
My problem: When I send the request to the php file, ISSET(VAR) returns every time false so that I can't pass variable to the php file.
But Firebug extension for Chrome/Firefox shows me that the POST value is set right POST -> "Response myvar" but GET is empty.
How do I pass the variable to the php file?
(I've searched arround the web but found nothing.)
My script, where this pointer is from the multiselect plugin and afterSelect returns if a object is selected
afterSelect: function()
{
this.qs1.cache();
this.qs2.cache();
count++;
var dataString = "count=" + count;
if ( count > 0 )
{
$.ajax
({
type: 'POST',
url: 'page-to-send-request.php',
data: dataString,
success: function()
{
$("#div-to-load").load("page.php #div-to-load").fadeIn('slow');
},
error: function (xhr, ajaxOptions, thrownError)
{
alert(xhr.status);
alert(thrownError);
}
});
}
},
The php page to load has for test only
if($_POST['count'])
{
$count = $_POST['count'];
echo "Count " .$count;
}
else{ echo "FALSE"; }
Expected result should be
Count 5
But real output is
FALSE
1st try
success: function(data)
{
console.log(data);
},
it should output "Count " .$count; if not
try to use
var dataString = {count: count};
and then you can use
$("#div-to-load").html(data).fadeIn('slow');
the reason of return false .. you used the .load to load the php page .. when you load it .. javascript know it as a separated page .. so $_POST['count'] is undefined in this case . and It will return False always
your success function should be like this
success: function(data)
{
$("#div-to-load").html(data).fadeIn('slow');
},
My ajax:
$.ajax(
{
type:'POST',
url: 'ajax.php', //the script to call to get data
data: {request: 'getUser',id:id},
dataType: 'json', //data format
complete: function(data) //on receive of reply
{
console.log(data);
}
});
My php file that handles the ajax request(ajax.php):
elseif ($_POST['request'] == 'getUser')
{
$DAO = new UserDAO;
$q = $DAO->ajaxGetUser($_POST['id']);
echo json_encode($q);
}
ajaxGetUser function:
public function ajaxGetUser($id)
{
$q = $this->db->prepare('SELECT * FROM user WHERE userId=:id');
$q->bindValue(':id', $id, PDO::PARAM_INT);
$q->execute();
$r = $q->fetch(PDO::FETCH_OBJ);
unset($r->userPassword);
return $r;
}
console.log(data) is showing me the object in the "ResponseJSON" on firebug, but when I try something like console.log(data.userName), console.log(data[0].userName), they're undefined, since i'm not very good in ajax i've been looking many threads but couldn't find one that could help me.
I guess the json is already parsed since dataType is set to "json", how can I access the User object with all its properties? Thanks for your help
readyState 4
responseJSON
Object { userId="6", userName="321", more...}
responseText
"{"userId":"6","userName...":null,"userStatus":"0"}"
status 200
statusText "OK"
abort function()
always function()
complete function()
done function()
error function()
fail function()
getAllResponseHeaders function()
getResponseHeader function()
overrideMimeType function()
pipe function()
progress function()
promise function()
setRequestHeader function()
state function()
statusCode function()
success function()
then function()
Set a success handler instead of complete:
The callback hooks provided by $.ajax() are as follows:
[...]
4. success callback option is invoked, if the request succeeds. It
receives the returned data, a string containing the success code,
and the jqXHR object.
[...]
6. complete callback option fires, when the request finishes,
whether in failure or success. It receives the jqXHR object,
as well as a string containing the success or error code.
The code would look like:
success: function(data)
{
console.log(data, data.userId, data.userName);
}
It seems data was an object, I managed to get the user object was by using data.responseJSON, so data.responseJSON.userName for the name.
I don't know why it would return in this way through.
I'm building a chatroom that sends messages via AJAX. Whenever I hit enter, with the data: parameter, it returns an error, but if I remove data:, it doesn't do anything. This is very puzzling, and I'm wondering what I'm doing wrong. Here is what I have:
$("#form").bind("keypress", function(e) {
if (e.keyCode == 13) {
$.ajax({
type: 'POST',
url: "send-message.php",
data: "message="+$("#message").val()+"&user="+$("#user").val()+"&room="+$("#room").val(),
success: $("#message").val(""),
error: $("#message").val("FAIL"),
});
return false;
}
});
I use PHP in my AJAX call, so I don't know if that is causing the problem?
Try this:
...
$.ajax({
type: 'POST',
url: "send-message.php",
data: {message: $("#message").val(), user: $("#user").val(), room: $("#room").val()},
success: function() { $("#message").val(""); },
error: function() { $("#message").val("FAIL"); }
});
...
In the above code:
a) data sent as JSON - this will make sure that any url encoding and escaping will be correctly performed by jQuery as needed
b) success and error options must be callback functions
I would do this just to check if it grabs all the data correct:
var data = {
message: $('#message').val(),
user: $('#user').val
};
console.log(data);
You need to change these lines:
success: $("#message").val(""),
error: $("#message").val("FAIL"),
to
success: function () { $("#message").val("") },
error: function () { $("#message").val("FAIL") // removed trailing comma
I wrapped your handlers in a function and removed the trailing comma.
You can pass an object into data, and jQuery takes care of transforming it into the correct form for the type of request you issue, in this case a POST:
$("#form").bind("keypress", function(e) {
if (e.keyCode == 13) {
$.ajax({
type: 'POST',
url: "send-message.php",
data: {
message: $("#message").val(),
user: $("#user").val(),
room: $("#room").val()
},
success: function () {
$("#message").val("");
},
error: function () {
$("#message").val("FAIL");
},
});
return false;
}
});
Also, error and success are callbacks, so you need to provide a function, not a string if you want it called. Fixed it for you.
If you want to pass your data in POST you should use the javascript key:value format (or JSON format).
Input the following in
data: {"message": $("#message").val(),"var2":variable}
and a hint
...
data: $("#form").serialize();
...
I have a PHP script that breaks if a variable is not populated and it isn't added to the database, but jQuery handles this as a success and I get this error:
TypeError: Result of expression 'data' [null] is not an object.
Here's the jQuery script:
$.ajax({
type: "POST",
url: "/clase/do-add",
data: $("#adauga").serialize(),
dataType: "json",
error: function (xhr, textStatus, errorThrown) {
alert('Try again.');
},
success: function(data) {
var dlHTML = '<dl id="' + data.id + '"> [too long] </dl>';
$('form#adauga').after(dlHTML);
$('#main dl:first').hide().fadeIn();
adaugaClasaSubmit.removeAttr('disabled');
adaugaClasa.removeAttr('readonly');
adaugaClasa.val("").focus();
}
});
The problem is that jQuery's concept of "error" is an HTTP error, not an error that you have noted yourself. If the HTTP response code is <400, jQuery will use your success callback. Your options are (a) to use PHP to give an error in your HTTP response
header("HTTP/1.0 500 Internal Server Error");
or (b) to do your error handling in the success handler:
success: function(data) {
if (!data) {
// do your error code here
} else {
// do your success code here
}
}
I prefer the first option, with HTTP response codes, to allow your code to make the best logical sense to a future editor (which may be you!).
success: function(data) {
if(data!=null){
...
}
}
try this