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.
Related
I'm making a site with several calls to PHP via AJAX, right now AJAX uses POST to get a echoed string from PHP and then compares that in a switch and then does what is required. Example in the code below
function submitPHP(dataForPHP){
//Runs ajax request
$.ajax({
type : "POST",
url : 'initPHP.php',
dataType : 'text',
data : dataForPHP,
success : function(data){
//Checks echoed data from PHP
switch(data){
case "LOGIN_ACCEPTED":
loggedInFunction();
break;
case "LOGIN_FAILED":
loggedInFailedFunction();
break;
}
}
});
}
I'm thinking if there is a way for the PHP to return what function (like "loggedInFunction();") I want to call instead of a string that I then have to compare and then call the function? I can change the AJAX to use JSON instead if that does it.
I've been looking around on other similar questions here on stack on most of them want to echo a whole function which is not what I want to do.
Thanks in advance!
I'd do this.
use HTTPS to perform login, HTTP really is insecure nowadays;
create a controller object with all allowed methods (actions);
call an action of that controller.
The idea of having a controller is convenient on several levels:
security: if a method is not in the controller you cannot call it, so it is a way to know what can be called and what is absolutely not possible to call;
cohesion: the methods are all next to each other and easier to maintain;
encapsulation: if there is any state it can be held easily inside the context of that object.
This is an example:
loginController = {
"acceptAction": function () {
},
"failAction": function () {
}
};
You can now call those methods from the AJAX handler. Say the server tells you what you must do. A verb so to speak, such as accept or fail. You can then do:
"success": function (data) {
loginController[data + "Action"]();
}
And that's it.
BTW: this is just the very basic MVC pattern. Oldie but goldie :)
I'm quite new to JavaScript/jQuery so please bear with. I have been trying to store the resulting JSON after an ajax request so I can use the login info from it later in my program. I get an error stating that "Data" is undefined. Here is the problematic code:
function LOGIN(){
$.ajax({
url: 'https://.......&JSONP=Data&.........',
success: function Success(){
var SessionData = Data();
(FunctionThatParsesJSON);
}
})
}
I have checked the URL manually and it works fine (including) being wrapped in the "Data" function. From what I have found online, this may be something to do with ajax been asynchronous. Can anyone suggest a way of storing the JSON so that I can use it later?
Try something like the following;
function LOGIN(){
$.ajax({
url: 'https://.......&JSONP=Data&.........',
success: function Success(data){
functionToProcessData(data)
})
}
When making your ajax call, you can handle the response given by assigning a parameter to the function. In the case above, I have passed the 'data' parameter to the success function allowing me to then use it in further functions (as demonstrated by 'functionToProcessData(data)'.
The response from ajax call is captured in success handler, in this case 'data'.
Check below code:
success: function(data){
var SessionData = data.VariableName;
// Here goes the remaining code.
}
})
Since people ask about explanation, thus putting few words:
When we do $.ajax, javascript does the async ajax call to the URL to fetch the data from server. We can provide callback function to the "success" property of the $.ajax. When your ajax request completed successfully, it will invoke registered success callback function. The first parameter to this function will be data came from server as response to your request.
success: function ( data ) {
console.log( data );
},
Hope this helps.
Internally everything uses promises. You can explore more on promises:
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise
Apparently you are using JSONP, so your code should look like this:
$.ajax({
url: 'https://.......&JSONP=Data&.........',
dataType:"jsonp",
success: function (data){
(no need to parse data);
}
});
Another option:
$.ajax({
url: 'https://.......&JSONP=Data&.........',
dataType:"jsonp"
})
.done(function (data){
(no need to parse data);
});
See the documentation and examples for more details.
success: function (data, textStatus, jqXHR){
these are the arguments which get passed to the success function. data would be the json returned.
I need to send variables (username+password) from a js function inside a .js file, to a PHP file, and store them inside the file.
I tried to use ajax but it doesn't work for me:
function func(){
var user = ...
var pass = ...
$.ajax({
type:"POST",
url:"myphp.php",
data: user,
success: function(){
alert("success!");
},
error: function(){
alert("error!")
}
});
}
when I open the PHP file I see nothing.
EDIT: my problem is much more basic. My ajax code just doesn't run inside the function. I have a .js file that contains only one function (the function above) and the ajax code doesn't get executed. I get no success nor error messages.
You need to pass the data to jQuery like this:
$.ajax({
type:"POST",
url:"myphp.php",
data: {user: user, password: pass},
success: function(data){
alert(data);
}
});
PHP won't have any problems parsing this, since jQuery automatically sends it in application/x-www-form-urlencoded. If you need to send JSON and have PHP read JSON, then that's a different story.
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
I'm trying to assign the contents of an xml file to a var, like so:
var testing = $.load('xx.xml');
$('#display').text(testing);
but it's not working. I tried the ".load" function as suggested in:
How to assign file contents into a Javascript var
and I had a look at the page they suggest form the jquery website, but I can't find something specific to assigning the contents of the .xml file to the var as a string.
I appreciate this is probably very obvious & I am arguably being lazy, but I have been trying random things for a while & cannot figure this out.
Thanks
EDIT! I was loading up the contents inside the load function, i didn't mean this, it's now edited.
Firstly, $.load isn't a defined function in the latest jQuery source, nor is it documented on the jQuery site.
Secondly, assuming you haven't modified jQuery's global AJAX settings, jQuery.fn.load and other request functions will be asynchronous, so you can't just assign the result to a variable because the function returns before the request has completed. You need to use callback handlers.
Try using $.ajax with a callback function instead:
var testing;
$.ajax('xx.xml', {
dataType: 'text',
success: function (data) {
testing = data;
$('#display').text(testing);
}
});
Since you want the data as text and the file appears to be XML, we're using dataType to tell jQuery to return the data as a string.
There is no $.load function. What you probably want is jQuery.get:
var xml;
$.get("xx.xml", function(data) {
xml = data;
});
As the file is retreived asynchronously, you need to assign the result to the variable inside the callback, which is executed when the request returns successfully. Note however that if you try and run code that depends on xml after the .get call, xml is going to be undefined because the callback won't have run yet. For example:
var xml;
$.get("xx.xml", function(data) {
xml = data;
//Do stuff with data here
});
console.log(xml); //Most likely undefined because asynchronous call has not completed
If you are trying to insert the results into a DOM element, then you can use the .load method:
$("#someElem").load("xx.xml");
if you are trying to get an xml from your server using ajax, you may try something like this -
function getXml()
{
var contents;
$.ajax({ url :'/website/method', type: 'GET', dataType :'xml', async : false,
cache : true, success : function(myXml){
contents = myXml;
}
});
return contents;
}