Method in Ajax other than POST and GET - ajax

I was asked in an interview what are the methods in AJAX other than GET and POST. I googled but I couldn't find any . Could someone please tell me.

HEAD Same as GET but returns only HTTP headers and no document body
PUT Uploads a representation of the specified URI
DELETE Deletes the specified resource
OPTIONS Returns the HTTP methods that the server supports
These are generally used methods
Also see detail about

There are four types of calls you cand do to a REST API GET,POST,PUT and DELETE. PUT should be suposedly used to modify already existing data while DELETE should be used to eliminate data. Still due to convention, PUT and DELETE are barely used. Here are a couple of examples of PUT and DELETE Ajax calls
$.ajax({
url: urlCalltoDeleteResource),
type: 'DELETE',
success: function(data) {
alert('Deleted');
},
error: function(data) {
alert('Not Deleted');
},
});
$.ajax({
url: urlToUpdate,
type: 'PUT',
data: "name=NameToUpdate",
success: function(data) {
alert('Load was performed.');
}
});

Related

get data from ajax as an attribute value for callback function

Im new to ajax. I was trying to find the answer but was not lucky to find the corresponsing one. Basically I need to use an ajax to get some data and after that to put this data to the variable that later will be used as an attribute for the callback function with custom code.
This ajax part is just a method of myObject.
So, in the end I need this kind of functionality:
myObject.getData(url, callback(data) {
//my custom code of what I wanna do after ajax is complete
});
My code
/*
HERE COME SOME PROPERTIES AND OTHER METHODS WICH IS NOT THE CASE
*/
//This is where Im stuck
var getData = function getFromUrl($url) {
$.ajax({
type: 'get',
url: $url,
dataType: 'html',
success: function(html) {
$obj = html;//Im lost on this step!
},
});
};
P.S. Im trying to find an async way (without using async:false). Hope its possible
First I encountered many problems. My first problem was No Access-Control-Allow-Origin, most websites dont allow you to just scrap get their data for security reasons. Luckily someone already made a proxy: http://cors.io/ . Second problem is that you cant embed http on https, so I cant use jsfiddle to show you this working, it works on my local enviroment. After you get the raw html you have to parse it, you can do it with full regex, or you can power yourself with jquery like I'm doing on this example. What we're doing is checking stackoverflow.com and getting the amount of featured questions with .find(".bounty-indicator-tab").first().html(); But once you have the full html you can get any data you need.
var getData = function getFromUrl(url) {
$.ajax({
url: 'http://cors.io/?' + url,
crossDomain: true,
dataType: 'html',
success: function (html) {
var match = $(html).find(".bounty-indicator-tab").first().html();
console.log(match);
return match;
},
error: function(e) {
console.log('Error: '+e);
}
});
};
url = 'http://stackoverflow.com/';
data = getData(url);
//You cant use data yet because its working async

Posting to Facebook app group via ajax is failing silently

Thank you in advance for any assistance you maybe able to provide. I'm trying to post from my app to an app group that I have created. Using the code below it completes the request successfully but the data returned is empty. Please tell me what I'm doing wrong. I did also notice that it's not performing a POST but rather a GET.
$.ajax({
type: 'POST',
url: 'https://graph.facebook.com/v2.1/'+g_id+'/feed?access_token='+User["User AccessToken"],
data: JSON.stringify({
message: g_mes
}),
dataType: "jsonp",
success: function(data){
console.log(data);
},
error: function(data1){
console.log(data1);
}
})
You really should use the JavaScript SDK for the API. Here is a basic tutorial: https://developers.facebook.com/docs/javascript/quickstart/v2.1
And this is what the API call would look like:
FB.api('/' + g_id + '/feed', 'post', {message: g_mes}, function(response) {
console.log(response);
});
See Facebook docs for a code example too: https://developers.facebook.com/docs/graph-api/reference/v2.1/group/feed
You donĀ“t even need to worry about the Access Token. You just need to use FB.login with the appropriate permissions in the scope parameter to authorize the user.

How to send and retrieve cross-domain ajax data in userscript

