Get jQuery Error if PHP Breaks - php

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

Related

500 error when passing variables to function

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

Jquery or Ajax if load fails

When you use Jquery or Ajax to call a page or script, which loads into a div,
or example
$.post('pagename.php', $(#cpay'.$id.'").serialize(), function(data) { $('#conSupp".$id."').html(data);
is there a way to display an error message in the div if the page fails to load
Many thanks
If you are using jquery 1.5 or above, the post will return a jqXhr object. If so, you could do something like this:
$.post('pagename.php', data, function(data) {
//success, do stuff with the data object
}).fail(function(jqXhr, ajaxOptions, thrownError){
//something went wrong
alert('Error: ' + thrownError);
});
Yes, bind an error handler, by calling the .fail() function on the jqXhr object returned by the call to $.post():
$.post(url, data, function(data) {
...
}).fail(function(jqXhr, textStatus, errorThrown) {
// an error occurred - do something here
});
I prefer just doing:
$.ajax({
type: 'POST',
url : 'pagename.php',
data: $(#cpay'.$id.').serialize()
}).done(function(data {
$('#conSupp".$id."').html(data);
}).fail(function() {
$('#conSupp".$id."').html('An error occured');
});
It's a little longer, but I find it much easier to read an change to whatever I need, and it's exactly what $.post does internally anyway, so saves me a function call?

ajaxSubmit error capturing

I'm having trouble getting ajaxSubmit to catch an error:
$(document).ready(function(){
$("#supportForm").validate({
rules: {
//validation
},
messages: {
//messages
},
submitHandler: function(form) {
$(form).ajaxSubmit({
url:"ajax/supportform",
type:"GET",
dataType: 'json',
error: function() { alert('error'); },
success: function() {alert('success'); },
});
}
});
})
what do I have to return in my php script to get it to fire the error event?
I've tried returning an array with error=>0 , exit(json_encode('error'=>'0'); etc.
See Mike de Klerk's link, it provided the clues as to what had to be done to trap an error:
It seems the success & error callbacks have nothing to do with passing a boolean error/success message, but only if the url was successfully called. I expect I am not getting error results as I am using a CMS that is always returning some kind of content - even if it's a 404 or 403 page.
Anyway, I had to return a json string from my php script:
<?php
$response = json_encode(array("error" => "false","message" => "this is the error message"));
return $response;
then parse it in my success callback:
submitHandler: function(form) {
$(form).ajaxSubmit({
url:"ajax/supportform",
type:"POST",
dataType: 'json',
error: function(data ) { alert(data); },
success: function(response) {
var obj = jQuery.parseJSON(response);
if(obj.error == "true"){
alert('error is true');
}else{
alert('error is false')
}
},
});
}
Edit: to show some specific error description coming from PHP you should read this question: jQuery Ajax error handling, show custom exception messages
Let your server generate some error, with PHP you can do that like this
<?php
header("HTTP/1.0 404 Not Found");
?>
Check out the documentation of the header function: http://nl.php.net/manual/en/function.header.php
What you are doing here is providing your webbrowser with data that does not belong in the typical HTML source, by which the webbrowser knows something went wrong.
You could actually add all meta data you want to the header of the webpage request, but when the webbrowser does not know what it means it is simply ignored. See the definition or status codes here: http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
change url to something that doesn't exist to force an error
function(form) {
$(form).ajaxSubmit({
url:"ajax/supportform001",
type:"GET",
dataType: 'json',
error: function() { alert('error'); },
success: function() {alert('success');} // <-was an extra comma
});
}

JQuery AJAX Issue without error

So I am adding a list of stores to a web page via a jQuery AJAX request. This little utility is not dynamic, just database driven. I have decided to use jQuery/AJAX to transfer the data because when I try to embed PHP in our current PHP CMS, I get a bunch of conflicting errors.
The problem I am having is that I am getting a jQuery AJAX error when trying to make the request to the PHP script, and I am not sure why.
Here is my AJAX request
$(document).ready(function(){
$.ajax({
type:"POST",
url:"getStores.php",
dataType: "json",
success:function(data){
results(data);
},
error: function(data) {
console.log(data.error);
}
});
});
The cryptic console error i am getting is this
function (){if(c){var a=c.length;m(arguments),i?k=c.length:e&&e!==!0&&(j=a,n(e[0],e[1]))}return this}
Here is my PHP code if it will be helpful:
//database connection
$return_arr = array();
$sql = mysql_query("SELECT * FROM where_to_buy");
while($row = mysql_fetch_array($sql, MYSQL_ASSOC))
{
$row_array['store_name'] = $row['store_name'];
$row_array['store_url'] = $row['store_url'];
array_push($return_arr,$row_array);
}
echo json_encode($return_arr);
I think the problem might be because I wrapping my JSON in an array?
EDIT:: JSON output from php script as requested
[{"store_name":"Example 1","store_url":"http:\/\/www.example1.com"},{"store_name":"Example 2","store_url":"http:\/\/www.example2.com"}]
Thanks for any help!
The reason you are getting that weird error message is that the error callback for the jQuery ajax function takes 3 arguments instead of 1, as described in the docs here: http://api.jquery.com/jQuery.ajax/
The first argument is a jQuery-special XMLHttpRequest object, which has a property called error that contains the function you are seeing logged to your console. The actual error that occurred during execution of your ajax call is the passed in to the error callback as the 3rd argument.
To see it, you should do something like:
$(document).ready(function(){
$.ajax({
type:"POST",
url:"getStores.php",
dataType: "json",
success:function(data){
results(data);
},
error: function(jqXHR, text, error) {
console.log(error);
}
});
});
That will get you closer to the real problem.
UPDATE:
Please show the output from your php script. It may be that it is not returning valid json. As noted in the php docs ( http://php.net/manual/en/function.json-encode.php ), [json_encode] only works with UTF-8 encoded data.
You might also check in to json_last_error ( http://php.net/manual/en/function.json-last-error.php ) to see if the encoding failed for some reason.
UPDATE 3:
It seems like your problem may be the path to the php script.
try it with:
$(document).ready(function(){
$.ajax({
type:"POST",
url:"/getStores.php", // <-- notice the leading slash!!!
//dataType: "json",
success:function(data){
//results(data);
console.log(data);
},
error: function(jqXHR, text, error) {
console.log(error);
}
});
});
or, putting it all back together if the above logs the correct json output to the console...
$(document).ready(function(){
$.ajax({
type:"POST",
url:"/getStores.php",
dataType: "json",
success:function(data){
results(data);
},
error: function(jqXHR, text, error) {
console.log(error);
}
});
});

JQuery.ajax() method not executing

I have a have a button that calls a JavaScript method that looks like this:
processSelection = function(filename) {
//alert('method reached');
$.ajax({
url: "sec/selectUsers.php",
data: "filename="+filename,
cache: false,
dataType:'html',
success: function(data) {
//$('#uploader').html(data);
$('#noUsers').sortOptions();
values = $('#noUsers').children();
for (i = 0; i < values.length; i++) {
$(values[i]).bind('dblclick',switchUser);
}
$('#addButton').bind('click',addSelection);
$('#removeButton').bind('click',removeSelection);
$('#submitButton').bind('click',addUsersToFile);
},
error: function (request, textStatus, errorThrown) {
alert('script error, please reload and retry');
}
}); /* ajax */
}
It is not going to the selectUsers.php script, nor is it posting the error message. When I click on my button 'add users' it does nothing. The other methods: switchUser, removeSelection, addSelection, and addUserstoFile are already defined.
I am fairly new to JavaScript and php and have been assigned this project running maintenance on our website. My php_error.log shows no error either. If anyone has any advice on this specific problem, or debugging in general I would very much appreciate it.
here is the click event:
<input type="button" value="add users" onclick="processSelection('<?=$drFile['name']?>')"/>
Okay,
To simplify my problem, I have done this:
processSelection = function(){
//alert('method reached');
$.ajax({
url: "sec/testPage.php",
cache: false,
success: function() {
alert('success');
},
dataType:'html',
error: function (request, textStatus, errorThrown) {
alert('script error, please reload and retry'); }
});
}
where testPage.php is just a table with some values in it.
Now when I click the button it show 'success', but never shows testPage.php
dataType: 'HTML'
has to be before your success method as far as i know. If still does not work try the following:
it will not show the test page because you are not appending anything to your current body. Your script executes successfully if you see "success"on your screen. All you need to do is if you have html generated in your testPage, assign all html to a php variable and then just echo it instead of returning it like
echo $myhtmlgenerated
and change
success: function() { ....
TO
success: function(result) {
$(body).append(result);
}
or you can play around with it and specify a special div which will hold the content from that page.

Categories