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);
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 a button on my page :
<button class="play"></button>
When I click on it, it launches the video via jQuery
$('.play').on('click',function(){
player.play();
});
But I also want to add PHP code to save the user ID in the database when he clicks on that button.
How can I mix PHP & jQuery? I'm not used to Ajax, is it the solution?
Thanks for your help!
add a function:
function add_to_db(user_id){
$.post('add.php', {userId: user_id}, function(response){
//do something with the response
r = JSON.parse(response);
if (r.status === 'error'){
//handle the error
alert(r.message);
}
});
});
when you play do the following
$('.play').on('click',function(){
player.play();
user_id = //however you chose to set this in the page
add_to_db(user_id);
});
your add.php:
//perform your db update or insert
//if successful:
$response['status'] = 'success';
//else:
$response['status'] = 'error';
$response['message'] = 'update was not successful';
//look into try/catch blocks for more detailed error messaging.
//then send the response back
echo json_encode($response);
Try using ajax
$('.play').on('click',function(){
player.play();
$.ajax({
type: "POST",
url: "some.php", // your php file name
data:{id :"id"}, //pass your user id
success:function(data)
{
if(data==true)
alert("success");
else
alert("error");
}
});
}
some.php
<?php
$success=false; //Declare and initialize a variable
// do your code to update your database
//and check if the database is updated , if so set $success=true
echo $success;
?>
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.
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.
I keep getting the error alert. There is nothing wrong with the MYSQL part, the query gets executed and I can see the email addresses in the db.
The client side:
<script type="text/javascript">
$(function() {
$("form#subsribe_form").submit(function() {
var email = $("#email").val();
$.ajax({
url: "subscribe.php",
type: "POST",
data: {email: email},
dataType: "json",
success: function() {
alert("Thank you for subscribing!");
},
error: function() {
alert("There was an error. Try again please!");
}
});
return false;
});
});
</script>
The server side:
<?php
$user="username";
$password="password";
$database="database";
mysql_connect(localhost,$user,$password);
mysql_select_db($database) or die( "Unable to select database");
$senderEmail = isset( $_POST['email'] ) ? preg_replace( "/[^\.\-\_\#a-zA-Z0-9]/", "", $_POST['email'] ) : "";
if($senderEmail != "")
$query = "INSERT INTO participants(col1 , col2) VALUES (CURDATE(),'".$senderEmail."')";
mysql_query($query);
mysql_close();
$response_array['status'] = 'success';
echo json_encode($response_array);
?>
You need to provide the right content type if you're using JSON dataType. Before echo-ing the json, put the correct header.
<?php
header('Content-type: application/json');
echo json_encode($response_array);
?>
Additional fix, you should check whether the query succeed or not.
if(mysql_query($query)){
$response_array['status'] = 'success';
}else {
$response_array['status'] = 'error';
}
On the client side:
success: function(data) {
if(data.status == 'success'){
alert("Thank you for subscribing!");
}else if(data.status == 'error'){
alert("Error on query!");
}
},
Hope it helps.
Just so you know, you can use this for debugging. It helped me a lot, and still does
error:function(x,e) {
if (x.status==0) {
alert('You are offline!!\n Please Check Your Network.');
} else if(x.status==404) {
alert('Requested URL not found.');
} else if(x.status==500) {
alert('Internel Server Error.');
} else if(e=='parsererror') {
alert('Error.\nParsing JSON Request failed.');
} else if(e=='timeout'){
alert('Request Time out.');
} else {
alert('Unknow Error.\n'+x.responseText);
}
}
Some people recommend using HTTP status codes, but I rather despise that practice. e.g. If you're doing a search engine and the provided keywords have no results, the suggestion would be to return a 404 error.
However, I consider that wrong. HTTP status codes apply to the actual browser<->server connection. Everything about the connect went perfectly. The browser made a request, the server invoked your handler script. The script returned 'no rows'. Nothing in that signifies "404 page not found" - the page WAS found.
Instead, I favor divorcing the HTTP layer from the status of your server-side operations. Instead of simply returning some text in a json string, I always return a JSON data structure which encapsulates request status and request results.
e.g. in PHP you'd have
$results = array(
'error' => false,
'error_msg' => 'Everything A-OK',
'data' => array(....results of request here ...)
);
echo json_encode($results);
Then in your client-side code you'd have
if (!data.error) {
... got data, do something with it ...
} else {
... invoke error handler ...
}
In order to build an AJAX webservice, you need TWO files :
A calling Javascript that sends data as POST (could be as GET) using JQuery AJAX
A PHP webservice that returns a JSON object (this is convenient to return arrays or large amount of data)
So, first you call your webservice using this JQuery syntax, in the JavaScript file :
$.ajax({
url : 'mywebservice.php',
type : 'POST',
data : 'records_to_export=' + selected_ids, // On fait passer nos variables, exactement comme en GET, au script more_com.php
dataType : 'json',
success: function (data) {
alert("The file is "+data.fichierZIP);
},
error: function(data) {
//console.log(data);
var responseText=JSON.parse(data.responseText);
alert("Error(s) while building the ZIP file:\n"+responseText.messages);
}
});
Your PHP file (mywebservice.php, as written in the AJAX call) should include something like this in its end, to return a correct Success or Error status:
<?php
//...
//I am processing the data that the calling Javascript just ordered (it is in the $_POST). In this example (details not shown), I built a ZIP file and have its filename in variable "$filename"
//$errors is a string that may contain an error message while preparing the ZIP file
//In the end, I check if there has been an error, and if so, I return an error object
//...
if ($errors==''){
//if there is no error, the header is normal, and you return your JSON object to the calling JavaScript
header('Content-Type: application/json; charset=UTF-8');
$result=array();
$result['ZIPFILENAME'] = basename($filename);
print json_encode($result);
} else {
//if there is an error, you should return a special header, followed by another JSON object
header('HTTP/1.1 500 Internal Server Booboo');
header('Content-Type: application/json; charset=UTF-8');
$result=array();
$result['messages'] = $errors;
//feel free to add other information like $result['errorcode']
die(json_encode($result));
}
?>
Server side:
if (mysql_query($query)) {
// ...
}
else {
ajaxError();
}
Client side:
error: function() {
alert("There was an error. Try again please!");
},
success: function(){
alert("Thank you for subscribing!");
}
adding to the top answer: here is some sample code from PHP and Jquery:
$("#button").click(function () {
$.ajax({
type: "POST",
url: "handler.php",
data: dataString,
success: function(data) {
if(data.status == "success"){
/* alert("Thank you for subscribing!");*/
$(".title").html("");
$(".message").html(data.message)
.hide().fadeIn(1000, function() {
$(".message").append("");
}).delay(1000).fadeOut("fast");
/* setTimeout(function() {
window.location.href = "myhome.php";
}, 2500);*/
}
else if(data.status == "error"){
alert("Error on query!");
}
}
});
return false;
}
});
PHP - send custom message / status:
$response_array['status'] = 'success'; /* match error string in jquery if/else */
$response_array['message'] = 'RFQ Sent!'; /* add custom message */
header('Content-type: application/json');
echo json_encode($response_array);
I had the same issue. My problem was that my header type wasn't set properly.
I just added this before my json echo
header('Content-type: application/json');
...you may also want to check for cross site scripting issues...if your html pages comes from a different domain/port combi then your rest service, your browser may block the call.
Typically, right mouse->inspect on your html page.
Then look in the error console for errors like
Access to XMLHttpRequest at '...:8080' from origin '...:8383' has been blocked by
CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested
resource.