AJAX: How to send back a success/error message - php

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');
}
}
});
});

Related

Ajax post does not give value to php file, post becomes get

I have this ajax function for login.
Edit: I just noticed that this server runs php7 while other server where the login does work uses php5. What has changed in php that this script doesn't work anymore?
Edit 2: Looks like the server request method isn't post but changed to get, why?
Solution: needed to remove the .php from url: "./ajaxcall/login.php", because I use pretty url htaccess.😅
var InName = $('#InName').val();
var InPass = $('#InPass').val();
alert(InName);
$.ajax({
type: "POST",
url: "./ajaxcall/login.php",
dataType: "json",
data: {InName:InName, InPass:InPass},
error: function (request, error) {
console.log(arguments);
alert("Inlog Can't do because: " + error);
},
success : function(data){
if (data.code == "200"){
$("#InErEr").html(data.msg);
//window.location.reload(true);
} else {
$("#InErEr").html(data.msg);
$('.lds-dual-ring').animate({opacity: 0}, 300);
}
}
});
On the alert(InName); I get the correct value of the username. But when I check in my php file $_POST['InName'] it is empty.
Part of php file
include('../config.php');
if(empty($_POST['InName'])) {
$Ierror = 'Username is required.';
}
if($_POST['InPass'] == '') {
$Ierror = 'Password is required.';
}
$username = $_POST['InName'];
$passwordL = $_POST['InPass'];
// count user in between //
if($Inlognumber_of_rows == 0) {
$Ierror = 'Username not found.';
} else {
// password check //
if(password_verify($salty_pass, $hashed_password)) {
} else {
$Ierror = 'Password incorrect.';
}
}
if ($Ierror == '') {
// do login //
} else {
$showerror = '<span style="color:#F00;">'.$Ierror.$username.$passwordL.$_POST['InName'].$_POST['InPass'].'</span>';
echo json_encode(['code'=>404, 'msg'=>$showerror]);
exit;
}
In the return message, $showerror I only get, Username not found, without the posted values. So the login is not working because of empty values? User is also present in the database of course. I also don't get the empty $_POST errors. So to cap up, in javascript I get the correct value for InName but not in php.
You are close but your error catch is not correct ... try this (Jquery):
var InName = 'something';
var InPass = 'morething';
$.post("./ajaxcall/login.php", {
InName: InName,
InPass: InPass
}, function(data, status) {
console.log(data, status);
}).done(function() {
alert("second success");
})
.fail(function() {
alert("error");
})
.always(function() {
alert("finished");
});
on your php file just do print_r($_POST); and you will receive this in your console...:
Array
(
[InName] => something
[InPass] => morething
)
success
Basically you were trying to print the error where you should have consoled log the request.responeText...
A good trick to know if posts arrived to the php even if the console.log won't show is doing this in the php file:
<?php
print_r($_POST) ;
$newfile = fopen('newfile.txt','a');
fwrite($newfile,json_encode($_POST));
fclose($newfile);
This will print and also store on a local file the post data....
Solution: needed to remove the .php from url: "./ajaxcall/login.php", because I use pretty url htaccess.😅

Confirming A Database Row was deleted via PHP in aJax/jQuery

