Solved

How to gracefully handle MySQL errors in a JSON request?

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

Free Tool: Postgres Monitoring System

A PHP and Perl based system to collect and display usage statistics from PostgreSQL databases.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Uploading a CSV Data Import via PHP & MySql 3 34
AJAX Wordpress Not Reading Variable 2 31
Do alert on select 6 15
Only allow one check box 17 27
Build an array called $myWeek which will hold the array elements Today, Yesterday and then builds up the rest of the week by the name of the day going back 1 week.   (CODE) (CODE) Then you just need to pass your date to the function. If i…
Today, the web development industry is booming, and many people consider it to be their vocation. The question you may be asking yourself is – how do I become a web developer?
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 dynamically set the form action using jQuery.

828 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