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.
Related
I have a ASP.net webform populated with data from a MS SQL DB, and allows you to edit values.
The web app uses a Harvest Chosen multiselect dropdown list (max=1) to select two different persons picked from the same list of information, but on two separate controls.
When I refresh the page, sometimes both controls are populated with the correct value, sometimes neither or one are. I tested in the console and it is definitely pulling the correct information from the DB, but I must be missing something relating to how these procedures are executed. I have done this work with VB.NET and ASP controllers in the past. This is my first time using AJAX and web method functions. I believe I am missing an update somewhere, or not understanding the order in which code is executed.
I tried explicitly stating the order of operations in the .aspx page, and then doing no update triggers until after all the code for the controller had been executed, but this appears to have broken both controllers (the both end up looking like normal select controllers). Apologies if my terminology is not on point, I am very self-taught. The current state of the code where I get inconsistent application
The .aspx page is as such. Each control has a set of different parameters that affect how it is populated, and what happens when it changes.
<select class="chosen-select" multiple data-placeholder="Assign a scientist" name="ChosenScientist" style="width:800px;" id="cmbChosenScientist">
<script type="text/javascript">
handleChosenControls("select#cmbChosenScientist.chosen-select");
</script>
</select>
<select class="chosen-select" multiple data-placeholder="Assign a supervisor" name="ChosenSupervisor" style="width:800px;" id="cmbChosenSupervisor">
<script type="text/javascript">
handleChosenControls("select#cmbChosenSupervisor.chosen-select");
</script>
</select>
The aspx page passes the controller name to a function which first defines all of the parameters used by the controllers.
function defineChosenControls(controller) {
switch (controller) {
case "select#cmbChosenScientist.chosen-select":
currentData = JSON.stringify({ sqlQueryName: "studyScientist" + "/" + MainContent_txbStudy.value });
populateData = JSON.stringify({ sqlQueryName: "userList" });
changeData = JSON.stringify({ strControlName: controller, arrValues: JSON.stringify($(controller).val()), strArg1: MainContent_txbStudy.value });
break;
case "select#cmbChosenSupervisor.chosen-select":
currentData = JSON.stringify({ sqlQueryName: "studySupervisor" + "/" + MainContent_txbStudy.value });
populateData = JSON.stringify({ sqlQueryName: "userList" });
changeData = JSON.stringify({ strControlName: controller, arrValues: JSON.stringify($(controller).val()), strArg1: MainContent_txbStudy.value });
break;
}
}
The function that handles the populating the options, setting the current value, and handling changes is as follows:
function handleChosenControls(controller) {
//Purpose: Any time a Chosen control is loaded, changed, etc., this is run.
defineChosenControls(controller);
$(controller).chosen({ max_selected_options: 1 });
//Script for populating the control
$.ajax({
type: "POST",
url: "ClientToServer.aspx/GetDT",
data: populateData,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
for (line of JSON.parse(response.d)) {
$(controller).append('<option value="' + line[Object.keys(line)[0]] + '">' + line[Object.keys(line)[0]] + '</option>');
}
$(controller).trigger("chosen:updated");
},
error: function (response) { console.log("ERROR: Unable to pass changed values from controller " + controller + " to server-side."); }
});
//Script for determining current value during load
$.ajax({
type: "POST",
url: "ClientToServer.aspx/GetDT",
data: currentData,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
for (line of JSON.parse(response.d)) {
$(controller).val(line[Object.keys(line)[0]]).trigger("liszt:updated");
console.log(line[Object.keys(line)[0]]);
}
$(controller).trigger("chosen:updated");
},
error: function (response) { console.log("ERROR: Unable to retrieve current value of " + controller + " from server-side."); }
});
//Script for when a value in the control is changed
$(controller).on('change', function (e) {
defineChosenControls(controller);
$.ajax({
type: "POST",
url: "ClientToServer.aspx/PassJqueryControlValue",
data: changeData,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
},
error: function (response) { console.log("ERROR: Unable to pass changed values from controller " + controller + " to server-side."); }
});
});
}
I expect both controls to have the proper value in the DB, and those values are being written in the browser console properly, but the harvest chosen controls are inconsistent.
The solution was to call the code after load.
<script type="text/javascript">
$(window).bind("load", function() {
handleChosenControls("select#cmbChosenScientist.chosen-select");
handleChosenControls("select#cmbChosenSupervisor.chosen-select");
});
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")"
});
});
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>
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 );
});
});
What i am trying to do is get a user to change one drop down, which then calls an ajax function which posts to the code behind (vb.net file) then clears and populates another asp dropdown list with the data returned from the function..hope i made sense
<script>
$(document).ready(function () {
$('.manuf').change(function () {
$.ajax({
type: "POST",
url: "ajax.aspx/GetModel",
data: '{' +
'ManufID:"' + $('.manuf').val() + '"' +
'}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
var data = json_parse(msg.d);
if (data.error) {
alert("Error!");
return;
}
alert(data.model);
},
error: function(msg) {
alert('Get Details Failure: ' + msg);
}
});
});
});
</script>
My bad - you can write your ajax call like this -
$.ajax({ url :"/website/myurl", type:"POST", contentType:"application/json;", dataType:"json", data : "{ 'id' : '" + $("select[id*=selCurrentManuf]").val() + "' } ",
success : function (return_data) {
var data = $.parseJSON(return_data);
// code to add the contents of data to other list
$("select[id*=selCurrentModel]").empty().append($("<option>").attr("value","0").text("Choose..."));
// for the dropdown list clear all options and add a 'choose...' as the first option
$.each(data, function (i, d) { $("<option>").attr("value", d.k).text(d.v).appendTo($("select[id*=selCurrentModel]")); });
}, error:function () {
// handle error
}
});
I assume that you know how to fetch data from the backend via ajax. Something like this -
$.ajax({ url :"/website/myurl", type:"POST", dataType:"application/json"; data:"json",
success : function (return_data) {
var data = $.parseJSON(return_data);
// code to add the contents of data to other list
}, error:function () {
// handle error
}
});
Lets say you are getting it in a variable data which is an array.
You may try something like this -
$("select[id*=selCurrentModel]").empty().append($("<option>").attr("value", "0").text("Choose..."));
// for the dropdown list clear all options and add a 'choose...' as the first option
$.each(data, function (i, d) { $("<option>").attr("value", d.k).text(d.v).appendTo($("#ddlExperience")); });
// user $.each to iterate the data object which
You may try things on these lines.... Hope this helps.