Error handling in Ajax call (jQuery) not working - php

I use jQuery and Ajax to pass data to a PHP / MySQLi page.
The code and the query work as intended but I can't find a way to handle the errors.
E. g. I want to inform the user about a potential duplicate record when the data that I pass to the PHP page already exists in my database (see comment in the code below).
I tried different approaches but my error handling is always ignored or not applied.
Can someone tell me how to do this right ?
jQuery (shortened):
$('#btnSave').on('click', function(e) {
e.preventDefault();
var vid = $.trim($('#vid').val());
var vid2 = $.trim($('#vid2').val());
var vid3 = $.trim($('#vid3').val());
var mode = 'update';
if(vid == 'new') {
mode = 'insert';
}
$.ajax({
type: 'POST',
url: 'updateVid.php',
data: {
mode: mode,
vstId: vstId,
vstId2: vstId2,
vstId3: vstId3
},
success: function(result){
alert('success');
},
error: function() {
alert('error'); // I am unable to retrieve this in jQuery / Ajax resp. to do anything here
}
});
});
PHP / MySQLi (shortened):
<?php
require_once 'me/config.php';
$postData = $_POST;
$mode = $_POST['mode'];
$vid = $_POST['vid'];
$vid2 = $_POST['vid2'];
$vid3 = $_POST['vid3'];
$conn = new mysqli($host, $username, $password, $database);
if($conn->connect_error) {
die("Connection Error: " . $conn->connect_error);
}
if($mode == 'update') {
$stmt = $conn->prepare("UPDATE vids v SET v.vid2 = ?, v.vid3 = ? WHERE v.vid = ?");
$stmt->bind_param("sss", $vid, $vid2, $vid3);
$stmt->execute();
} else {
$vid = '99999999';
$vid2 = '99XXX999';
$stmt = $conn->prepare("SELECT vid2 FROM vids WHERE vid = ?");
$stmt->bind_param("s", $vid);
$stmt->execute();
$stmt->store_result();
if($stmt->num_rows > 0) {
echo 'Error'; // I am unable to retrieve this in jQuery / Ajax
} else {
$stmt->close();
$stmt = $conn->prepare("INSERT INTO vids (vsid, vid2, vid3) VALUES (?, ?, ?)");
$stmt->bind_param("sss", $vid, $vid2, $vid3);
$stmt->execute();
echo 'Success';
}
}
$stmt->close();
$conn->close();
?>
Many thanks in advance,
Tom

It 's all about HTTP status codes. The jQuery success function is fired, when the http status code was 200/OK. If the returned http status code was errornous, it calls the error function. Knowing that you have to send http status codes within the php response header.
For this please have a look at the php http_reponse_code() function.
http_response_code(422);
echo json_encode($some_data);
exit();
Your echo output is always a valid output for jQuery. Outputting data without a status code is always a 200/OK status. As shown above, you can set the returned status with PHP. A list of HTTP status codes is shown here.

Because your AJAX call is always successful you will not get a failure. If the AJAX call fails, you will get an error.
Your PHP can fail separately, but it will not produce an AJAX error, so if you want to handle PHP errors with AJAX you have to handle them in the success function but providing a way to know the PHP failed. For example:
success: function(result){
if(result->message == 'fail') {
// handle failure here
}
},
ALSO
Please, quit using alert() for troubleshooting., use console.log() instead.

Related

Catch an Ajax Query POST error doesn't work

I wrote some code that enters data into my sql database using JQuery and PHP and it works.
However, I need the error block of the Ajax request to be executed when the database server is offline, sql throws an error, or whenever there should be an error.
The problem is, that the error-block of the ajax request never is executed. Always just the success block. No matter if the sql query is wrong or the database server is offline.
I have tried it with a fail-block and with jQuery.$.get() but that doesn't work either. But I prefer an ajax request anyway.
I have written the following code so far:
//JavaScript-function to insert data into a database. The parameter is an SQL-INSERT statement.
function insertIntoDatabase(sqlQuery)
{
var result;
$.ajax({
type: "POST",
url: "../../general/clientHelper.php",
data: {sql: sqlQuery},
async: false,
error: function()
{
if(sqlQuery.split(" ")[0] != "INSERT") console.log("SQL-Query is not an INSERT statement");
result = false;
},
success: function()
{
result = true;
}
});
return result;
}
<?php
//clientHelper.php - Insert data into the database.
if(isset($_POST['sql'])) insertIntoDatabase($_POST['sql']);
function insertIntoDatabase($sqlQuery)
{
$ip = "10.10.10.1";
$port = 3306;
$username = "candidate";
$password = "candidate";
$dbname = "cqtsdb";
$connection = new mysqli($ip, $username, $password, $dbname, $port);
$connection->query($sqlQuery);
$connection->close();
exit();
}
?>
I don't know what to do now :/ Please help <3
UPDATE:
I found out that if I add one parameter to the success function it gets filled with the text of an error if one has occurred. If everything is right the text is just "". So I didn't have to do anything else than check for it :)
success: function(data)
{
if(data == "") result = true;
else result = false;
}
Check the query result, if it was successful then return a certain value to ajax like 1, if it wasn't, return 0.
Then in ajax success function check that value and show a message accordingly or whatever you want to do.
I use procedural PHP and I do it this way
function leave($msg, $conn, $type){
//$msg is the message I want to display to the user.
//$type is the query result type I explained above.
//$conn is to close the connection.
echo json_encode(array(
"msg" => $msg,
"type" => $type
));
mysqli_close($conn);
exit();
}
call this function that way
$result = mysqli_query($conn, $query);
if ($result) {
leave('done', $conn, 1);
} else {
leave('something went wrong', $conn, 0);
}
check the value like that:
...
success: function (response) {
if(response.type == 1){
// do smth
}
else if(repsonse.type == 0){
// do another thing
}
},
...

