2

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.

2
  • have you tried debugging in firebug ? Commented Jun 3, 2012 at 16:57
  • just did, but there are no errors reported. Commented Jun 3, 2012 at 17:12

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.