Solved

How to gracefully handle MySQL errors in a JSON request?

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

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!

Question has a verified solution.

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

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…
This article discusses how to implement server side field validation and display customized error messages to the client.
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…
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.

752 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