Retrieving data from ajax in php

I have a simple ajax call firing on click of a button, sending the element's id attribute via POST, No errors and the data is being sent, I checked on the network console.
Therefore the next logical step is to think it's an issue with the php, in which i'm making a simple update statement, the issue is the php can't see the data passed by the ajax call. please see below:
AJAX:
$("a.report_btn").click(function() {
var url = "report_post.php"; // the script where you handle the form input.
$.ajax({
type: "POST",
url: url,
data: $("a.report_btn").attr("id"),
success: function(response) {
content.html(response);
$(".liked_success").show();
}, error:function(exception){alert('Exeption:'+exception);}
});
return false; // avoid to execute the actual submit of the form.
});
PHP:
<?php include 'db_connect.php';
$id =$_POST['id'];
try {
$sql = "UPDATE jobs_list
SET post_like = post_like+1, TimeStamp = TimeStamp
WHERE id=$id
LIMIT 1";
$statement = $dbh->prepare($sql);
$statement->bindValue("id", $id, PDO::PARAM_INT);
$statement->bindValue("post_like", $_POST['post_like'], PDO::PARAM_INT);
$count = $statement->execute();
$dbh = null; // Disconnect
}catch( PDOException $e ) {
echo 'Ops... something went wrong...'; // error message
var_dump($statement);
}
?>

How to retrieve an error message from a php file to another php file?

I'm new to ajax and this is my first attempt to use it.
What I'm trying to do is create a small system to register an email and password to the database without updating the page and it worked just fine!
However, as you will notice on my 'register.php' file, there is a condition to not allow duplicate emails, as well as PDOException to prevent errors...so, how can I send a message (an alert or whatever) to my index page in case any of them occurs?
This is my .js file:
$(document).ready(function(){
$("#btnRegister").click(function(){
$.ajax({
type: 'post',
url: 'register.php',
data: { txtEmail: $("#frmEmail").val(), txtPassword: $("#frmPassword").val() }
}).done(function(){
$("#frmEmail").val('');
$("#frmPassword").val('');
$("#frmEmail").focus();
});
});
});
My 'register.php' file:
<?php
try
{
$handler = new PDO('mysql:host=127.0.0.1;dbname=register', 'root', '');
$handler -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$email = $_POST['txtEmail'];
$password = $_POST['txtPassword'];
$sql = "SELECT email FROM users WHERE email = ?";
$query = $handler -> prepare($sql);
$query -> bindValue(1, $email);
$query -> execute();
if(($query -> rowCount()) != 0)
die("Error: the inserted email already exists.");
else
{
$sql = "INSERT INTO users (email, pass) VALUES (?, ?)";
$query = $handler -> prepare($sql);
$query -> bindValue(1, $email);
$query -> bindValue(2, $password);
$query -> execute();
}
}
catch(PDOException $ex)
{
die("Error: " . $ex -> getMessage());
}
?>
Usually, your PHP file would return a response indicating the success or failre of the registration.
In your PHP file, instead of dieing when there is an error, you should return a json-encoded array containing the error message, for example:
if(($query -> rowCount()) != 0)
echo json_encode(array('error' => "Error: the inserted email already exists."));
exit;
else
Then in your javascript's done function, you can check for this message:
}).done(function(data){
if (data.error) {
alert(data.error); // or do something else
} else {
// every thing looks ok, do your thing
}
});
I'd recommend always returning something from php, whether it's an error message as above, or simply json_encode(array('success' => true));. That way, you can be sure that the request has actually done what is expected, and not returned a blank page for another (bad) reason.
Note: if you have problems getting this to work, you might need to add dataType: 'json' to your ajax options (under type: 'post')
All you need to do is change all the die(); to echo ""; so instead of killing the PHP part, it returns the messages towards your index file. Next just change your jQuery script to:
$(document).ready(function(){
$("#btnRegister").click(function(){
$.ajax({
type: 'post',
url: 'register.php',
data: { txtEmail: $("#frmEmail").val(), txtPassword: $("#frmPassword").val() }
}).done(function(msg){
if(msg != ''){
alert(msg);
}
$("#frmEmail").val('');
$("#frmPassword").val('');
$("#frmEmail").focus();
});
});
});

