done not executed ajax - ajax

Im having this piece of code. Where I use this Action to get trigger an export that downloads an excel file. Which works perfectly when I type the link and argument in my browser, the file gets downloaded.
But I want to call this from an ajaxified context and this is where it all gets wrong.
<script type="text/javascript">
function exportPerson(e) {
e.preventDefault();
var dataItem = this.dataItem($(e.currentTarget).closest("tr"));
var action = '#Url.Action("ExportContactAlarmList", "Contact")';
$.ajax({
url: action + '/' + dataItem.Id,
type: "POST",
done: function(response) {
var dataURI = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" +
kendo.util.encodeBase64(response);
kendo.saveAs({
dataURI: dataURI,
fileName: "PersonExport.xlsx",
proxyURL: "#Url.Action("Save", "Home")"
});
}
});
}
</script>
I'm kind of stuck because the done method never gets executed. And I don't know why.
These are my responses from my headers I get back.
Everything looks good, no errors in the console.

Normally I use $.ajax with these functions:
success = A function to be called if the request succeeds
error = A function to be called if the request fails
complete = A function to be called when the request finishes (after success and error callbacks are executed). I also use it to stop the loading bar.
beforeSend = A pre-request callback function. Even used to start loading bar.
So I would suggest you to use this:
success: function(response) {...
ref: http://api.jquery.com/jquery.ajax/
I am not sure, but there are some restrictions to download files using XMLHttpRequest. Maybe if you define the header before... See accepts settings form $.ajax and dataType.
Good luck!

try this
$.ajax({
url: action + '/' + dataItem.Id,
type: "POST",
success: function(response) {
var dataURI = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" +
kendo.util.encodeBase64(response);
kendo.saveAs({
dataURI: dataURI,
fileName: "PersonExport.xlsx",
proxyURL: "#Url.Action("Save", "Home")"
});
}
});
or
$.ajax({
url: action + '/' + dataItem.Id,
type: "POST"
}).done(function(response) {
var dataURI = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" +
kendo.util.encodeBase64(response);
kendo.saveAs({
dataURI: dataURI,
fileName: "PersonExport.xlsx",
proxyURL: "#Url.Action("Save", "Home")"
});
});

Related

Laravel - Ajax and preventdefault

I have a problem with getting items in cart, after I add an item into the cart, Ajax works perfect, then when i try to remove it from the list, first time it wont work with Ajax, if I reload the page it will work.
Ajax generate response like this:
1x ItemTitle X (remove)
When remove has /delete-from-cart/id/place_id
It only works when I reload the page, and also I have a button for coupons that is also managed to work with Ajax, but it only works after refresh.
$('.deletefromcart a').each(function(){
$('#'+this.id).on('click',function(e) {
e.preventDefault();
var id = $(this).attr('data-del');
var url = $(this).attr('href');
var place = $(this).attr('data-place');
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url: '/delete-from-cart/'+id+'/'+place+'',
method: 'get',
data: $(this).serialize(),
success: function(data){
toastr.warning('Uspešno ste obrisali iz korpe!', 'Korpa');
$(".korpa").load(location.href + " #cartAll");
},
error: function(data){
console.log(data);
}
});
});
});
It seems like this function cant find any object to run it from ajax after I add to cart, after refresh it finds.
If you need live preview, i can make you an account.
You should bind the click event handler on each 'delete' element as,
$('body').on('click', '.deletefromcart a', function (e) {
e.preventDefault();
var id = $(this).attr('data-del');
var url = $(this).attr('href');
var place = $(this).attr('data-place');
$.ajax({
url: '/delete-from-cart/' + id + '/' + place + '',
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
method: 'get',
data: $(this).serialize(),
success: function (data) {
toastr.warning('Uspešno ste obrisali iz korpe!', 'Korpa');
$(".korpa").load(location.href + " #cartAll");
},
error: function (data) {
console.log(data);
}
});
});
Note 1: Your method of binding will attach the event handler to all .deletefromcart a elements. But the one I suggested will bind the event handler to only one element, body. This will also work on dynamically added .deletefromcart a elements.
Note 2: You can include the header values as above too.

Ajax request type POST returning GET