I'm trying to figure out the best way to relay back to ajax if the POST data sent to the .php file successfully deleted the data from the database. I'm not sure what to phrase what I'm looking for, but essentially I thought about a 'if() { } else { }' statement perhaps, but I'm not sure how to send the data back correctly into the success:function. Here is the basic code below that ajax is using. The PHP file is just standard code for running a deletion via php/mysqli.
$.ajax({
url: "../ajax/modules/delete-from-db.php",
data:{},
type:'POST',
success:function(data){
//IF() {
//EXECUTE SUCCESS & REMOVE DIV
//} ELSE {
//GIVE NOTICE OF DELETION FAILURE
//}
}
});
So anyone have any ideas how I could accomplish this?
On your php. depends on what you are using, you can check if the query was successful or not. then you can add anything on your return statement that you could use on your ajax success funtion.
Example:
on the php side using PDO
$success = true;
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$sql = "DELETE FROM MyGuests WHERE id=3";
$conn->exec($sql);
} catch (PDOException $e) {
$success = false;
}
return json_encode([
'success' => $success
])
Then on ajax. you can use this
$.ajax({
url: "../ajax/modules/delete-from-db.php",
data:{},
type:'POST',
success:function(data){
IF(data.success) {
//EXECUTE SUCCESS & REMOVE DIV
} ELSE {
//GIVE NOTICE OF DELETION FAILURE
}
}});
Some changes in your php file. if delete query return success then return true or 1 otherwise false or 0.
$.ajax({
url: "../ajax/modules/delete-from-db.php",
data:{},
type:'POST',
success:function(data){
if(data == 1){
alert("success");
} else {
alert("error");
}
}
});
it depends on what you send back from your php script, i recommend JSON which you could format as such
{
status:"success",//or error if failed
message:"record was successfully deleted"
}
in the php script you could have a Boolean flag to check if the record was deleted eg:
if($deleteFlag){
$response = array('status'=>'success', 'message'=>'record was successfully deleted');
} else {
$response = array('status'=>'error', 'message'=>'could not delete record!');
}
header('Content-type: application/json');
echo json_encode($response);

Php function return is an empty array using Ajax otherwise not

I'm using CakePHP framework. My problem is that when I print a php function then it gives me an array with a lot of members but when using the same function with Ajax then the response is empty.
Ajax response function:
public function functionOne(){
$this->autoRender = false;
if ($this->request->is('ajax')) {
if(!$this->request->data['amount']) {
$json['errors'][] = 'Fill in all the required fields';
}elseif(!is_numeric($this->request->data['amount'])){
$json['errors'][] = 'Field amound has to be a number';
}
if(!$this->request->data['currency_from']){
$json['errors'][] = 'Fill in all the required fields';
}
if(!$this->request->data['currency_to']){
$json['errors'][] = 'Fill in all the required fields';
}
if(!$this->request->data['rate_date']){
$json['errors'][] = 'Fill in all the required fields';
}
if(isset($json['errors'])){
$json['status'] = 'error';
}else{
$json['status'] = 'success';
$json['curs'] = $this->functionTwo($this->request->data['date1']);
$json['rates'] = $this->functionThree($this->request->data['date'], $this->request->data['from'], $this->request->data['to'], $this->request->data['amount']);
}
print_r(json_encode($json));
}
}
View file ajax request:
$(document).ready(function(){
$('#converter').on('submit', function(e) {
var form = $(this);
e.preventDefault();
$.ajax({
url: '<?php echo $this->Html->url(array(
"controller" => "cur",
"action" => "functionOne"
));
?>',
data: form.serialize(),
type: 'post',
async: true,
success: function (data) {
var json = data;
if (json.status == 'error') {
$('#errors').show();
$('#currencies').hide();
$('#errors').html('');
$.each(json.errors, function (k, v) {
$('#errors').append("<span>" + v + "</span>");
});
}
if (json.status == 'success') {
var json = data;
$('#errors').hide();
$('#currencies').show();
}
}
});
})
});
getCur method returns an array in format "code" => "name". It gets the currencies from reading different sources XML files. When I print the function outside of the response it gives me a correct result but with ajax it just gives me an empty array.
Errors are coming through the response though.
Thanks!
What version of Cake are you using??
Depends on the version of cake.
1.3.x:
$this->RequestHandler->isAjax();
2.x
$this->request->is('ajax');
Also can you check your chrome network tab for any specific issue.
Try to :
echo your json like echo json_encode($json);
In success callback, parse data variable by using :
success : function(data){
var json = $.parseJSON(data);
console.log(json);
}
See the data inside console.
Mistake was that I created the instances inside the method so ajax thought that I did not have any.
Thanks for replying!

Using Ajax to generate an alert box

