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
}
},
...
Related
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.
I have some code that sends a variable (pin) to php via AJAX the database is then queried and if a result is found the php echo's a value of 1. Everything is working fine, except that the Ajax does not recognise the value returned by the php.
Here is my code
$(document).ready(function () {
$("form.submit").submit(function () {
var pin = $(this).find("[name='pin']").val();
// ...
$.ajax({
type: "POST",
url: "http://www.example.com/pin.php",
data: {
pin : pin,
},
success: function (response) {
if (response == "1") {
$("#responsecontainer").html(response);
window.location.href = "home.html?user=" + user;
// Functions
} else { // Login failed
alert("LOGIN FAILED");
}
}
});
this.reset();
return false;
});
});
And here is my PHP code, I know that the code below returns a value of 1. When Ajax is triggered it returns a value that generates a login fail message. Is there a way to see what Ajax is sending, if i swap out the ajax and directly submit the for to the server it also returns a 1 on the php echo.
$pin = $_GET["pin"];
$db = new PDO("mysql:host=localhost;dbname=xxxxx;charset=utf8", "xxxx", "xxxx");
$count = $db->query("SELECT count(1) FROM users WHERE pin='$pin'")->fetchColumn();
echo $count;
It's recommended to return JSON data as result for an ajax request.
So try this :
Edit: I've updated the php code to make the sql query with PDO prepare() method taking into account #Dominik's commentary
$pin = $_POST['pin'];
$db = new PDO('mysql:host=localhost;dbname=xxxxx;charset=utf8', 'xxxx', 'xxxx');
$stmt = $pdo->prepare('SELECT count(1) FROM users WHERE pin = :pin');
$stmt->execute(array('pin' => $pin));
return json_encode([
"count" => $stmt->fetchColumn()
]);
And in your ajax success callback :
...
success: function(response) {
var count = JSON.parse(response).count;
if (count == "1") {
$("#responsecontainer").html(response);
window.location.href = "home.html?user="+ user;
} else {// Login failed
alert("LOGIN FAILED");
}
},
error: function(error) {
...
}
Hope it's helps you :)
I have a poll and when user click on one of the options, it sends data through ajax:
$.ajax({
type: 'POST',
url: '/poll.php',
data: {option: option, IDpoll: IDpoll},
dataType: 'json',
async: false,
error: function(xhr, status, error) {
alert(xhr.responseText);
},
success: function(data) {
if(data.msg == "0") {
$( "#pollArea" ).load( "/pollVote.php", { allow: true }, function() {
alert( "Ďakujeme za Váš hlas!" );
});
}
else {
alert(data.msg);
alert("V tejto ankete ste už hlasovali.");}
}
});
This works fine. Now data are passed to the file poll.php:
if (isset($_POST['option']) && isset($_POST['IDpoll'])) {
require 'includes/config.inc.php';
$ip = $_SERVER['REMOTE_ADDR'];
$option = $pdo->quote($_POST['option']);
$IDpoll = $pdo->quote($_POST['IDpoll']);
$date = date("d.m.Y H:i:s");
$poll = new Poll();
$msg = $poll->votePoll($IDpoll, $ip, $option, $date);
$arr = array(
'msg' => $msg
);
echo json_encode($arr);
This also works, the problem happened in class Poll - method VotePoll:
public function votePoll($IDpoll, $ip, $option, $date)
{
try {
$query = "SELECT * FROM `votes` WHERE `IDpoll` = '$IDpoll' AND `ip` = '$ip'";
$result = $this->pdo->query($query);
if ($result->rowCount() == 0) {
/* do stuff */
}
catch (PDOException $e) {
return $e->getMessage();
}
}
And the error message from the ajax call is following: Call to a member function rowCount() on a non-object. I know what this message means, but I can't find out why the variable $result isn't considered as PDO object. Strange thing is, that when I try to call function votePoll manually, it works perfectly and when I use var_dump on result it is PDO object. So where is the mistake?
EDIT: I forgot to say I was just editing this function. Originally it worked with mysqli but I wanted to switch to pdo (so query and stuff like that are okay).
So, this problem was in these lines:
$option = $pdo->quote($_POST['option']);
$IDpoll = $pdo->quote($_POST['IDpoll']);
PDO quote function add quotes to the string so option became 'option' etc. Then it was sent to query where additional quotes were added, so the result was ''option'' and that is error.
I'm quite new with PHP/Jquery and I am trying to do an update password script for my web site. So far the passwords update but I'm struggling to think of how I would validate this to check against the old password.
Also, how would it be possible to display the error messages in an alert box (like java alert window). The reason I ask is because I would need to create an alert box if the old password doesn't match the password that exists in the database.
Any help on this would be much appreciated. If you need any additional code I will post this ASAP.
// *Update Profile Password* //
$("#btn-profile-update2").bind('click', function(){
// Get info from text boxes
/* var profile_oldpassword = $('#txt-prof-oldp').val(); */
var profile_newpassword = $('#txt-prof-newp').val();
var profile_confirmpassword = $('#txt-prof-confp').val();
new_password = $('#txt-prof-newp').val();
old_password = $('#txt-prof-oldp').val();
if (profile_newpassword !== profile_confirmpassword) {
response = "Passwords entered do not match"
alert(response);
return;
}
// An array of field names to be updated
var arr_field_names = Array();
// Add the field name to index of array
arr_field_names[0] = "Password";
// An array of field values that correspond with our field names...
var arr_field_values = Array();
arr_field_values[0] = profile_newpassword;
// Send to updateProfDetails function
updatePassword(arr_field_names,arr_field_values,new_password,old_password);
});
});
Which sends to this function:
function updatePassword(arr_field_names,arr_field_values,new_password,old_password) {
// Ajax parameters...
$.ajax({
// Request sent from control panel, so send to cp.request.php (which is the handler)
url: 'scripts/php/bootstrp/cp.request.php',
type: 'GET',
data: {
ft: "password",
table: "tblusers",
oldpassword: old_password,
newpassword: new_password,
field_names: arr_field_names,
field_values: arr_field_values,
// Either pass a row id as the 'id' OR a where clause as the 'condition' never both
id: null,
condition: null
},
dataType: 'text',
timeout: 20000,
error: function(){
$('#cp-div-error').html('');
$('#cp-div-error').append('<p>There was an error updating the data, please try again later.</p>');
$('#cp-div-error').dialog('open');
},
success: function(response){
// Refresh page
// location.reload(true);
}
});
}
and finally the PHP update:
public function password($tableName)
{
$PDO = new SQL();
$dbh = $PDO->connect(Database::$serverIP, Database::$serverPort, Database::$dbName, Database::$user, Database::$pass);
$username = UserAccount::get_useremail();
$password = hash('sha256',trim($_GET['newpassword']));
$oldpassword = hash('sha256',trim($_GET['oldpassword']));
// Does the password given match the password held?
$this->sql = "UPDATE $tableName SET password = '$password' WHERE UserName = '$username'";
try {
// Query
$stmt = $dbh->prepare($this->sql);
$stmt->execute();
$count = $stmt->rowCount();
echo $count.' row(s) updated by SQL: '.$stmt->queryString;
$stmt->closeCursor();
}
catch (PDOException $pe) {
echo 'Error: ' .$pe->getMessage(). 'SQL: '.$stmt->queryString;
die();
}
// Close connection
$dbh = null;
}
You almost got it.. key is here:
success: function(response) { .. }
just play with response maybe something like this:
success: function(response) {
if (response == "wrong password") alert ("don't guess");
else if (response == "password changed") alert ('you got it! congrats!');
}
I think Vytautas makes a good point, i havn't read it all trough but i just want to give you a important hint
put $PDO->connect in a try{}catch(){}
If the PDO connect function gets an error it prints your database information including password.
I'm having troubles using ajax and php. What I'm trying to do is call an ajax function that grabs a value from an form's input, and checks if that email exists in a database. Here is my current javascript:
//Checks for Existing Email
function checkExisting_email() {
$.ajax({
type: 'POST',
url: 'checkExist.php',
data: input
});
emailExists = checkExisting_email();
//If it exists
if (emailExists) {
alert("This email already exists!");
}
Unfortunately, I can't get my alert to go off. In my PHP function, it checks whether the input is a username or an email (just for my purposes, and so you know), and then it looks for it in either column. If it finds it, it returns true, and if not, it returns false:
include ('func_lib.php');
connect();
check($_POST['input']);
function check($args)
{
$checkemail = "/^[a-z0-9]+([_\\.-][a-z0-9]+)*#([a-z0-9]+([\.-][a-z0-9]+)*)+\\.[a-z]{2,}$/i";
if (!preg_match($checkemail, $args)) {
//logic for username argument
$sql = "SELECT * FROM `users` WHERE `username`='" . $args . "'";
$res = mysql_query($sql) or die(mysql_error());
if (mysql_num_rows($res) > 0) {
return true;
} else {
return false;
}
} else {
//logic for email argument
$sql = "SELECT * FROM `users` WHERE `email`='" . $args . "'";
$res = mysql_query($sql) or die(mysql_error());
if (mysql_num_rows($res) > 0) {
return true;
} else {
return false;
}
}
}
SO my issue is, how does ajax respond to these returns, and how do I make ajax function accordingly? Mainly, why doesn't this work?
Any help is very much appreciated. Thank you!
You need to add the success option to your Ajax request, which is the JS function which gets executed when the XHR succeeds. Have a look at the jQuery documentation for more info.
Without running the script, I think you'll find that $_POST['input'] is empty; you need to pass your data as something like data: {'input': input} to do that.
Your PHP also needs to return some content to the script; consider changing your call to check() to something like this:
echo (check($_POST) ? 'true' : 'false');
You can now check the content in JavaScript.
Basically ajax is a hand-shaking routine with your server.
Ajax:
$.post('yoursite.com/pagewithfunction.php',
{postkey1:postvalue1, postkey2:postvalue2...},
function (response) {
// response is the data echo'd by your server
}, 'json'
);
pagewithfunction:
yourFunction(){
$var1 = $_POST['postkey1'];....
$result = dosomething($var1..);
echo json_encode($result); // this is passed into your function(response) of ajax call
}
So in $.post you have the url of the php page with the function, { var:val } is the post data, and function(response) is where you handle the data that is echo'd from your server -- the variable, response, is the content that is echo'd.