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
I have an ajax call that works great the first time the form is submitted after that all javascript on the page seems to break. As well as the form won't submit with ajax again.
Here is my ajax call:
$('form').submit(function(event) {
$('input:submit').attr("disabled", true).after('<p class="loading">Searching...</p>');
$.ajax({
type: "POST",
url: pathname,
data: $(this).serialize(),
success: function(data) {
$('#container').html("<div id='message'></div>");
$('#message').append(data).hide().fadeIn(1500);
},
});
event.preventDefault();
});
I'm getting no errors in my console. Any ideas what might be causing this?
I solved the issue, the main page content was changing. Which was causing the javascript to unload. So I need to use Jquery .on/.live and then it works. For what ever reason this worked fine on one server and not on another.
Use as below: No Need to define event.preventDefault();
$('form').submit(function(event) {
$('input:submit').attr("disabled", true).after('<p class="loading">Searching...</p>');
$.ajax({
type: "POST",
url: pathname,
data: $(this).serialize(),
success: function(data) {
$('#container').html("<div id='message'></div>");
$('#message').append(data).hide().fadeIn(1500);
$('input:submit').removeAttr("disabled");
},
});
return false;
});
Remove disabled after submitting the form. And remove the , mentioned by #JustinRusso.
$('form').submit(function(event) {
$('input:submit').attr("disabled", true).after('<p class="loading">Searching...</p>');
$.ajax({
type: "POST",
url: pathname,
data: $(this).serialize(),
success: function(data) {
$('#container').html("<div id='message'></div>");
$('#message').append(data).hide().fadeIn(1500);
$('input:submit').removeAttr("disabled");
}
});
event.preventDefault();
});
I have an ajax function is called when a form is completed. It is suppose to redirect to a certain page if there is a success for a failure. When I run the form in IE, it works perfectly but in Firefox, the page does not redirect at all. It just refreshes the page. Here is the ajax code:
$.ajax({
url: "someURL",
type: "POST",
dataType: "xml",
data: params,
success: function () { window.location = 'success_page.htm' },
failure: function () { window.location = 'error_page.htm' }
});
Well, there's a minor mistake in your code: you are missing some semicolons:
$.ajax({
url: "someURL",
type: "POST",
dataType: "xml",
data: params,
success: function () { window.location = 'success_page.htm'; },
failure: function () { window.location = 'error_page.htm'; }
});
If this still doesn't resolve your problem, then I would guess there is something wrong with your params variable. Could you show us the whole code?
try
window.location = '/error_page.htm'
Sometimes working with IE I had the same problem, I use window.location.href instead of window.location
I have a code for pulling data from careerbuilders api. The link works well when tested on the browser, but I can't seem to parse anything from it. Care to tell me what is wrong?
html code:
<div class="main">
Companies:
</div>
jQuery code:
$(document).ready(function () {
$.ajax({
type: "GET",
url: "http://api.careerbuilder.com/v1/jobsearch?DeveloperKey=WDHL4Z86PBQY29Z7ZQQS&Location=Canada",
dataType: "xml",
success: xmlParser(xml)
});
});
function xmlParser(xml) {
$(xml).find("JobSearchResult").each(function () {
$(".main").append(
$(this).find("Company").text()
);
});
}
Here is a jsfiddle live example: http://jsfiddle.net/Cc4SY/
In your case xml won't be defined. You have to wrap the success callback in another function which in turn will call your xmlParser function.
What you are doing is calling the xmlParser function and assigning the return value as the success callback, which is not intended. So you have wrap it in another function and call xmlParser from that function and in that case the xml response will be properly passed to the xmlParser and you will able to parse it.
The code might look like this:
$(document).ready(function () {
$.ajax({
method: "GET",
url: "http://api.careerbuilder.com/v1/jobsearch?DeveloperKey=WDHL4Z86PBQY29Z7ZQQS&Location=Canada",
dataType: 'xml',
success: function (response) {
xmlParser(response);
}
});
});
function xmlParser(response){
var xml = $.parseXML(response);
$(xml).find("JobSearchResult").each(function () {
$(".main").append(
$(this).find("Company").text()
);
});
}
I think now it's working:
$(document).ready(function () {
$.ajax({
type: "GET",
url: "http://api.careerbuilder.com/v1/jobsearch?DeveloperKey=WDHL4Z86PBQY29Z7ZQQS&Location=Canada",
dataType: "xml",
success: function(xml)
{
xmlParser(xml);
}
});
});
Fiddle here: http://jsfiddle.net/Cc4SY/2/
Console response: XMLHttpRequest cannot load http://api.careerbuilder.com/v1/jobsearch?DeveloperKey=WDHL4Z86PBQY29Z7ZQQS&Location=Canada. Origin http://fiddle.jshell.net is not allowed by Access-Control-Allow-Origin.
It's a jsfiddle restriction.
I have a jQuery function that is called when the "submit" button is clicked:
function SubmitForm() {
var idList = [];
var list = $('#TableAdminPortfolio .CheckBoxProjects');
list.each(function () {
var id = $(this).closest('td').children('.hiddenId').val(); // parseInt()
idList.push(id);
});
$.ajax({
url: $(this).href,
type: 'POST',
data: idList,
success: function (result) {alert('Successful');},
error: function (result) {alert('Error');}
});
}
My controller looks like:
[Transaction]
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(IEnumerable<int> projects)
{
...
}
The paramater (projects) is always null. I've stepped through my jQuery code inspecting it each step of the way and the idList is definitely populated. I've also tried my $ajax like this:
$.ajax({
url: $(this).href,
type: 'POST',
data: { projects : idList },
success: function (result) {alert('Successful');},
error: function (result) {alert('Error');}
});
And still the same results. Any ideas what is going on? And yes, I have a reason for doing an Ajax Post rather then a Form Post.
TIA
NOTE:
I am using jQuery v1.6.4 and ASP.NET MVC 2.0.
try converting your array to json using JSON.stringify
$.ajax({
url: $(this).href,
type: 'POST',
dataType: "json",
data: JSON.stringify(idList),
traditional: true,
success: function (result) {alert('Successful');},
error: function (result) {alert('Error');}
});
try:
var mylist='{"projects":'+ JSON.stringify(idList)+'}';
then
data:mylist,