I am calling the JS function cancelAppointment on button click, I can confirm that the function is running okay as the first alert is shown.
I have followed many guides to try and get this to work but they are yielding no results.
At the moment the success message is not being showed and the row is not being deleted. I can confirm the PHP script works fine.
the function is as below:
<head>
<script>
//Making the call to ajax this is encased in a function so it is not called pre-maturely
function deleteAppointment()
{
jQuery(document).ready(function(){
alert("Trying to run!");
$.ajax({
type : "POST",
url : "http://www.website.com/delete_appointment.php",
//data : "",
success : function(response) {
//Success
alert("Deleted");
}
});
});
}
</script>
For the moment, until I get the ajax to work the PHP contains PDO, that will delete from both the Appointments & AppointmentLines table with an ID of 1000. I will parse this in once this first part works.
In Wordpress the jQuery library included in the noConflict() mode, so the global $ shortcut for jQuery is not available, see more details here.
To make it work change $ to jQuery:
function deleteAppointment()
{
jQuery.ajax({
type : "POST",
url : "http://www.website.com/delete_appointment.php",
success : function(response) {
alert("Deleted");
}
});
}
You need to define what response the Ajax method is expecting to receive.
Make the response either 'text' (as shown in the example bellow) or make the response 'json'. You just add 'dataType: "text"' as a setting to the ajax call.
$.ajax({
type : "POST",
url : "http://www.website.com/delete_appointment.php",
dataType : "text",
success : function(response) {
//Success
alert("Deleted");
}
});
Currently you're your success method is waiting for the value of "response" to be returned however you are not defining what it is.
EDIT: I was corrected that it should be dataType not data for the setting I was originally talking about.
I found the answer,
Because I was using wordpress you must use jQuery in place of $ I needed to wrap this in a DOM function with $ defined so that jQuery would understand $
I kept the data argument commented in the end.
This issue was caused due to wordpress requiring slightly different syntax when calling a jQuery function. Thanks for your help everyone.
Related
Okay, so I searched the web as much as I could and I couldn't find the solution on my problem. I also typed the question and searched for an answer as I saw similar questions to mine. Didn't help. I tried numerous solutions.
Well I have an index page that loads includes/data.php which loads the data from database and echo the .js format that is then loaded by function and display data on the page, so I have at the end of my index.php something like this:
<script type="text/javascript" src="includes/data.php"></script>
On the same index page I have a form that inserts data to database. If you refresh the page I will see refreshed includes/data.php along with new data I just inputted.
I am trying to implement AJAX so that when I click on the button I insert the data to database (already achieved this) and to refresh content of includes/data.php and index.php so it shows data right away without refreshing the index.php. This is my AJAX code:
$('#addtocal').submit( function() {
$.ajax({
url : $(this).attr('action'),
type : $(this).attr('method'),
data : $(this).serialize(),
success : function( data ) {
// This is the part where I am stuck.
},
error : function(){
$(".error").fadeIn(2000);
$(".error").fadeOut(2000);
}
});
return false;
});
Just to mention that #calendar is where main jquery function is loading the html content based on the info from /includes/data.php. Thank you in advance for any help you can provide and let me know if you need any other information from me in order to better assist me.
P.S. I saw many suggested using .load() to load content from includes/data.php but that is not working in my case as the content from includes/data.php needs to serve other jquery function that creates html on the fly and and place it in #calendar
I got it to work. What I did I inser aditional $.ajax inside the $.ajax and on completion and I called again again the jquery that uses /includes/data.php
so the code would be something like this:
$('#addtocal').submit( function() {
$.ajax({
url : $(this).attr('action'),
type : $(this).attr('method'),
data : $(this).serialize(),
success : function( data ) {
$.ajax({
url: "../includes/data.php",
dataType: "script",
cache: true
}).done(function() {
// Here I called other jquery function that uses ../includes/data.php
});
},
error : function(){
$(".error").fadeIn(2000);
$(".error").fadeOut(2000);
}
});
return false;
});
Thanks for your help anyway #Half Crazed gave me a clue so I get the $.getScript function and saw the way to call .js again so I tried and it worked.
Hi I am using ajax to do a post request. I think what I want to do is call a function within a php file but am a little confused if and how you do this, could anyone shed any light on this? This is what I have in my js file:
function callAjaxAddition2() {
arguments0 = jQuery('#code').val();
$.ajax({
type: "POST",
url: file.php",
data: {code: arguments0},
success: function(data) {
request( $posted )
}
});
return false;
}
'request' is a function within the php file.
Update I think I should be able to trigger what I need to using this: http://docs.woothemes.com/document/wc_api-the-woocommerce-api-callback/ if I put the url into the url field however that doesn't seem to work, how might I use a callback with ajax post?
First fix this line with the missing opening quote file.php".
You cannot call a PHP function through AJAX but can trigger when it needs to be called, the following demonstrates the same:
In your PHP, your code would be:
if(isset($_POST['code'])){
#'code' here is the identifier passed from AJAX
request($_POST['code']);
}
Once your function has been called, does the necessary and returns the output to AJAX, you can use the data parameter you have set to see what output was sent back from PHP:
success: function(data) {
alert(data); //contains the data returned from the
//PHP file after the execution of the function
}
Calling on a php file via ajax call is like running the script that you pass in the url parameter.
You don't get access to the inner functions, all you can do is pass data and get response.
If you want the request() function to be called in the script, you will have to call it in the php script.
My question regards the $.ajax() jQuery method. I can't get the success parameter in $.ajax() to work.
This works:
$.ajax({
type: 'POST',
url: "/getCodes.php?codes=billingCodes&parent="+$('#wClient').val(),
dataType: 'json',
success: window.alert("inside aJax statement")
});
This does not:
$.ajax({
type: 'POST',
url: "/getCodes.php?codes=billingCodes&parent="+$('#wClient').val(),
dataType: 'json',
success: function(){
window.alert("inside aJax statement");
}
});
In the first case, I get a JavaScript alert window that lets me know the $.ajax() I called is working. All that is changed in the second block of code is I put the window.alert() inside a function() { window.alert(); }.
The point of this is to verify that the $.ajax is running so I can put some actual useful code in the function(){} when the $.ajax runs successfully.
In your second example nothing will happen unless you get a successful call back from the server. Add an error callback as many here have suggested to see that indeed the ajax request is working but the server is not currently sending a valid response.
$.ajax({
type: "POST",
url: "/getCodes.php?codes=billingCodes&parent="+$('#wClient').val(),
dataType:"json",
success: function(response){
alert(response);
},
error: function(jqXHR, textStatus, errorThrown){
alert('error');
}
});
helpful Link in tracking down errors.
Your first example does nothing whatsoever to prove that the ajax call has worked. All it does is prove that the ajax function was reached, because the values of the properties in the anonymous object you're passing into the ajax function are evaluated before the function is called.
Your first example is basically the same as this:
// THIS IS NOT A CORRECTION, IT'S AN ILLUSTRATION OF WHY THE FIRST EXAMPLE
// FROM THE OP IS WRONG
var alertResult = window.alert("inside aJax statement");
$.ajax({
type: 'POST',
url: "/getCodes.php?codes=billingCodes&parent=" + $('#wClient').val(),
dataType: 'json',
success: alertResult
})
E.g., first the alert is called and displayed, then the ajax call occurs with success referencing the return value from alert (which is probably undefined).
Your second example is correct. If you're not seeing the alert in your second example, it means that the ajax call is not completing successfully. Add an error callback to see why.
In first case window.alert is executed immidiatly when you run $.ajax
In second it run only when you receive answer from server, so I suspect that something wrong in you ajax request
You may want to try and use a promise:
var promise = $.ajax({
type: 'POST',
url: "/getCodes.php?codes=billingCodes&parent="+$('#wClient').val(),
dataType: 'json'
});
promise.fail( function() {
window.alert("Fail!");
});
promise.done( function() {
window.alert("Success!");
});
What this does is saves the ajax call to a variable, and then assigns additional functionality for each of the return states. Make sure that the data type you are returning is actually json, though, or you may see strange behavior!
Note that js is single-threaded; the reason your first example works is because it actually executes the code next 'success' and stores the result. In this case there is nothing to store; it just pops an alert window. That means that the ajax call is leaving the client after the alert is fired: use the developer tools on Chrome or equivalent to see this.
By putting a function there, you assign it to do something when the ajax call returns much later in the thread (or, more precisely, in a new thread started when the response comes back).
I think that you do it right, but your request does not succeeds. Try add also error handler:
error: function(){alert("Error");};
I guess that dataType does not match or something like that.
It is 100% your second example is correct. Why it does nothing? Maybe because there is no success in the ajax call.
Add "error" handler and check waht does your ajax call return with the browsers' developer tool -> Network -> XHR . This really helps in handling of broken / incorrect ajax requests
I am currently working on a project, in which I am getting some data using ajax jQuery. I am using the following code:
$.ajax({
dataType : 'html',
type: 'POST',
url : url,
//cache: false,
data : data,
complete : function() { },
success: function(data)
{
$('#servicelist').hide();
$('#stafflist').show();
data=$(data).find('div#stafflistcontent');
$('#stafflist').html(data);
}
});
When I am trying to alert the data at the very first line of ajax success,it is returning the complete HTML of the page, now I am going to find the <div id="stafflistcontent">. In Firefox and Chrome it is returning the correct HTML but in IE its returning only OBJECT OBJECT, How can I resolve this issue?
Edit
IE version : IE8
jQuery Version : 1.9.1
$(data).find('div#stafflistcontent') returns a jQuery object, not "data" (what ever you mean with that). .html() takes a string as it's parameter, so that shouldn't work like way.
Instead of
$('#stafflist').html(data);
use
$('#stafflist').empty().append(data);
If that doesn't work you'll need to show your HTML and exactly what your AJAX call returns.
replace:
$('#stafflist').html(data);
with:
$(data).html().appendTo('#stafflist');
or:
$("<p></p>").append($(data).html()).appendTo('#stafflist');
I have a function that makes an Ajax request for any anchor. The request method can be GET or POST. In this case, I want to make a POST without using a form but the Ajax request throws an error before even sending the request. The error has the value "error" and all error/failure description variables are "".
function loadPage(url,elem_id,method,data) {
ajaxLoading(elem_id);
$.ajax({
type: method,
url: url,
data: data,
success:function(data){
$("#"+elem_id).html(data);;
},
error:function(request,textStatus,error){
alert(error);
}
});
}
When the function is called the params are these (copied from the js console):
data: "partial=yes"
elem_id: "page"
method: "post"
url: "/projects/2/follow"
As asked, here is the code that calls the loadPage function.
$("body").on("click","a.ajax",function(event) {
var _elem = getDataElem($(this));
var _method = getRequestMethod($(this));
var _partial = getRequestPartial($(this));
handlers.do_request(event,$(this).attr("href"),_elem, _method, _partial);
});
var handlers = (function() {
var obj = {};
obj.do_request = function(event,url,elem_id,method,data) {
event.preventDefault();
loadPage(url,elem_id,method,data);
history.pushState({selector:elem_id,method:method,data:data},null,url);
};
}());
After the failure of the Ajax request, the request is made by default and it responds sucesss. In all I have read, this seems to be a valid way to make a POST request (that doesn't need a form).
Am I doing something wrong in the function? Why is the error information empty?
Thanks
EDIT:
I have been thinking, for a POST from a "form" that function works, when the variable "data" is made with the serialize function (e.g. "var data = $(this).serialize();"). Could it be that the format of the "data" when I make a POST without a "form" is wrong in someway? Maybe the JQuery Ajax function doesn't accept a simple string like "partial=yes" as data when a POST is made. Any thoughts on this?
I just experienced this problem and after an hour or two, thought to try setting cache to false. That fixed it for me.
$.ajax({
url: url,
cache: false,
type: method
});
Unfortunately, when I removed cache again, my request was working as if it had never had a problem. It seems as if setting cache:false made something 'click'.
Oh well.
Just a guess, but in the docs the type parameter is in all caps, i.e. 'POST' and not 'post'.
Try:
function loadPage(url,elem_id,method,dat) {
ajaxLoading(elem_id);
$.ajax({
type: method,
url: url,
data: dat,
success:function(data){
$("#"+elem_id).html(data);;
},
error:function(request,textStatus,error){
alert(error);
}
});
}
I'm wondering if you are running into a problem using a variable named after a keyword. If this doesn't work, try calling loadPage with no arguments and hard coding all of your ajax parameters, just to see if that works.
Could not solve the problem, neither could find the reason why it was happening. Although, I found a way around, by using a hidden empty form instead of an anchor with the method 'POST'. For a form, the function worked nicely.
Thanks for the answers