I have a favourites button calling an ajax request to update a MySQL database.
I would like to have a alert if there are duplicate additions or too many additions.
Can anybody see a way that I could show an alert if there is a duplicate addition? My code is below:
AJAX REQUEST
$.ajax({
type: 'post',
url: 'favaddDB.php',
data: $('#addfaveform').serialize(),
success: function () {
alert('Added To Favourites');
}
});
PHP
$db = new PDO("mysql:host=localhost;dbname=favourites", 'root', '');
$query1="SELECT * FROM `$email` ";
$stat1=$db->prepare($query1);
$stat1->execute();// IMPORTANT add PDO variables here to make safe
//Check if fave adds >9
$count = $stat1->rowCount();
$fave=$count;
if ($fave>9) {die(); exit();} // HERE I WISH TO RUN AN ALERT OR SEND BACK A MESSAGE TO DISPLAY
else {$fave=$fave+1;}
Just return the text to alert to your javascript:
$db = new PDO("mysql:host=localhost;dbname=favourites", 'root', '');
$query1="Query here ($email/similar should NOT BE HERE! Add them via execute/prepare.";
$stat1=$db->prepare($query1);
$stat1->execute();// IMPORTANT add PDO variables here to make safe
//Check if fave adds >9
$count = $stat1->rowCount();
$fave=$count;
if ($fave>9) {die("Here is a message");} // HERE I WISH TO RUN AN ALERT OR SEND BACK A MESSAGE TO DISPLAY
else {$fave=$fave+1; die("Here is another message"); }
Ajax request:
$.ajax({
type: 'post',
url: 'favaddDB.php',
data: $('#addfaveform').serialize(),
success: function (message) {
alert(message);
}
});
Additionally, you should consider using JSON, to pass back entire objects to your javascript, and parse it there:
$db = new PDO("mysql:host=localhost;dbname=favourites", 'root', '');
$query1 = "Query here ($email/similar should NOT BE HERE! Add them via execute/prepare.";
$stat1 = $db->prepare($query1);
$result = $stat1->execute();// IMPORTANT add PDO variables here to make safe
// Tell javascript we're giving json.
header('Content-Type: application/json');
if (!$result) {
echo json_encode(['error' => true, 'message' => 'A database error has occurred. Please try again later']);
exit;
}
//Check if fave adds >9
$count = $stat1->rowCount();
$fave = $count;
if ($fave > 9) {
echo json_encode(['error' => false, 'fave' => $fave, 'message' => 'Fave > 9!']);
} // HERE I WISH TO RUN AN ALERT OR SEND BACK A MESSAGE TO DISPLAY
else {
$fave = $fave+1;
echo json_encode([
'error' => false,
'fave' => $fave,
'message' => 'Current fave count: ' . $fave
]);
}
And in your ajax, make sure you set dataType: 'json', which will automatically parse it into an object:
$.ajax({
type: 'post',
url: 'favaddDB.php',
data: $('#addfaveform').serialize(),
dataType: 'JSON',
success: function (res) {
if (res.error) {
//Display an alert or edit a div with an error message
alert(res.message);
} else {
//Maybe update a div with the fave count
document.getElementById('#favcount').value = res.fave;
alert(res.message);
}
}
});
Simple is better, in most cases.
By returning messages, you can do whatever you want on the frontend side, depending on the message.
PHP:
<?php
$db = new PDO("mysql:host=localhost;dbname=favourites", 'root', '');
$query1 = "SELECT * FROM " . $email;
$stat1 = $db->prepare($query1);
$stat1->execute();
$count = $stat1->rowCount();
$fave = $count;
if ($fave > 9) {
echo "tooMany"; exit();
} else {
echo "addedFav"; $fave++;
}
JS:
jQuery.post({
url: 'favaddDB.php',
data: jQuery('#addfaveform').serialize()
}).then(function (code) {
switch (code) {
case "addedFav":
alert('Added To Favourites');
break;
case "tooMany":
alert('Too many favourites');
break;
}
}).catch(function (error) {
console.log(error);
});
Related
This is my first baby step with Ajax and I'm already struggling. I have a request that inserts into the DB but my code for the moment is behaving like all the requests are successful, but I want to be able to handle the errors when updating the DB. I want to alert() a success/error message depending on the MYSQL response.
My Ajax call:
$("a.bgbtb").click(function(){
var btnid = $(this).attr("id").split('newbudbtn-')[1];
var newbudget = $("INPUT[id=newbud-"+btnid+"]").val();
var platform = $("span#"+btnid).text();
$.ajax({
url:"campbdgtedit.php",
method:"POST",
data:{platform:platform, btnid:btnid, newbudget:newbudget},
success:function(data){
myAlertTop();
}
});
});
campbdgtedit.php:
$query = "INSERT INTO campaigns (camp_budget, camp_campaignid) VALUES ('".$_POST['newbudget']."', '".$_POST['btnid']."')";
if ($conn->query($query) === TRUE) {
echo "Success<br/>";
} else {
echo "Error: " . $query . "<br>" . $conn->error;
}
How can I catch if there is an error in the query and handle my alerts accordingly? I've tried many solutions I've found here but I can't seem to make them work.
I would recommend returning JSON from your PHP code, this can be interpreted directly as an object in the JavaScript if you use dataType: 'json' on your ajax call. For example:
if ($conn->query($query) === TRUE) {
echo json_encode(array('success' => true));
} else {
echo json_encode(array('success' => false,
'message' => "Error: Insert query failed"
)
);
}
Note that in general it's not secure to pass back query details and connection errors to the end user, better to pass back a generic message and log the actual error to a file or other location.
In your JavaScript:
$("a.bgbtb").click(function(){
var btnid = $(this).attr("id").split('newbudbtn-')[1];
var newbudget = $("INPUT[id=newbud-"+btnid+"]").val();
var platform = $("span#"+btnid).text();
$.ajax({
url:"campbdgtedit.php",
method:"POST",
data:{platform:platform, btnid:btnid, newbudget:newbudget},
dataType: 'json',
success:function(data){
if (data.success) {
// all good!
myAlertTop();
}
else {
// problems
alert(data.message);
}
}
});
});
If i understand correctly, you need to analyze the "echo" from the php side in the JS side in order to alert the appropriate error.
Use the "data" that is returned here:
success:function(data){
myAlertTop();
}
and do the following:
success:function(data){
myAlertTop(data);
}
function myAlertTop(replyfromPHPside)
{
if (replyfromPHPside =="abc")
{
alert('..');
}
else
{
...
}
}
I believe the best way is to echo out a json-string from PHP and "catch" the response in javascript like this:
campbdgtedit.php:
$query = "INSERT INTO campaigns (camp_budget, camp_campaignid) VALUES ('".$_POST['newbudget']."', '".$_POST['btnid']."')";
$arr = array();
if ($conn->query($query) === TRUE) {
$arr['response'] = true;
} else {
$arr['response'] = false;
}
echo json_encode($arr);
Javascript:
$("a.bgbtb").click(function(){
var btnid = $(this).attr("id").split('newbudbtn-')[1];
var newbudget = $("INPUT[id=newbud-"+btnid+"]").val();
var platform = $("span#"+btnid).text();
$.ajax({
url:"campbdgtedit.php",
method:"POST",
data:{platform:platform, btnid:btnid, newbudget:newbudget},
success:function(data){
if (data.response == 'true') {
alert('DB success');
}
else {
alert('DB fail');
}
}
});
});
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 :)
Alright, this is probably super simple but I've been breaking my head over this all day and I cannot get it to work.
I have a page that displays a list of users from a mysql query. On this page it should also be possible to add users. To do this, I'm sending an AJAX call to process.php which does some validation and sends an error if there is one. If there is no error, I want AJAX to update the page.
The problem is, that if there are no errors (a user has been added), I want to return the updated userlist. This means storing the output of my getUsers(); function in an array, which isn't possible.
How can I achieve this?
p.s. I realise this is crappy code and I should be using OOP/PDO, but this isn't for a production environment and it works. So I'll leave it like this for the time being.
users.php
<article>
<ul>
<?php getUsers(); ?>
</ul>
</article>
<form id="addUserForm">
...
<input type="hidden" name="addUser">
</form>
$("#addUserForm").on("submit",function() {
event.preventDefault();
var data = $("#addUserForm").serialize();
$.ajax({
type: "POST",
url: "process.php",
data: data,
dataType: "json",
success: function(response) {
if (response.success) {
$("article ul).html(response.data);
} else {
$(".errorMessage).html("<p>" + response.error + </p>");
}
}
});
});
functions.php
function getUsers()
{
global $db;
$query = mysqli_query($db, "SELECT * FROM users");
while($row = mysqli_fetch_assoc($query))
{
echo "<li>" . $row["user_firstname"] . "</li>";
}
}
function addUser($email, $password)
{
global $db;
$result = mysqli_query($db, "INSERT INTO users ... ");
return $result
}
process.php
if (isset($_POST["addUser"]))
{
... // Serialize data
if (empty ...)
{
$responseArray = ["success" => false, "error" => "Fields cannot be empty"];
echo json_encode($responseArray);
}
// If user is successfully added to database, send updated userlist to AJAX
if (addUser($email, $password))
{
$responseArray = ["success" => true, "data" => getUsers();];
echo json_encode($responseArray)
}
}
Your getUsers() function is printing and not returning the data to json connstructor
function getUsers()
{
global $db;
$query = mysqli_query($db, "SELECT * FROM users");
while($row = mysqli_fetch_assoc($query))
{
echo "<li>" . $row["user_firstname"] . "</li>";
}
}
it has to be something like this
function getUsers()
{
global $db;
$query = mysqli_query($db, "SELECT * FROM users");
$list = "";
while($row = mysqli_fetch_assoc($query))
{
$list. = "<li>" . $row["user_firstname"] . "</li>";
}
return $list;
}
And there is a syntax error in the following line
if (addUser($email, $password)
close it with ")"
You can capture the output of the getUsers function without changing the current behavior if that's what you're after. In the success output change
$responseArray = ["success" => true, "data" => getUsers();];
echo json_encode($responseArray)
to
ob_start();
getUsers();
$usersList = ob_get_clean();
$responseArray = ["success" => true, "data" => $usersList];
echo json_encode($responseArray)
What this does is captures the output and stores it into a varable $usersList which you can then return as a string.
You'd be better off returning the users as an array and dealing with generating the markup on the client side IMO, but that's up to you. This is just another way to get what you have working.
More information about php's output buffer here
Are you trying to get the error returned by ajax or you want to have custom error? (e.g. string returned by your php script). If you're referring to ajax error you should have this:
EDIT: Since you mentioned you want a custom error returned by process.php
Process.php
if (isset($_POST["addUser"]))
{
... // Serialize data
if (empty ...)
{
$responseArray = ["success" => false, "error" => "Fields cannot be empty"];
echo json_encode($responseArray);
}
// If user is successfully added to database, send updated userlist to AJAX
if (addUser($email, $password))
{
$responseArray = ["success" => true, "data" => getUsers();];
echo json_encode($responseArray)
}else{
echo 1;
}
//I added else echo 1;
}
Your ajax will be:
$("#addUserForm").on("submit",function() {
event.preventDefault();
var data = $("#addUserForm").serialize();
$.ajax({
type: "POST",
url: "process.php",
data: data,
dataType: "json",
success: function(response) {
if(response != 1){
$("article ul").html(response.data);
}else{
alert('Custom error!');
}
},
error: function(jqXhr, textStatus, errorThrown){
console.log(errorThrown);
}
});
});
BTW you're missing ) in your posted code if (addUser($email, $password))
This is how I do:
try{dataObj = eval("("+response+")");}
catch(e){return;}
alert(dataObj->example_key);
I am having difficulty with properly setting up JSON post to get number of rows from MYSQL database from a php file. I am getting "undefined" alert, when I am looking to alert the number of rows as an integer. I have been using a different stackoverflow post to try to build this Get variable from PHP file using JQuery/AJAX.
Here is the ajax call:
// check number of records in Mine
$.ajax({
url: 'pyrAddToMine.php',
type: 'POST',
success : function (result) {
alert(result['ajax']); // "Hello world!" alerted
console.log(result['numRec']) // The value of your php $row['numRec'] will be displayed
},
error : function () {
alert("error");
}
});
Here is the php code in pyrAddToMine.php:
mysql_select_db($database_cms_test, $cms_test);
$query = "SELECT * FROM $favUserTableName";
$result = mysql_query($query) or die();
$row = mysql_fetch_array($result);
$num_records = mysql_numrows($result);
IF ($num_records >= 15){
$numRec = array(
'ajax' => 'Hello world!',
'numRec' => $num_records,
);
echo json_encode($numRec);
exit;
}
Here are more details on the php file:
<?php
require_once('../Connections/cms_test2.php');
...
mysql_select_db($database_cms_test, $cms_test);
$query = "SELECT * FROM `$favUserTableName`";
$result = mysql_query($query) or die();
$row = mysql_fetch_array($result);
$num_records = mysql_numrows($result);
IF ($num_records >= 15){
$numRec = array(
'ajax' => 'Hello world!',
'numRec' => $num_records,
);
echo json_encode($numRec);
exit;
}
...
?>
Hello you forgot to specify the datatype
$.ajax({
url : 'myAjaxFile.php',
type : 'POST',
data : data,
dataType : 'json',
success : function (result) {
alert(result['ajax']); // "Hello world!" alerted
console.log(result['advert']) // The value of your php $row['adverts'] will be displayed
},
error : function () {
alert("error");
}
})
if you do not set required options for accepting json, you recieve an string that contain ajax format and you did not recieve an object in javascript
$.ajax({
url: 'pyrAddToMine.php',
type: 'POST',
/* required for accept json for ajax */
accepts:'application/json',
dataType:'json',
/* */
success : function (result) {
alert(result['ajax']); // "Hello world!" alerted
console.log(result['numRec']) // The value of your php $row['numRec'] will be displayed
},
error : function () {
alert("error");
}
});
I have created a registration system that uses AJAX to process the form so that I can return false. The relevant js is the top block of code. I pass this data to join.php, which sends it to the database. I run a check in join.php to make sure that nobody with a duplicate email has already signed up. As you can see, if the email already exists, I want to insert a message using javascript. Instead of reading the script tags, it simply pastes them into my alert in plaintext...so my alert has the datastring and then actually says the code <script>...</script>. How can I get this js to process instead?
Javascript:
$(".submit").click(function() {
var dataString = {
school : $("#school").val(),
studentEmail : $("#studentEmail").val(),
studentPassword : $("#studentPassword").val(),
parentEmail : $("#parentEmail").val(),
parentPassword : $("#parentPassword").val(),
studentFirstName : $("#studentFirstName").val(),
studentLastName : $("#studentLastName").val(),
studentPhone : $("#studentPhone").val(),
parentFirstName : $("#parentFirstName").val(),
parentLastName : $("#parentLastName").val(),
parentPhone : $("#parentPhone").val()
};
$.ajax({
type: "POST",
url: "join.php",
data: dataString,
success: function(data) {
alert ("data sent: "+ data);
}
});
return false;
}
});
join.php
if($_POST) {
$school = mysql_real_escape_string($_POST['school']);
$studentEmail = mysql_real_escape_string($_POST['studentEmail']);
$parentEmail = mysql_real_escape_string($_POST['parentEmail']);
$studentFirstName = mysql_real_escape_string($_POST['studentFirstName']);
$studentLastName = mysql_real_escape_string($_POST['studentLastName']);
$studentPhone = mysql_real_escape_string($_POST['studentPhone']);
$parentFirstName = mysql_real_escape_string($_POST['parentFirstName']);
$parentLastName = mysql_real_escape_string($_POST['parentLastName']);
$parentPhone = mysql_real_escape_string($_POST['parentPhone']);
$check = mysql_query("SELECT studentEmail FROM clients WHERE studentEmail = '{$studentEmail}';");
$num = mysql_num_rows($check);
if (($num) == 0) {
$sql = "INSERT INTO clients ".
"(`studentEmail`, `studentPassword`, `parentEmail`, `parentPassword`, ".
"`studentFirstName`, `studentLastName`, `studentPhone`, `parentFirstName`, ".
"`parentLastName`, `parentPhone`, `school`) ".
" VALUES ('$studentEmail', '$studentPassword', '$parentEmail', ".
"'$parentPassword', '$studentFirstName', '$studentLastName', ".
"'$studentPhone', '$parentFirstName', '$parentLastName', '$parentPhone', '$school')";
$result = mysql_query($sql);
if ($result) {
echo "Database query successful!";
}
else {
die("Database query failed: " . mysql_error());
}
include "emails/signUp.php";
}
else {
echo 'FAIL
<script>
$(".formErrorMessage").html("Email already exists");
</script>';
}
}
The alert shows your script block because you've got this in your success handler:
alert ("data sent: "+ data);
Data is going to be whatever text you output in your PHP. If you want to have variable behavior based on whether your request was successful or not, I'd recommend that your PHP returns JSON containing a success flag and the message. Your JavaScript callback would then look like this:
function(data) {
if (data.success) {
alert ("data sent: "+ data.message);
} else {
$(".formErrorMessage").text(data.message);
}
}
Your PHP should then change your content-type to JSON:
header('Content-Type: application/json');
... and your echos would change to something like this:
echo '{"success": false, "message": "Email already exists."}';
Your server call shouldn't be returning raw HTML. Should return JSON that contains all the status information the server needs to handle things. i.e. in the usual case:
{'success': true}
or
{'success': false, 'emailAlreadyExists': true, 'msg': 'Email Already Exists'}
of
{'success': false, 'msg': 'Database query failed: blahblahMySqlError'}
Then your client JS should handle it...
$.ajax({
type: "POST",
url: "join.php",
data: dataString,
success: function(data) {
if(data.success) {
alert ("success!");
}
else{
alert("error: " + data.msg);
if(data.emailAlreadyExists){
$(".formErrorMessage").html("Email already exists");
}
}
}
});
from php, you have give formatted status responses
on success:
echo '{"status":"success", message:"Database query successful!"}';
if account already exists:
echo '{"status":"failed", message:"Email already exists"}';
So you will be able to identify this in JavaScript callback function
$.ajax({
type: "POST",
url: "join.php",
data: dataString,
success: function(data) {
if(status.error == "failed"){
$(".formErrorMessage").html(data.message);
}
}
});
This is the best way to do it. Or if you just want to execute a string received from php, you can use eval
success: function(data) {
eval(data);
}
In that case there is no need of script tags in response, only the Javascript statement that has to be executed.