Solved

How to gracefully handle MySQL errors in a JSON request?

Posted on 2014-12-30
3
343 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
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

PeopleSoft Has Never Been Easier

PeopleSoft Adoption Made Smooth & Simple!

On-The-Job Training Is made Intuitive & Easy With WalkMe's On-Screen Guidance Tool.  Claim Your Free WalkMe Account Now

Question has a verified solution.

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

These days socially coordinated efforts have turned into a critical requirement for enterprises.
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…
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

617 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