I want to pop up an alert box after checking whether some data is stored in the database. If stored, it will alert saved, else not saved.
This is my ajax function:
AjaxRequest.POST(
{
'url':'GroupsHandler.php'
,'onSuccess':function(creategroupajax){ alert('Saved!'); }
,'onError':function(creategroupajax){ alert('not saved');}
}
);
but now it show AjaxRequest is undefined.
How can I fix this?
This of course is possible using Ajax.
Consider the below sample code for the same.
Ajax call :
$.ajax({
url: 'ajax/example.php',
success: function(data) {
if(data == "success")
alert('Data saved.');
}
});
example.php's code
<?php
$bool_is_data_saved = false;
#Database processing logic here i.e
#$bool_is_data_saved is set here in the database processing logic
if($bool_is_data_saved) {
echo "success";
}
exit;
?>
function Ajax(data_location){
var xml;
try {
xml = new XMLHttpRequest();
} catch (err){
try {
xml = new ActiveXObject("Msxml2.XMLHTTP");
} catch (error){
try {
xml = new ActiveXObject("Microsoft.XMLHTTP");
} catch (error1){
//
}
}
}
xml.onreadystatechange = function(){
if(xml.readyState == 4 && xml.status == 200){
alert("data available");
}
}
xml.open("GET", data_location, true);
xml.send(null);
}
window.onload = function(){
Ajax("data_file_location");
}
You can create an addtitional table with date(time) of last update database and check if this date is later. You can use standard setInterval function for it.
This is possible using ajax. Use jQuery.ajax/pos/get to call the php script that saves the data or just checks if the data was saved previously (depends on how you need it exactly) and then use the succes/failure callbacks to handle its response and display an alert if you get the correct response.
Below code based on jQuery.
Try it
$.ajax({
type: 'POST',
url: 'http://kyleschaeffer.com/feed/',
data: { postVar1: 'theValue1', postVar2: 'theValue2' },
beforeSend:function(){
// this is where we append a loading image
$('#ajax-panel').html('<div class="loading"><img src="/images/loading.gif" alt="Loading..." /></div>');
},
success:function(data){
// successful request; do something with the data
$('#ajax-panel').empty();
$(data).find('item').each(function(i){
$('#ajax-panel').append('<h4>' + $(this).find('title').text() + '</h4><p>' + $(this).find('link').text() + '</p>');
});
},
error:function(){
// failed request; give feedback to user
$('#ajax-panel').html('<p class="error"><strong>Oops!</strong> Try that again in a few moments.</p>');
}
});
use the ajax to call the script and check values in the database through the script. If
data present echo success else not.lets look an example of it.
Assuming databasename = db
Assuming tablename = tb
Assuming tableColumn = data
Assuming server = localhost
Ajax:
$.ajax({
url: 'GroupsHandler.php',
success:function(data){
if(data=="saved")
{
alert("success");
}
}
});
Now in the myphpscript.php :
<?php
$Query = "select data from table";
$con = mysql_connect("localhost","user","pwd"); //connect to server
mysql_select_db("db", $con); //select the appropriate database
$data=mysql_query($Query); //process query and retrieve data
mysql_close($con); //close connection
if(!$empty(mysql_fetch_array($data))
{
echo "saved";
}
else
{
echo " not saved ";
}
?>
EDIT:
You must also include jquery file to make this type of ajax request.Include this at the top of your ajax call page.
<script src='ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js' type='text/javascript'></script>
First, decide whether to use POST or GET (I recommend POST) to pass AJAX data. Make a php file (ajax.php) such that it echos true or false after checking whether some data is stored in the database. You may test with a variable $your_variable = "some_data_to_check"; having a data inside and once you are finished, you may replace it with $your_variable = $_POST["ajaxdata"];.
Then in your page, set up AJAX using jQuery plugin like:
var your_data_variable = "data_to_send";
$.ajax({
type: "POST",
url: "ajax.php",
data: 'ajaxdata=' + your_data_variable,
success: function(result){
if(result == "true"){
alert("saved");
}else{
alert("not saved");
}
}
You may have a look at jQuery AJAX Tutorial, Example: Simplify Ajax development with jQuery.

Echoed Javascript appearing in alert instead of processing

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.

Categories