I use this code to store and retrieve ajax data via http://openkeyval.org/
$.ajax({ /* send data */
url: "http://api.openkeyval.org/store/",
data: "test-key-data=" + JSON.stringify([123,456]),
dataType: "jsonp",
success: function(data){
console.log(data);
}
});
$.ajax({ /* retrieve data */
url: "http://api.openkeyval.org/test-key-data",
dataType: "jsonp",
success: function(data){
console.log(data);
}
});
everything work fine in Chrome javascript console but in userscript I get error like this
Uncaught ReferenceError: jQuery110208458673823624849_1375932537303 is
not defined
I try to use GM_xmlhttpRequest to retrieve data like this
GM_xmlhttpRequest({
method: "GET",
url: "http://api.openkeyval.org/test-key-data",
onload: function(response) {
console.log(response.responseText);
}
});
but it seem like openkeyval doesn't accept data via POST/GET method and log result was like when you access it directly from url of browser like this
{"error":"not_found","documentation_url":"http://openkeyval.org/"}
I include jQuery and it work fine with this code
// #require http://code.jquery.com/jquery-latest.min.js
I try to use Greasemonkey/jQuery XHR bridge with out change other code by like this
// #require http://courses.ischool.berkeley.edu/i290-4/f09/resources/gm_jq_xhr.js
and try use openkeyval official javascript library with code like this
// #require http://cdn.openkeyval.org/statics/openkeyval.packed.js
and retrieve data with code like this
var ourCallback = function(value, key) {
console('The value of ' + key ' + is ' + value);
};
window.remoteStorage.getItem('test-key-data', ourCallback);
still got error ERROR: Unexpected string
Please help, I mess with it more than 10 hours. Thank you so much.
It look like $.ajax always trigger error event function
but GM_xmlhttpRequest can retrieve mistype data, so I try looking for dataType: "jsonp" in GM_xmlhttpRequest and I got that jsonp header content-type is "application/javascript" OR "application/json" and the first one work well.
my new code for retrieve data look like this
GM_xmlhttpRequest({
method: "GET",
url: "http://api.openkeyval.org/test-key-data?nocache=" + new Date(),
headers: {
"Content-Type": "application/javascript"
},
onload: function(response) {
console.log(response.responseText);
}
});
and retrieve data using $.ajax even it always trigger error event function but it still send data.
I try both content-type on GM_xmlhttpRequest and still not work.
my code to store data look like this
$.ajax({ /* send data */
url: "http://api.openkeyval.org/store/",
data: "test-key-data=" + JSON.stringify(myVarObject),
dataType: "jsonp"
});
Add this into $.ajax({...})
crossDomain: true;
It is because by default cross domain ability is disabled. See http://api.jquery.com/jQuery.ajax/
EDIT:
Sometimes there will be a issue with different charset between local script and remote script. Try using:
scriptCharset: "utf-8";
Also look at JQuery AJAX is not sending UTF-8 to my server, only in IE
Elaborating my comment
The reference is to the callback function generated by jquery.
It Sounds to me the way you invoke your userscript unloads the jquery functions before the callback is executed.
Perhaps you use a link and forgot the preventDefault?
If you ajax and have
$("#linkid").on("click"
or
$("#formid").on("submit"
it is MANDATORY to continue like this:
,function(e) {
e.preventDefault();
Otherwise the link is followed or the form is submitted which may not have any visible effect, but the asynchronous scripts have been (partially) unloaded unless the form and link has a target other than the current window

GET and POST in ajax

I have a C# web application which uses ajax method to GET and POST data. Is there any difference between GET and POST methods in passing data (in case of contentType,data,dataType)?
$.ajax({
type: 'GET',
url: "url",
contentType: "application/json; charset=utf-8",
data: { value: "data" },
dataType:"json",
success: function (data) {
alert(data);
},
error: function (data) {
alert("In error");
}
});
});
GET encodes the information into the url, the more info you GET the longer your URL becomes.
POST stores data in an array and passes that array to the next page. your Url remains unmodified.
While that may not seem like a huge deal, URLs do have a maximum length and errors will ensue if you exceed it. In addition and call to a specific url may fail due to the modifications GET makes. Apart from that, They are similar enough in function to be interchangeable for most purposes.
In normal form method also GET is used to sent some insensitive small chunk of data to server in querystring, whereas POST is used for sending large and secure data to the server
In case of using ajax GET is commonly used, POST is feasible only when you have to do DB interactions on server or there's some sensitive data involved, read more here http://www.jquery4u.com/ajax/key-differences-post/

Jquery AJAX for fetching JSON, affected by URL prefix (www vs. no www)?

I have come across a peculiar item in JQuery that I am hoping somebody can help me to understand.
I've spent much of the day trying to get JQUERY's AJAX 'success' function to be raised when returning JSON from the server.
I checked the JSON # JSONLint to ensure validity, checked encoding, tried different headers, but still PROBLEMS.
After a couple hours, I switched the url (by accident!)
from
http//www.testing.com/_r4444/myfile.php
to the exact same thing WITHOUT the www... and it suddenly worked.
I have no clue why this would be the case - any ideas?
the snippet follows
$(document).ready(function() {
$.ajax( {
type: "POST",
contentType: "application/json",
url: "http://testing.com/_r4444/getter.php",
beforeSend: function(x) {
if(x && x.overrideMimeType) x.overrideMimeType("application/json;charset=UTF-8");
},
data: "pass=TEST",
dataType: "json",
error: function (xhr, status) {
alert(status);
},
success: function (result) {
alert(result);
}
});
});
Are you using "www" on the page in the browser?
Try switching the call to not include the domain, like:
"/_r4444/getter.php" instead of the full domain.

Resources