Reputation: 18863
I am submitting a form using ajax,
function ajax_post() {
// ...(code);
var hr = new XMLHttpRequest();
var url = "http://domain.com/submit_action.php";
var vars = "element_1=" + ln + "&element_2=" + fn;
hr.open("POST", url, true);
hr.send(vars);
// ...(code);
}
having the php exc the query:
$sql = 'SELECT *
FROM ' . table. '
WHERE ' . $db -> sql_build_array('SELECT', $data);
$result = $db -> sql_query($sql);
$sql = 'INSERT INTO ' . table. ' ' . $db -> sql_build_array('INSERT', $data);
$db -> sql_query($sql);
In my above code, it will run. But when the 'fn' and 'ln' are the same or already exist in the db, then there will be a error. But because im using ajax to submit it, I stay on the current page of the form without getting a error, without knowing if the query exc or not.
Question is, is there a way to have php tell ajax what kind of error occured during the exc of query? Thanks in advance.
Upvotes: 2
Views: 200
Reputation: 21532
anything echoed during your php script will be returned into the hr.responseXML
and hr.responseText
attributes.
Catch these 2 values within your hr.onreadystatechange
callback, whenever the status is OK, to know what happened in your php.
hr.onreadystatechange = function() {
if (hr.readyState == 4 && (hr.status == 200)) {
//do something with hr.responseText
}
}
I personnaly systematically encapsulate my php answers inside a generic xml response, with a customized status: error/ok/business error, and a customized message, so I know what to do with it at the javascript layer.
In addition to this, I would suggest you catch the 1062 mysql error to know that the error is due to an already existing value, and raise a more user-friendly message.
Upvotes: 2