Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

ajax error handling

Posted on 2012-03-11
10
Medium Priority
?
312 Views
Last Modified: 2012-03-19
I have created an ajax call which submits some php code to a mysql db and it works ok.
I now want to add some error handling so if the mysql query fails then the user gets told so.

The code below is how far I have got with it but the array always comes back undefined.

Could someone take a look and perhaps give me a clue why it doesn't work.

Many Thanks

Steve


javascript
function saveCanvas(frm) {
	
    $.blockUI({ message: '<h1><img src="images/busy.gif" /><br>Submitting...<br>Please Wait...</h1>' }); 
&#9;
    var strImageData = canvas.toDataURL();  
&#9;
    $.ajax({
      &#9;type: 'POST',
      &#9;url: 'draw/submitimage.php',
&#9;  &#9;dataType : 'html',
&#9;&#9;data: frm.serialize() + "&imageData="+encodeURIComponent(strImageData),
&#9;&#9;cache: false,
&#9;&#9;async: true,

&#9;&#9;success: function(data) {
&#9;&#9;&#9;if (data.status() == "success") {
&#9;&#9;&#9;&#9;alert("SUCCESS. " + data.message);

&#9;&#9;&#9;} else {
&#9;&#9;&#9;&#9;alert("Oops. " + data.message);
&#9;&#9;&#9;}
&#9;&#9;},
&#9;&#9;
&#9;&#9;error: function(jqXHR, exception) {
            if (jqXHR.status === 0) {
                alert('Not connect.\n Verify Network.');
            } else if (jqXHR.status == 404) {
                alert('Requested page not found. [404]');
            } else if (jqXHR.status == 500) {
                alert('Internal Server Error [500].');
            } else if (exception === 'parsererror') {
                alert('Requested JSON parse failed.');
            } else if (exception === 'timeout') {
                alert('Time out error.');
            } else if (exception === 'abort') {
                alert('Ajax request aborted.');
            } else {
                alert('Uncaught Error.\n' + jqXHR.responseText);
            }
        }
&#9;});
&#9;
&#9;    return false;
};

Open in new window



submit php
<?php require_once '../includes/config.php'; ?>

  <?php
  
  &#9;  $ajaxResponse=array();
  
&#9;  //convert all the posts to variables:
&#9;  $terminalNumber = $_COOKIE['terminalNumber'];
  &#9;  $submissionType = "image";
  &#9;  $name = $_POST['name'];
&#9;  $subject = $_POST['subject'];
&#9;  $message = $_POST['description'];&#9;  
&#9;  $imageData = $_POST['imageData'];
&#9; 
   //Insert the values into the correct database with the right fields
   $result=mysql_query("INSERT INTO messages (dateTime, terminalNumber, submissionType, name, subject, message, imageData)".
      "VALUES (NOW(), '$terminalNumber', '$submissionType', '$name', '$subject', '$message', '$imageData')");&#9;  
&#9; 
&#9;//handle your query.
if ($result) {
     $ajaxResponse['status'] = "success";
     $ajaxResponse['message'] = "Your feedback has been submitted";
} else {
     $ajaxResponse['status'] = "failure";
     $ajaxResponse['message'] = "There was a problem: " . mysql_error();
}

echo json_encode($ajaxResponse);

?>

Open in new window

0
Comment
Question by:Steve Tinsley
  • 4
  • 3
10 Comments
 
LVL 111

Expert Comment

by:Ray Paseur
ID: 37707597
In MySQL datetime is a reserved word.  Not sure if that is the problem or not, but it could be a risk.
0
 
LVL 111

Expert Comment

by:Ray Paseur
ID: 37707600
What happens if you remove the AJAX part of it and just make a form that posts directly to submit.php?  If you try that it will help isolate the problem to the server side vs. the client side.

Also, please learn about this function before you get hacked.
http://us3.php.net/manual/en/function.mysql-real-escape-string.php
0
 

Author Comment

by:Steve Tinsley
ID: 37707636
Just so you know... even tho the alert that comes back is: Oops undefined it still successfully entering the record into the mysql db.

if (data.status() == "success") {
	alert("SUCCESS. " + data.message);

} else {
	alert("Oops. " + data.message);
}

Open in new window


I could remove the code above and it all works fine. I would just like to inform the user if there was an error.
0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 111

Accepted Solution

by:
Ray Paseur earned 1500 total points
ID: 37707649
It seems like data.status() is not defined as a method.  How about data.status without the parentheses, so it is a property?
0
 

Author Comment

by:Steve Tinsley
ID: 37707666
I have altered the function so that all it does it alert("SUCCESS. " + data.message);
But it still alerts undefined.
Any other ideas?

function saveCanvas(frm) {

    $.blockUI({ message: '<h1><img src="images/busy.gif" /><br>Submitting...<br>Please Wait...</h1>' }); 

    var strImageData = canvas.toDataURL();  
	
    $.ajax({
      	type: 'POST',
      	url: 'draw/submitimage.php',
	  	dataType : 'html',
		data: frm.serialize() + "&imageData="+encodeURIComponent(strImageData),
		cache: false,
		async: true,
		

		success: function(data) {
				alert("SUCCESS. " + data.message);
				window.location.href = "index.php";
		},
		
		error: function(jqXHR, exception) {
            if (jqXHR.status === 0) {
                alert('Not connect.\n Verify Network.');
            } else if (jqXHR.status == 404) {
                alert('Requested page not found. [404]');
            } else if (jqXHR.status == 500) {
                alert('Internal Server Error [500].');
            } else if (exception === 'parsererror') {
                alert('Requested JSON parse failed.');
            } else if (exception === 'timeout') {
                alert('Time out error.');
            } else if (exception === 'abort') {
                alert('Ajax request aborted.');
            } else {
                alert('Uncaught Error.\n' + jqXHR.responseText);
            }
        }
	});
	    return false;
};

Open in new window

0
 

Author Comment

by:Steve Tinsley
ID: 37715217
Has anyone else got any ideas why the variable I am setting in the PHP script is showing as undefined in the javascript success statement?
0
 

Author Closing Comment

by:Steve Tinsley
ID: 37739981
This was one of the problems.
0

Featured Post

Important Lessons on Recovering from Petya

In their most recent webinar, Skyport Systems explores ways to isolate and protect critical databases to keep the core of your company safe from harm.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction This article is intended for those who are new to PHP error handling (https://www.experts-exchange.com/articles/11769/And-by-the-way-I-am-New-to-PHP.html).  It addresses one of the most common problems that plague beginning PHP develop…
A while back, I ran into a situation where I was trying to use the calculated columns feature in SharePoint 2013 to do some simple math using values in two lists. Between certain data types not being accessible, and also with trying to make a one to…
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will receive an overview of the basics of CSS showing inline styles. In the head tags set up your style tags: (CODE) Reference the nav tag and set your properties.: (CODE) Set the reference for the UL element and styles for it to ensu…
Suggested Courses

886 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question