How to get DELETE request parameters - javascript

This is how I want to delete a record using jquery ajax
deleteFile: function(obj) {
$.ajax({
type: 'delete',
dataType: 'json',
url: 'service/lead.php?a=deleteFile',
data: {id: $(obj).attr('data-lf-id')}
}).done(function(response) {
console.log("done");
}).fail(function(error) {
});
}
This works but how am I suppsed to get the id value on the lead.php page? This is what I am currently doing but it doesn't capture the id value.
//service/lead.php
if ($_SERVER['REQUEST_METHOD'] == "DELETE") {
if ($_GET['a'] == 'deleteFile') {
echo json_encode($lead->deleteLeadFile($_REQUEST['id']));
}
}

I would suggest changing your Ajax type to either 'POST' or 'GET". You can then use the appropriate $_GET or $_POST variable to retrieve your id.
deleteFile: function(obj) {
$.ajax({
type: 'POST',
dataType: 'json',
url: 'service/lead.php?a=deleteFile',
data: {id: $(obj).attr('data-lf-id')}
}).done(function(response) {
console.log("done");
}).fail(function(error) {
});
}
//service/lead.php
if ($_GET['a'] == 'deleteFile') {
echo json_encode($lead->deleteLeadFile($_POST['id']));
}

file_get_contents(“php://input”)
This always gives you raw request data - you have to parse it [with parse_str if you send urlencoded data, with json_decode if you send JSON].
But you should keep it RESTful and not RPC-like, and issue a delete over /resource/:id.

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

Pass variable via ajax to api.php

I am trying to pass a js variable via ajax to the php side. My js code is:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
var sAgentId = 'hi'
$.ajax({
url: "api-test.php",
method: "POST",
data : { id:sAgentId}
}).done(function(){
console.log('done')
})
and in the php file, I am trying to get the variable via post:
$sAgentId = $_POST['id'];
But finally in api i get the notification that says
Notice: Undefined index: id in C:\xampp\htdocs\webdev-php-exam-prep\exercise\api-test.php on line 2
Can anyone tell me what I am doing wrong?
Try adding this to your AJAX method:
dataType: "json"
Try also console logging the response back to check $_POST['id'] is being set.
.done(function(data) {
console.log("Data: ", data);
});
and in your PHP just return $_POST['id']
var sAgentId = 'hi'
$.ajax({
url:'api-test.php',
type: "POST",
data: {id: sAgentId },
cache: !0,
dataType: 'json',
success: function(data) {
console.log(data);
}
});
try replace method by type:
type: "POST",

Ajax: Pass Model List to Controller

I have a view that takes a list of a model as the Model, so
#model List<Collections.Models.Status>
I want to pass this list as the data for an Ajax call, but I keep getting "System.Collections.Generic.List[Collections.Models.Status]" instead of the values in the model.
Here's the Ajax code:
$.ajax({
url: "/Home/Update",
data: JSON.stringify(#Model),
type: 'POST',
dataType: 'json',
success: function (responseJSON) {
if (responseJSON.message == 'success') {
alert('here');
}
},
error: function (error) {
showModal("Error: " + error.message);
}
});
Which translates in the debugger to:
$.ajax({
url: "/Home/Update",
data: JSON.stringify(System.Collections.Generic.List`1[Collections.Models.CollectionStatus]),
type: 'POST',
dataType: 'json',
success: function (responseJSON) {
if (responseJSON.message == 'success') {
alert('here');
}
},
error: function (error) {
showModal("Error: " + error.message);
}
});
How do I pass the actual values of the list instead of System.Collections.Generic.List[Collections.Models.Status]?
I've tried #Model.ToList(), #Html.Raw(Model), neither worked.
set contentType property to application/json.
and use below code to set data property
data: JSON.stringify({'your controllers parameter name': '#Model'})

jQuery AJAX POST method not working

I am trying to execute the AJAX operation. the call is working fine but the problem I am having is that I am getting an empty string as a response. There is no error in the console. all I get is an empty string. Even when I change the dataType to JSON, I still get the same response.
JavaScript Code:
$.ajax({
url: "data/saveCart.php",
method: "POST",
data: {
cartItem:item
},
dataType: "text",
success: function(data){
console.log(data);
}
});
PHP code:
if(isset($_POST['cartItem'])) {
echo "AJAX successful";
} else {
echo "AJAX failed";
}
It seems like it was caused by not stringifying your data.
var item = {
toothbrush: {
price: 1
}
};
$.ajax({
url: "data/saveCart.php",
method: "POST",
data: {
cartItem: JSON.stringify( item )
},
dataType: "text",
success: function(data){
console.log(data);
}
});

how to post text '&nsbp ' using javascript?

The content that i want to send
<div id="preview">&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp</div>
Element function:
function _(obj) {
return document.getElementById(obj);
}
Ajax:
$.ajax({
type: 'POST',
url: 'http://<?php echo $domain ?>/libraries/ajax/pdf.php',
data: 'html=' + _("preview").innerHTML + '&nama=a',
dataType: 'html',
beforeSend: function() {},
success: function(response) {
Materialize.toast((response), 4000);
}
});
How to send &nsbp as text instead of POST parameter?
Use the encodeURIComponent(<string to be encoded>) to encode the data
Use
data: { html: _("preview").innerHTML, nama: 'a'}
And $.ajax will encode it. Under the hood, it uses uses this encodeURIComponent(), you use it like
data: 'html='+encodeURIComponent(_("preview").innerHTML)+'&nama=a',

Categories