Ajax to submit form, and retrieve success/error

I'm using jQuery with Ajax to submit a form to a PHP script.
The user will input their details, click a submit button, the PHP script will run and will have either performed the desired action or failed.
At this point I would want to display a success or error message based on the type of error.
<script>
$( "#contact-form" ).submit(function(event) {
event.preventDefault();
$.ajax({
url: "includes/contact-us.php",
type: "post",
data: $("#contact-form").serialize(),
success:function(data) {
alert(data);
},
error:function(){
alert("failure");
}
});
});
</script>
So in my jQuery above, when the form is submitted, it prevents the default action="path to script.php" then performs the submit. I've done this in case users have Javascript disabled, so at least the base functionality will be there.
PHP
<?php
if(isset($_POST['contact']) && !empty($_POST['contact'])){
$link = new mysqli("example", "example", "example", "example");
if($link->connect_errno > 0) {
die('Unable to connect to database [' . $link->connect_error . ']');
}
$name = $_POST['name'];
$email = $_POST['email'];
$website = $_POST['website'];
$subject = $_POST['subject'];
$message = $_POST['message'];
$stmt = $link->prepare("INSERT INTO contact (name, email, website, subject, message) VALUES (?, ?, ?, ?, ?)");
$stmt->bind_param("sssss", $name, $email, $website, $subject, $message);
if($stmt->execute()){
$rtn = "Success";
echo json_encode($rtn);
} else {
$rtn = "Failed";
echo json_encode($rtn);
}
$stmt->close();
$link->close();
}
However, in this example, an alert box appears empty. No errors in firebug or Apache logs.
Is it possible to: when I perform an submit using Ajax, I can recieve an echo "Text from error or success box"; which I can then put into a bootstrap alert?
The code I'm writing is new, so adapting to new libraries is something I would consider. This is purely for UI enhancement to show error or success messages, if the user has javascript disabled then the form default action wouldn't be prevented - they just wouldn't see a success or error message.
Something I have seen is "Javascript promises" I don't mind using Javascript if this is better in terms of useability, as I don't want to freeze the browser when a submit takes place.
Thanks for your time
Your code should look something like this
I would pass back a standard form of success/error from PHP. So failure might look like this:
json_encode(['success'=>false]);
Then acting on this in Javascript would look like this:
$.ajax({
url: "includes/contact-us.php",
type: "post",
data: $("#contact-form").serialize(),
success:function(data) {
data = JSON.parse(data);
if (data.success)
alert('success!');
else
alert('got failure response from PHP');
},
error:function(){
alert("failure");
}
});
You can use try catch() in php
<?php
// ...
try{
// your code
$msg = 'Success';
return json_encode($msg);
}catch(Exception $e){
$msg = 'Error';
return json_encode($msg);
}
?>

Why doesn't my ajax work with prepared mysqli statement

I have a small problem, which is that when I add my prepared statement into the PHP file, the Ajax stops working and gives me a 500- error, but when I remove the statement, it works like a charm.
This is my PHP file:
<?php
include ('db_connect.php');
include ('functions.php');
$datad = $_POST['superstr'];
$id = 1;
$stmt = $mysqli->prepare("UPDATE `song` SET `lyrtext`=? WHERE `id`=?");
$stmt->bind_param("si", $datad, $id);
$status = $stmt->execute();
echo $datad;
?>
and my Ajax looks like this:
$.ajax({
url: 'includes/sendlyrics.php',
type: 'POST',
data: {superstr: 'pelle'},
success: function(data) {
//called when successful
var hello = data;
//prompt(data);
console.log("The data is:");
console.log(data);
console.log("The variable which should keep the data has this content:");
console.log(hello);
},
error: function(e) {
//called when there is an error
console.log(e.message);
prompt(e.message);
//alert(e.message);
}
});
What's the problem?
$stmt = $mysqli->prepare("UPDATE `song` SET `lyrtext`=? WHERE `id`=?");
$stmt->bind_param("si", $datad, $id);
$status = $stmt->execute();
Is wrong. Amend this to:
$stmt = $mysqli->prepare("UPDATE `song` SET `lyrtext`=? WHERE `id`=?");
$stmt->bind_param("si", $datad, $id);
$stmt->execute();
If you are looking for confirmation of the query executing successfully you can test this by:
if($stmt->execute()){
//returned true - statement executed successfully
} else{
//returned false
}
Also you should modify your Ajax call to something similar to:
$.ajax({
url : "your/url/here.php"
type : "POST",
data : {superstr: 'pelle'},
dataType : "json",
success : function(data){
//do something with the response
},
error : function(jqXHR, textStatus, errorThrown){
//handle the error
}
});
By adding a dataType of json, you should then ammend the echo statement of your .php file to read:
$response = Array();
array_push($response, $datad);
echo json_encode($response);
I'm sure you've read the documentation online already, but Ajax can be found here, and prepared statements here.
This is all written with the caveat that your DB connection is valid...which it would appear to be given the wording of your question, and your previous attempts at solving the issue.

Categories