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
});
}
Related
I am trying to create a simple AJAX call using JSON, but I keep getting a parse error on the result and when I check the resultText it shows the source code of the entire page, with the JSON response showing a success above the page headers.
Here is my AJAX call, where #class is a select box with values.
$("#class").change( function () {
if($('#class').val().length > 0){
$.ajax({
type: "GET",
url: "http://192.168.0.9/ajax",
data: 'class_id=' + $("#class").val(),
datatype: 'json',
async: 'true',
beforeSend: function() {
alert("Before send!");
},
success: function(result){
if (result.status){
$('#result').html(result);
} else {
alert('request unsuccessful!');
}
},
complete: function() {
alert("Complete!");
},
error: function (request,error) {
alert('A jQuery error has occurred. Status: ' + error +':'+ request.responseText);
$("#result").html(request.responseText);
}
});
} else {
alert('Please make a selection');
}
return false;
});
This is my PHP function that returns the result
$result = array();
$result['status'] = "success";
$result['message'] = "Types";
header("Content-Type: application/json; charset=utf-8", true);
echo json_encode($result);
Finally, this is the response I am getting in my error alert:
A jQuery error has occurred status:parseerror
{"status":"success", "message":"Types"}<!DOCTYPE html>
<html>
...rest of my page from where the request was sent
I am hoping this is a simple error and someone can tell me what I am doing wrong?
Perhaps your parameter should be pass in JSON format:
data: "{'class_id':'" + $("#class").val() + "'}",
Try to remove datatype:'json' from the Javascript and header("Content-Type: application/json; charset=utf-8", true); it should be recognize itself
I'm programming a site, and I've got a problem.
I have the following jQuery code:
$('input[type="text"][name="appLink"]').keyup(function() {
var iTunesURL = $(this).val();
var iTunesAppID = $('input[name="iTunesAppID"]').val();
$.ajax({
type: 'POST',
url: jsonURL,
dataType: 'json',
cache: false,
timeout: 20000,
data: { a: 'checkiTunesURL', iTunesURL: iTunesURL, iTunesAppID: iTunesAppID },
success: function(data) {
if (!data.error) {
$('section.submit').fadeOut('slow');
//Modifying Submit Page
setTimeout(function() {
$('input[name="appLink"]').val(data.trackViewUrl);
$('div.appimage > img').attr('src', data.artworkUrl512).attr('alt', data.trackName);
$('div.title > p:nth-child(1)').html(data.trackName);
$('div.title > p:nth-child(2)').html('by '+data.sellerName);
$('span.mod-category').html(data.primaryGenreName);
$('span.mod-size').html(data.fileSizeBytes);
$('span.mod-update').html(data.lastUpdate);
$('select[name="version"]').html(data.verSelect);
$('input[name="iTunesAppID"]').attr('value', data.trackId);
}, 600);
//Showing Submit Page
$('section.submit').delay('600').fadeIn('slow');
} else {
$('.json-response').html(data.message).fadeIn('slow');
}
},
error: function(jqXHR, textStatus, errorThrown) {
//$('.json-response').html('Probléma történt! Kérlek próbáld újra később! (HTTP Error: '+errorThrown+' | Error Message: '+textStatus+')').fadeIn('slow');
$('.json-response').html('Something went wrong! Please check your network connection!').fadeIn('slow');
}
});
});
Sometimes (randomly) the content fades out-in twice.
Could you let me know what's wrong?
Thanks in advance.
I guess the page is dynamically generated from javascript,
If you execute the following function twice, then there be two events since it executes twice,
so a better way is to unbind all previus 'keyup' event and bind it again.
Try this,
$('input[type="text"][name="appLink"]').unbind('keyup').keyup(function() {
});
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);
}
});
});
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.
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