difference between XMLHttpRequest and $ajax - javascript

Hello I have read about jQuery ajax method, jQuery wraps some XMLHttpRequest inside.
I need(want) to redo next stuff to $ajax, but I worried about parameters. Is it possible send to $ajax url with parameters without param key, just in URL param ?
var element ;
...
if (window.XMLHttpRequest) { // Mozilla, Safari,...
http_request = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE
http_request = new ActiveXObject("Microsoft.XMLHTTP");
}
http_request.onreadystatechange = function() { alertContents(element); };
url = unescape(url + parameters);
http_request.open('GET', url, true);
http_request.send(null);

Use this same code for ajax consumes the time
$.ajax({
type: "get",
url: "geocode.php?address="+address,
dataType: "xml",
//async:true,
success : function(xmlData){
alert(xmlData);
},
error : function(){
alert("Could not retrieve XML file.");
}
});

if you want to use $.ajax you could write
$.ajax({
url: url,
type: "GET",
data: parameters
success: function(data) {
alertContents(element);
}
});

Pretty much anything you can do using the XMLHttpRequest you can do with jQuery (jQuery uses XMLHttpRequest for ajax).
$.ajax({
url: url + parameters,
type: "GET",
success: function(data){
alert(data);
}
});
you could also set the parameters in the data option so that the type option will send it as POST or GET based on what you supply to it.
$.ajax({
url: url,
data: parameters,
type: "GET", // or POST, or any other valid type
success: function(data){
alert(data);
}
});

If I'm understanding your question correctly, the answer is yes, you can.
The following are equivalent:
$.ajax({
url: "some.php?name=John&location=Boston"
});
$.ajax({
url: "some.php",
data: "name=John&location=Boston"
});
$.ajax({
url: "some.php",
data: {
name : "John",
location : "Boston"
}
});

Related

How to delete or post data using ajax(POST,DELETE) [duplicate]

GET:$.get(..)
POST:$.post()..
What about PUT/DELETE?
You could use the ajax method:
$.ajax({
url: '/script.cgi',
type: 'DELETE',
success: function(result) {
// Do something with the result
}
});
$.ajax will work.
$.ajax({
url: 'script.php',
type: 'PUT',
success: function(response) {
//...
}
});
We can extend jQuery to make shortcuts for PUT and DELETE:
jQuery.each( [ "put", "delete" ], function( i, method ) {
jQuery[ method ] = function( url, data, callback, type ) {
if ( jQuery.isFunction( data ) ) {
type = type || callback;
callback = data;
data = undefined;
}
return jQuery.ajax({
url: url,
type: method,
dataType: type,
data: data,
success: callback
});
};
});
and now you can use:
$.put('http://stackoverflow.com/posts/22786755/edit', {text:'new text'}, function(result){
console.log(result);
})
copy from here
Seems to be possible with JQuery's ajax function by specifying
type: "put" or
type: "delete"
and is not not supported by all browsers, but most of them.
Check out this question for more info on compatibility:
Are the PUT, DELETE, HEAD, etc methods available in most web browsers?
From here, you can do this:
/* Extend jQuery with functions for PUT and DELETE requests. */
function _ajax_request(url, data, callback, type, method) {
if (jQuery.isFunction(data)) {
callback = data;
data = {};
}
return jQuery.ajax({
type: method,
url: url,
data: data,
success: callback,
dataType: type
});
}
jQuery.extend({
put: function(url, data, callback, type) {
return _ajax_request(url, data, callback, type, 'PUT');
},
delete_: function(url, data, callback, type) {
return _ajax_request(url, data, callback, type, 'DELETE');
}
});
It's basically just a copy of $.post() with the method parameter adapted.
Here's an updated ajax call for when you are using JSON with jQuery > 1.9:
$.ajax({
url: '/v1/object/3.json',
method: 'DELETE',
contentType: 'application/json',
success: function(result) {
// handle success
},
error: function(request,msg,error) {
// handle failure
}
});
You should be able to use jQuery.ajax :
Load a remote page using an HTTP
request.
And you can specify which method should be used, with the type option :
The type of request to make ("POST" or
"GET"), default is "GET". Note: Other
HTTP request methods, such as PUT and
DELETE, can also be used here, but
they are not supported by all
browsers.
ajax()
look for param type
Other HTTP request methods, such as PUT and DELETE, can also be used here, but they are not supported by all browsers.
For brevity:
$.delete = function(url, data, callback, type){
if ( $.isFunction(data) ){
type = type || callback,
callback = data,
data = {}
}
return $.ajax({
url: url,
type: 'DELETE',
success: callback,
data: data,
contentType: type
});
}
You can do it with AJAX !
For PUT method :
$.ajax({
url: 'path.php',
type: 'PUT',
success: function(data) {
//play with data
}
});
For DELETE method :
$.ajax({
url: 'path.php',
type: 'DELETE',
success: function(data) {
//play with data
}
});
If you need to make a $.post work to a Laravel Route::delete or Route::put just add an argument "_method"="delete" or "_method"="put".
$.post("your/uri/here", {"arg1":"value1",...,"_method":"delete"}, function(data){}); ...
Must works for others Frameworks
Note: Tested with Laravel 5.6 and jQuery 3
I've written a jQuery plugin that incorporates the solutions discussed here with cross-browser support:
https://github.com/adjohnson916/jquery-methodOverride
Check it out!
CRUD
this may make more sense
CREATE (POST)Request
function creat() {
$.ajax({
type: "POST",
url: URL,
contentType: "application/json",
data: JSON.stringify(DATA1),
success: function () {
var msg = "create successful";
console.log(msg);
htmlOutput(msg);
},
});
}
READ (GET)Request
// GET EACH ELEMENT (UNORDERED)
function read_all() {
$.ajax({
type: "GET",
url: URL,
success: function (res) {
console.log("success!");
console.log(res);
htmlOutput(res);
},
});
}
// GET EACH ELEMENT BY JSON
function read_one() {
$.ajax({
type: "GET",
url: URL,
success: function (res) {
$.each(res, function (index, element) {
console.log("success");
htmlOutput(element.name);
});
},
});
}
UPDATE (PUT)Request
function updat() {
$.ajax({
type: "PUT",
url: updateURL,
contentType: "application/json",
data: JSON.stringify(DATA2),
success: function () {
var msg = "update successful";
console.log(msg);
htmlOutput(msg);
},
});
}
DELETE (DELETE)Request
function delet() {
$.ajax({
type: "DELETE",
url: deleteURL,
success: function () {
var msg = "delete successful";
console.log(msg);
htmlOutput(msg);
},
});
}
GitHub Reference
You could include in your data hash a key called: _method with value 'delete'.
For example:
data = { id: 1, _method: 'delete' };
url = '/products'
request = $.post(url, data);
request.done(function(res){
alert('Yupi Yei. Your product has been deleted')
});
This will also apply for

