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

x
?
Solved

How to gracefully handle MySQL errors in a JSON request?

Posted on 2014-12-30
3
Medium Priority
?
367 Views
Last Modified: 2014-12-30
New to AJax/JSON and need assistance in handling MySQL errors on the called PHP page.  

All of the examples I've found online do a "die" if the query fails or no records are returned.  I want to gracefully handle errors by showing an alert if the call fails. (This is also a huge advantage to me in debugging.)  The text I want to show is generated on the PHP page.

Rough code follows.

Thanks!
Bruce


javascript function code:
	var xmlhttp;
	xmlhttp = new XMLHttpRequest();
	
	xmlhttp.onreadystatechange=function() {
		if (xmlhttp.readyState==4 && xmlhttp.status==200) {
		    txt = xmlhttp.responseText;
         		var R = JSON.parse(txt);
// load variables, display info, etc.
	} 
	
	xmlhttp.open("GET","ajax_user_data.php?id=" + rqstr, true);
	xmlhttp.send();

PHP page code:
<?php
header("content-type:application/json");
session_start();
include_once("adiInclude.php");

$id = $_GET['id'];
$txt = '';
$connAJAX = ConnectDB();   // function is in include file

$sql = 'SELECT * FROM users WHERE user_id = ' . $id;

$qry = mysql_query($sql, $connAJAX);

if (!$qry) {
	$txt = 'JSON Users query failed: ' . mysql_error($connAJAX) . " SQL: " . $sql;
		
} elseif (mysql_numrows($qry) == 0) {
	$txt = "JSON Invalid User ID: " . $id;
	mysql_free_result($qry);
	
} else {
	$row = mysql_fetch_assoc($qry);
	foreach($row as $i => $v) {
		if ($i == "user_id" || $i == "user_cam" || $i == "user_country" || $ == "user_via") {
			$txt .= ', "' . $i . '":' . $v . '';
		} else {
			$txt .= ', "' . $i . '":"' . $v . '"';
		}
	}
	$txt = '{ ' . substr($txt, 2) . ' }';
	
	mysql_free_result($qry);	
}
mysql_close($connAJAX);
echo $txt;	
exit();
?>

Open in new window

0
Comment
Question by:springthorpeSoftware
3 Comments
 
LVL 83

Assisted Solution

by:leakim971
leakim971 earned 1000 total points
ID: 40523939
I see you set the header line 16
so just use die :
    die('{"success":false}');

and replace line 7 by :
var R = JSON.parse(txt);
if(R.success == false)  { // if(!R.success)
    alert("error");
    return false;
}

Open in new window

0
 
LVL 58

Accepted Solution

by:
Gary earned 1000 total points
ID: 40524061
Prepend your $txt for the errors with ! (just an example) e.g.
$txt = '!JSON Users query failed: '.....

Open in new window


Your state change function becomes

	xmlhttp.onreadystatechange=function() {
		if (xmlhttp.readyState==4 && xmlhttp.status==200) {
		    txt = xmlhttp.responseText;
			if(txt.substring(0, 1)=="!"){
				alert(txt.substring(1))
			}
			else{
         			var R = JSON.parse(txt);
				// load variables, display info, etc.
			}
	} 

Open in new window

0
 

Author Closing Comment

by:springthorpeSoftware
ID: 40524875
Both work well! Thanks!
0

Featured Post

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

Question has a verified solution.

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

This article demonstrates how to create a simple responsive confirmation dialog with Ok and Cancel buttons using HTML, CSS, jQuery and Promises
This article discusses how to implement server side field validation and display customized error messages to the client.
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
Suggested Courses

824 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