I was wondering if there is anyway to make this:
<form action="http[://localhost/.../script.php" method="POST">
a regular call. I don't want it to run on form submit, but instead I wan't it to run when I call a function.
Would I use jQuery or AJAX?
You may use Fetch API on chrome to do so:
// building your form values
var data = new URLSearchParams();
data.set('var1', 'value 1');
data.set('var2', 'value 2');
// send to the endpoint
fetch("http://localhost/.../script.php", {
method: 'POST',
mode: 'no-cors',
cache: 'no-cache',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: data
}).then(function(response) {
// check the response object for result
// ...
});
You can use ajax to call the the php function and store its response.
$.ajax({url: "demo_test.txt", success: function(result){
$("#div1").html(result);
}});
Make sure u include jquery CDN
You could use AJAX to post data to your PHP script, which will then run.
Note that jQuery and AJAX are not alternatives for each other.
AJAX is an asynchronous HTTP request (which is what you want).
jQuery is a javascript library which you can use to make AJAX calls.
I would take a look at https://api.jquery.com/jQuery.post/
This is a shorthand function for making an ajax POST request. E.g.:
function triggerMyPhpScript(data) {
$.post("http://localhost/.../script.php", data, function(responseData) {
// do something with the response of your script
});
}
I also like the Fetch answer from Koala Yeung. This will also work fine on modern browsers. Keep in mind that if you want to support ancient browsers (e.g. internet explorer), you need to implement feature detection and a fallback in case fetch is not supported by the browser.
Related
I want to make a post request to an API (http://nairabox.com/food_documentation/) using Ajax but am kind of confused on how to go about it.
This is what I have tried so far:
$.ajax({
type: "POST",
url: "https://mapp.nairabox.com:8443/api/v1/food/",
dataType : "json",
data: { case: "browse"},
headers: {
'case': 'browse'
},
success: function(data){
console.log('success');
}
})
So far, it is returning no result.
What could I be getting wrong?
The API doc is here (http://nairabox.com/food_documentation/)
The documentation you link to does not say to add any custom HTTP request headers.
You, however, are doing so here:
headers: {
'case': 'browse'
},
The case data belongs in the data and only in the data.
By adding the custom header, you are preventing the request from being simple and triggering a preflight OPTIONS request which the server does not accept.
Remove the above and you will get a response (and your success function will fire … you should probably do something with the data argument though)
Note, also, that the documentation says you should pass latitude and longitude as well as case.
Unless you add them, the response you get is unlikely to be useful.
Is there any way to know what is the method (GET/POST/PUT/DELETE) of an ajax request in Javascript or Jquery?
I went through the docs but I couldn't get a solution. My aim is to set headers if the ajax request is not of GET method.
Instead of using jQuery for making AJAX calls, recommend using either native fetch or in case you need to support older browsers you can use https://github.com/github/fetch.
By default AJAX calls will be GET calls. If you want to use another HTTP method, then you need to set the method as an option. For example using native fetch
fetch('someURL', {
credentials: 'same-origin',
method: 'POST',
body: JSON.stringify(payload),
});
Another good read is https://davidwalsh.name/fetch.
This is while making the ajax call. If you want to what was the original call made from the response you get, unless the server explicitly sets the value in the header, I don't think you will be able to figure that out.
I was able to solve this.
$(document).ajaxSend(function(e, xhr, options) {
if(options.type != "GET") {
xhr.setRequestHeader(HEADER, VALUE);
}
});
options gives the type of the request that's being made.
Thank you everyone for help!
So I've got this jQuery AJAX call, and the response comes from the server in the form of a 302 redirect. I'd like to take this redirect and load it in an iframe, but when I try to view the header info with a javascript alert, it comes up null, even though firebug sees it correctly.
Here's the code, if it'll help:
$j.ajax({
type: 'POST',
url:'url.do',
data: formData,
complete: function(resp){
alert(resp.getAllResponseHeaders());
}
});
I don't really have access to the server-side stuff in order to move the URL to the response body, which I know would be the easiest solution, so any help with the parsing of the header would be fantastic.
cballou's solution will work if you are using an old version of jquery. In newer versions you can also try:
$.ajax({
type: 'POST',
url:'url.do',
data: formData,
success: function(data, textStatus, request){
alert(request.getResponseHeader('some_header'));
},
error: function (request, textStatus, errorThrown) {
alert(request.getResponseHeader('some_header'));
}
});
According to docs the XMLHttpRequest object is available as of jQuery 1.4.
If this is a CORS request, you may see all headers in debug tools (such as Chrome->Inspect Element->Network), but the xHR object will only retrieve the header (via xhr.getResponseHeader('Header')) if such a header is a simple response header:
Content-Type
Last-modified
Content-Language
Cache-Control
Expires
Pragma
If it is not in this set, it must be present in the Access-Control-Expose-Headers header returned by the server.
About the case in question, if it is a CORS request, one will only be able to retrieve the Location header through the XMLHttpRequest object if, and only if, the header below is also present:
Access-Control-Expose-Headers: Location
If its not a CORS request, XMLHttpRequest will have no problem retrieving it.
var geturl;
geturl = $.ajax({
type: "GET",
url: 'http://....',
success: function () {
alert("done!"+ geturl.getAllResponseHeaders());
}
});
The unfortunate truth about AJAX and the 302 redirect is that you can't get the headers from the return because the browser never gives them to the XHR. When a browser sees a 302 it automatically applies the redirect. In this case, you would see the header in firebug because the browser got it, but you would not see it in ajax, because the browser did not pass it. This is why the success and the error handlers never get called. Only the complete handler is called.
http://www.checkupdown.com/status/E302.html
The 302 response from the Web server should always include an alternative URL to which redirection should occur. If it does, a Web browser will immediately retry the alternative URL. So you never actually see a 302 error in a Web browser
Here are some stackoverflow posts on the subject. Some of the posts describe hacks to get around this issue.
How to manage a redirect request after a jQuery Ajax call
Catching 302 FOUND in JavaScript
HTTP redirect: 301 (permanent) vs. 302 (temporary)
The underlying XMLHttpRequest object used by jQuery will always silently follow redirects rather than return a 302 status code. Therefore, you can't use jQuery's AJAX request functionality to get the returned URL. Instead, you need to put all the data into a form and submit the form with the target attribute set to the value of the name attribute of the iframe:
$('#myIframe').attr('name', 'myIframe');
var form = $('<form method="POST" action="url.do"></form>').attr('target', 'myIframe');
$('<input type="hidden" />').attr({name: 'search', value: 'test'}).appendTo(form);
form.appendTo(document.body);
form.submit();
The server's url.do page will be loaded in the iframe, but when its 302 status arrives, the iframe will be redirected to the final destination.
UPDATE 2018 FOR JQUERY 3 AND LATER
I know this is an old question but none of the above solutions worked for me. Here is the solution that worked:
//I only created this function as I am making many ajax calls with different urls and appending the result to different divs
function makeAjaxCall(requestType, urlTo, resultAreaId){
var jqxhr = $.ajax({
type: requestType,
url: urlTo
});
//this section is executed when the server responds with no error
jqxhr.done(function(){
});
//this section is executed when the server responds with error
jqxhr.fail(function(){
})
//this section is always executed
jqxhr.always(function(){
console.log("getting header " + jqxhr.getResponseHeader('testHeader'));
});
}
try this:
type: "GET",
async: false,
complete: function (XMLHttpRequest, textStatus) {
var headers = XMLHttpRequest.getAllResponseHeaders();
}
+1 to PleaseStand
and here is my other hack:
after searching and found that the "cross ajax request" could not get response headers from XHR object, I gave up. and use iframe instead.
1. <iframe style="display:none"></iframe>
2. $("iframe").attr("src", "http://the_url_you_want_to_access")
//this is my aim!!!
3. $("iframe").contents().find('#someID').html()
This doesn't seem to be working :
$.ajaxSetup({
headers: {
Accept: 'application/vvv.website+json;version=1 ',
Authorization: 'Token token=\"FuHCLyY46\"'
}
});
I would have thought it would. If I add these filters specifically to my AJAX call then they do work. I'd like to do this globally for all AJAX calls.
I did some additional tests and the code you posted works perfectly. If you have problems with something in how the parameters are setup, you could always to go the beforeSend call and modify the xml request yourself.
$.ajaxSetup({
beforeSend: function (xhr)
{
xhr.setRequestHeader("Accept","application/vvv.website+json;version=1");
xhr.setRequestHeader("Authorization","Token token=\"FuHCLyY46\"");
}
});
It's also possible to do this in a framework-agnostic way by monkey-patching the open method:
var o = XMLHttpRequest.prototype.open;
XMLHttpRequest.prototype.open = function(){
var res = o.apply(this, arguments);
var err = new Error();
this.setRequestHeader('X-Ajax-Stack', JSON.stringify(err.stack));
return res;
}
In this example I'm sending stack trace information via a header, which allows the backend to know where Ajax requests originated, even if it's from third-party code that doesn't use jQuery.
(Note: careful about headers getting too big)
The beforeSend answer does not establish the same header's as adding header directly to the ajax call. So in order for jQuery to do this properly I add this :
headers: myGlobalHeaders
where myGlobalHeaders is a global variable. Unfortunately, I have to write this extra line on every single ajax call. Terrible! Maybe I'll edit the jQuery framework to handle this..
How can I use public APIs in a Javascript application? For example I want to make a call to the Zillow API using JQuery AJAX.
When issuing the request in JQuery AJAX (shown below) I get the following error:
XMLHttpRequest cannot load "MY HTTP REQUEST URL". Origin "MY WEB DOMAIN" is not allowed by Access-Control-Allow-Origin.
var requesturl = "http://www.zillow.com/webservice/GetRegionChildren.htm?zws-id="+zwsid+"&state="+state+"&city="+city+"&childtype=neighborhood";
Code:
var jqxhr = $.ajax({
url: requesturl
})
.done(function(data) {
console.log(data);
});
I've also tried adding crossDomain, dataType and headers params (shown below), but they haven't helped.
var jqxhr = $.ajax({
url: requesturl,
crossDomain: true,
dataType: 'xml',
headers: { 'Access-Control-Allow-Origin': '*' },
beforeSend: setHeader
})
.done(function(data) {
console.log(data);
});
Most popular public API's support JSONP request. Refer API documentation for details.
Cross ajax domain request is restricted. So you will be needing to make JSONP request. Don't worry JQuery will handle most of it.
Sounds like you need to register your url with Zillow, maybe contact them / hunt around on their doc pages. Also jquery has a get method which makes ajax requests even simpler. There's also getJSON if that is the return format.