I'm currently trying to make an ajax POST request to send a testimonial simple form to a Django view. The problem is this request is returning a GET instead of a POST.
This is my ajax:
<script>
$(document).ready(function(){
$("form.testimonial-form").submit(function(e){
e.preventDefault();
var dataString = $(this).serialize();
$.ajax({
type: "POST",
url: "/testimonials",
data: dataString,
success: function(_data) {
if (_data[0]){
$('.modal-text').css({display: "none"});
}
else{
$('.unsuccess').css({display: "block"});
}
}
});
});
});
</script>
Any idea what could I be doing wrong?
replace type by method
method: 'post',
also you may need send headers:
headers: {
'X-CSRFToken': getCSRFToken()
},
where getCSRFToken is:
function getCSRFToken() {
return $('input[name="csrfmiddlewaretoken"]').val();
}
I am not really sure why this is happening, but i would write the function in a bit different way. since ajax();'s default type is "GET", i suspect somewhere it is being set to default.
first set the type="button" of submit button (whose id is e.g. "submit_button_id"), so it doesnot submits if you click on it. or put the button outside of <form>
then try this code
<script>
$(function(){ // same as "$(document).ready(function()"..
$("#submit_button_id").on('click',function(){
var dataString = $('form.testimonial-form').serialize();
$.ajax({
type: "POST",
url: "/testimonials",
data: dataString,
success: function(_data) {
if (_data[0]){
$('.modal-text').css({display: "none"});
}
else{
$('.unsuccess').css({display: "block"});
}
}
});
});
});
</script>

when ajax post success i want to refresh a particular <div> in page

i want to refresh a particular div on ajax success, im using the below code but the whole page getting refreshed.
<script type="text/javascript">
$('#post_submit').click(function() {
var form_data = {
csrfsecurity: $("input[name=csrfsecurity]").val(),
post_text: $('#post_text').val()
};
$.ajax({
url: "<?php echo site_url('/post_status'); ?>",
type: 'POST',
data: form_data,
success: function(response){
$(".home_user_feeds").html("markUpCreatedUsingResponseFromServer");
}
return false;
});
return false;
});
</script>
you have an extra return false which is inside the $.ajax block which most probably causes an error so your form isn't submitted via ajax. If you remove that, you shouldn't have any issues.
Use the submit event of the form and remove the return false from the ajax callback:
$('#myFormId').on('submit', function() {
var form_data = {
csrfsecurity: $("input[name=csrfsecurity]").val(),
post_text: $('#post_text').val()
};
$.ajax({
url: "<?php echo site_url('/post_status'); ?>",
type: 'POST',
data: form_data,
success: function(response){
$(".home_user_feeds").html("markUpCreatedUsingResponseFromServer");
}
});
return false;
});
Remove the return false from inside your $.ajax function. Its a syntax error. The $.ajax function only expects a json object as an argument. "return false" cannot be part of a json object. You should keep the JavaScript console open during testing at all times - Press Ctrl-Shift-J in Chrome and select console to see any JS errors.
Also suggest you use <input type=button> instead of <input type=submit> or <button></button>

Pass Ajax POST variable to JQuery UI dialog