How do redirect in Ajax Post?

Im trying to redirect Ajax post in a success function
Here's the code
$.ajax({
type: "POST",
url: "/api/create-room/",
data:{
targetedUser,
},
success: function(data) {
// How to redirect in here??
}
});
You could use window.location.replace or window.location.href inside the success function :
$.ajax({
type: "POST",
url: "/api/create-room/",
data:{
targetedUser,
},
success: function(data) {
window.location.replace("url"); //Simulate HTTP redirection
//Or
window.location.href = "url"; //Simulate click on a link
}
});
For more information you could check This post.
Hope this helps.

How to parse parameters from Ajax return string

I have a litte problem.
I call an file and this file has to know from which level it was called.
I'm developing in an special tool, and thats how it works here.
for example:
var Url = baseUrl + "?func=ll&objId=" + WebreportId + "&objAction=RunReport";
jQuery.ajax({
url: Url,
type: "GET",
data: { level: 'dossier' },
success: function(response){
$('#thirdPartyContent').html($(response).find('#cvDossier').html());
}
});
In my JavaScript Functions in the Call, i have to know from which level it was called. Like here "dossier".
How can i read out an string in the call? With the URL Parms i can just check the superior url, and not the url from the ajax call, isn't it?
I hope you understand my probs.
Try utilizing beforeSend option of $.ajax()
jQuery.ajax({
url: Url,
type: "GET",
data: { level: 'dossier' },
beforeSend: function(jqxhr, settings) {
// set `data` property at `jqxhr` object
jqxhr.data = settings.url..match(/=.*/)[0].split(/=|&.*/).filter(Boolean)[0];
},
success: function(response, textStatus, jqxhr){
// do stuff with `jqxhr.data` : `"dossier"`
console.log(jqxhr.data);
$('#thirdPartyContent')
.html($(response).find('#cvDossier').html());
}
});

jquery ajax call response in javascript is blank

The fail function gives me a correct output, whereas the done function gives me blank. I am stuck with this for hours. Any idea on how to debug this?
var xhr = false;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
if (contentType == null) {
contentType = "application/json";
}
var reqst = $.ajax({
beforeSend : function(req) {
req.setRequestHeader("Content-Type", "application/json");
},
url : url,
type : "post",
contentType : contentType,
data : paramsTable,
});
reqst.done(function(xhr){
alert(xhr.responseText);
});
reqst.fail(function(xhr){
alert(xhr.responseText);
});
I would like to recommend you to use Ajax jQuery API instead of the old Ajax requests. No body uses it today (almost nobody; since you use it)
$.ajax({
beforeSend: function(req) {
req.setRequestHeader("Content-Type", "application/json");
},
url: url,
type: "post",
contentType: contentType,
data: paramsTable,
success: function () {
// here the code to execute if success
},
error: function () {
// here the code to execute if error..
}
});
Why your code isn't working
Because you are never using the xhr to send the Ajax request so it has nothing to show as the response text. Funny isn't it? hehehe.
use this:
success: function(resp) {
alert(resp); // where resp is the name of the responseText here..
}
I have shown you how to use it. Good luck!
For more: http://api.jquery.com/jquery.ajax/
Try to use standard jquery ajax structure:
$.ajax({
url: "test.html",
context: document.body
}).done(function() {
$( this ).addClass( "done" );
})
.fail(function() {
alert( "error" );
});

jQuery: how to make http request with arguments and body?

So I want to make a http request with a body (say file, file2, file3) and arguments like action=delete how to make such request with jquery?
Pass parameters with url and files with body:
$.ajax({
url: 'someurl' + '?action=delete',
type: 'POST',
data: requestbodyhere,
success: function(responseData){
}
});
You want to do a POST? You can do that using Ajax:
jQuery.ajax({
type: 'POST',
url: url,
data: {
file1:'file1',
flie2:'file2'
},
success: function(response) {
//in response you have the answer from the server as a string
}
});

Categories