Solved

How to gracefully handle MySQL errors in a JSON request?

Posted on 2014-12-30
3
313 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 82

Assisted Solution

by:leakim971
leakim971 earned 250 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 250 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

Enabling OSINT in Activity Based Intelligence

Activity based intelligence (ABI) requires access to all available sources of data. Recorded Future allows analysts to observe structured data on the open, deep, and dark web.

Join & Write a Comment

Suggested Solutions

These days socially coordinated efforts have turned into a critical requirement for enterprises.
Password hashing is better than message digests or encryption, and you should be using it instead of message digests or encryption.  Find out why and how in this article, which supplements the original article on PHP Client Registration, Login, Logo…
The viewer will learn how to count occurrences of each item in an array.
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …

760 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

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now