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.
anything echoed during your php script will be returned into the
hr.responseXMLandhr.responseTextattributes.Catch these 2 values within your
hr.onreadystatechangecallback, whenever the status is OK, to know what happened in your php.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.