Below is an Ajax POST variable I use to return some information to an ASP MVC3 View. However, I cannot get the .dialg() pop-up function to work. Right now you click on the icon that calls GetProgramDetails(pgmname), and nothing happens. First time using Ajax, so any suggestions would be appreciated. Thx!
<script src="http://code.jquery.com/jquery-1.8.3.js" type="text/javascript"></script>
<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js" type="text/javascript"></script>
<script type="text/javascript">
function GetProgramDetails(pgmname) {
var request = $.ajax({
type: 'POST',
url: '/BatchPrograms/PopDetails',
data: { programName: pgmname },
dataType: 'html'
});
request.done(function (data) {
$('#data').dialog();
});
</script>
EDIT
I've updated the request.done function to include a simple alert to see if the code was being called. After stepping through with Chrome's debugger, I saw that the code inside was completely skipped over.
request.done(function (data) {
alert("HERE!");
$('#programExplanation').html(data);
});
SECOND EDIT
Here is the controller code the ajax is returning a value from:
[HttpPost]
public string PopDetails(string programName)
{
BatchPrograms batchprograms = db.BatchPrograms.Find(programName);
if (batchprograms == null) return string.Empty;
StringBuilder s = new StringBuilder();
s.Append(batchprograms.ProgramName + " - " + batchprograms.ShortDescription);
s.Append("<br />Job Names: " + batchprograms.PrdJobName + ", " + batchprograms.QuaJobName );
s.Append("<br /> " + batchprograms.Description);
return s.ToString();
}
You need to use the success method to handle the callback, like so:
var request = $.ajax({
type: 'POST',
url: '/BatchPrograms/PopDetails',
data: { programName: pgmname },
dataType: 'html'
}).success(function(data){ $('#data').dialog()} );
This will launch the dialog for you, but if you want to get the response data to work with it, you can have GetProgramDetails take a second parameter which is a callback for after the data is loaded like so:
function GetProgramDetails(pgmname, callback) {
var request = $.ajax({
type: 'POST',
url: '/BatchPrograms/PopDetails',
data: { programName: pgmname },
dataType: 'html'
}).success(callback);
}
This way after the response is received you can handle what to do with the data in your implementation of the callback, in this case it seems like you will be setting data in the dialog and launching the dialog.

Is it possible to make multiple calls using Jsonp with deferred objects?

I'm trying to make two or more requests all at once if that's even possible? I'm concerned about speed since after the first request is made I want to display that info onto a web page and then do the same for each additional url.
I've been reading about deferred objects and trying some examples, and so far I've tried to do this,
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.6.4.min.js"></script>
<script >
$(document).ready(function($) {
// - 1st link in chain - var url = 'https://www.sciencebase.gov/
catalog/items?parentId=504108e5e4b07a90c5ec62d4&max=60&offset=0&format=jsonp';
// - 2nd link in chain - var url = 'https://www.sciencebase.gov/
catalog/itemLink/504216b6e4b04b508bfd333b?format=jsonp&max=10';
// - 3rd (and last) link in chain - var url = 'https://www.sciencebase.gov/
catalog/item/4f4e4b19e4b07f02db6a7f04?format=jsonp';
// parentId url
function parentId() {
//var url = 'https://www.sciencebase.gov/catalog/items?parentId=
504108e5e4b07a90c5ec62d4&max=3&offset=0&format=jsonp';
return $.ajax({
type: 'GET',
url: 'https://www.sciencebase.gov/catalog/items?parentId=
504108e5e4b07a90c5ec62d4&max=3&offset=0&format=jsonp',
jsonpCallback: 'getSBJSON',
contentType: "application/json",
dataType: 'jsonp',
success: function(json) {},
error: function(e) {
console.log(e.message);
}
});
}
// itemLink url
function itemLink() {
//var url = 'https://www.sciencebase.gov/catalog/itemLink
/504216b6e4b04b508bfd333b?format=jsonp&max=10';
return $.ajax({
type: 'GET',
url: 'https://www.sciencebase.gov/catalog/itemLink
/504216b6e4b04b508bfd333b?format=jsonp&max=10',
jsonpCallback: 'getSBJSON',
contentType: "application/json",
dataType: 'jsonp',
success: function(json) {},
error: function(e) {
console.log(e.message);
}
});
}
// Multiple Ajax Requests
$.when( parentId(), itemLink()).done(function(parentId_data, itemLink_data) {
console.log("parentId_data.items[0].title");
});
});
But it doesn't seem like the functions are functioning. I was expecting to be able to put some stuff after the .when() method inside the function to tell my program what to do, but I'm not getting anything displayed??
Thanks for the help!
Part of the problem is that in the done handler for $.when, the arguments that are passed to the callback are the array of arguments for each request, not simply the data that you want to use. You can get around this by using .pipe as in the example below.
Also, don't specify jsonpCallback unless you have a very good reason, most of the time you want to let jQuery manage that internally for you.
Here's a working example tested on JSFiddle
jQuery(function($) {
function parentId() {
return $.ajax({
url: 'https://www.sciencebase.gov/catalog/items?parentId=504108e5e4b07a90c5ec62d4&max=3&offset=0&format=jsonp',
dataType: 'jsonp',
error: function(e) {
console.log(e.message);
}
// We'll use pipe here so that rather than the value being passed to our $.when handler
// is simply our data rather than an array in the form of [ data, statusText, jqXHR ]
}).pipe(function( data, statusText, jqXHR ) {
return data;
});
}
function itemLink() {
return $.ajax({
url: 'https://www.sciencebase.gov/catalog/itemLink/504216b6e4b04b508bfd333b?format=jsonp&max=10',
dataType: 'jsonp',
error: function(e) {
console.log(e.message);
}
}).pipe(function(data) {
return data;
});
}
// Multiple Ajax Requests
$.when( parentId(), itemLink()).done(function(parentId_data, itemLink_data) {
console.log( parentId_data, itemLink_data );
});
});

Resources