Google Chrome do GET request after POST AJAX - google-chrome

I have a problem with Google Chrome.
I try to post data from page to my MVC controller with AJAX and sometimes Chrome tries to do GET request after POST.
I saw that it happens in case when try to post data very frequently (push button 5-10 times with minimum delay) or in case when page doing nothing (stay) on the page about after 5-10 minutes.
$.ajax({
url: '#Url.Action("PO_Comparison")',
data: JSON.stringify(parameters),
dataType: 'json',
traditional: true,
contentType: 'application/json',
type: 'POST',
success: function (result) {
compare_with_data = result;
$.when(fillData(result)).done(function () {
EditShow();
ComparingUnloadPopupBox();
});
$("#compare_image_please_wait").hide();
},
error: function (error) {
alert(error.statusText + "! Please reload the page.");
ComparingUnloadPopupBox();
$("#compare_image_please_wait").hide();
}
});
MVC controller part:
public JsonResult PO_Comparison( List<Project_Items> parameters)
{
//Updating my Project_Items
return Json(new{ data:compared_data }, JsonRequestBehavior.DenyGet);
}
Internet explorer and Firefox works fine.
Thanks

Related

Append additional HTML result in calling MVC action by Ajax in DNN8

I'm new in DNN development.
I have created a very simple module in Visual studio--- A textbox and a button.
I just want to call the action in a controller by click the button, then show the return result in the textbox.
The code call the action success, but not sure why append lots of HTML inforation in the result.
Here is the action in the controller:
public ActionResult test1()
{
return Content("Return something");
}
Here is the Ajax code from the View:
$(document).ready(function () {
$("#btnSub").click(function () {
//alert(this.action);
$.ajax({
type:"GET",
contentType:"application/text",
url: "#Url.Action("test1", "Sky")",
data:"",
dataType: "text",
success: function (data) { $("#txtResult").val(data); alert("Success!") },
error:function(){alert("Failed!")}
});
});
});
And here is the result show in the textbox:
Anyone can let me know why the HTML information returned? Actually, I don't need it.
Thanks
Unfortunately, as described in DNN8 MVC unsupported features, it's not yet possible to return a JsonResult. So the solution I used is to return an ActionResult (although the function returns Json):
public ActionResult Test()
{
return Json(new { success = true });
}
On jquery side, I setup ajax call to receive result as html. This avoid the browser to display a parsing error. Finally, just need to remove the html part and manually parse the response. It's not very clean, but the only solution I found until DNN support JsonResult.
$.ajax({
url: '#Url.Action("Index", "Contact")',
type: 'POST',
dataType: 'html',
data: $('#contact-form input').serialize(),
success: function (response) {
jsonPart = response.substring(0, response.indexOf("<!DOCTYPE html>"));
var data = JSON.parse(jsonPart);
if (data.success) {
alert("Great");
}
},
error: function (jqXHR, textStatus, errorThrown) {
alert("Error!");
}
});
EDIT : Improved solution
DNN8 now support IMvcRouteMapper. You can then register a route in RouteConfig.cs. Once done, you can call the function using following URL :
/DesktopModules/MVC/ModuleName/Controller/Action
The action can return a JsonResult. But pay attention, if you just call that function, it will fail with a null exception on ModuleContext. You have to include in the ajax call the following header :
headers: {
"ModuleId": #Dnn.ModuleContext.ModuleId,
"TabId": #Dnn.ModuleContext.TabId,
"RequestVerificationToken": $("input[name='__RequestVerificationToken']").val()
}
You can find the module complete code here.
This is a working ajax call in DNN 9. You dont have to use #urlaction it will give whole html as well as data. dnn.getVar("sf_siteRoot", "/") +
"DesktopModules/MVC/ModuleName/Controller/Action", this does the trick and don't forget to add the header otherwise it will throw 500 error.
$.ajax({
url: dnn.getVar("sf_siteRoot", "/") +
"DesktopModules/MVC/ModuleName/Controller/Action",
type: 'POST',
contentType: "application/json; charset=utf-8",
dataType: 'json',
data: "{ 'id':" + JSON.stringify(3543)+" }",
headers: {
"ModuleId": #Dnn.ModuleContext.ModuleId,
"TabId": #Dnn.ModuleCon`enter code here`text.TabId,
"RequestVerificationToken":
$("input[name='__RequestVerificationToken']").val()
},
success: function (response) {
debugger;
},
error: function (errmsg) {
alert("Error!");
}
});
Your controller should be
[HttpPost]
public ActionResult ActionName(int id)
{
var data = id;
return BuidJsonResult(true,data);
}
Happy Coding :)

jquery ajax request fails with error in chrome (with async: false), but works in FF

Trying to build what should be a simple AJAX request with jQuery. Here's the coffeescript:
$('#ad_id_string').blur(function() {
var self, idString, adURL;
self = $(this);
if (self.val() != "") {
idString = self.val();
adURL = "/advertisements/" + idString;
$.ajax({
url: adURL,
type: "GET",
dataType: "json",
data: "",
async: false,
contentType: "application/json",
success: function(response, textStatus, jqXHR) {
console.log(response);
},
error: function(jqXHR, textStatus, errorThrown) {
console.log("Failed - " + textStatus + " : " + errorThrown);
}
});
}
});
Firefox executes the request with no problem, and the JSON is returned as expected. However, Chrome refuses to even send the request. Instead, it gives this error: NETWORK_ERR: XMLHttpRequest Exception 101
I've tried setting async:true instead of false, as well as removing the async parameter all together. That just causes chrome to fail the request before sending without an error of any kind. My Q/A folks will be testing this in Chrome or Safari, so it needs to work in those browsers.
Looks like this had something to do with my version of Chrome (23.0.1271.97), and the url in question. I'm using Rails, so I was hitting http://localhost:3000, and Chrome has issues passing AJAX requests with port numbers.

ajax post multiple parameters does not pass properly to asp.net mvc action

I am not able to pass 2 parameters to the action method as json. I have the following ASP.net MVC3 action.
[HttpPost]
public JsonResult Create( PatientContactEpisodes patientcontactepisode, IList<PatientContactEpisodeProcedures> patientcontactepisodeprocedures)
And my ajax post looks like this.
$("#SaveButton")
.button()
.click(function () {
var episode = getpatientcontactepisode();
$.ajax({
type: 'POST',
traditional: true,
url: "/User/PatientContactEpisodes/Create",
contentType: 'application/json, charset=utf-8',
data: {patientcontactepisode: JSON.stringify(episode), patientcontactepisodeprocedures: JSON.stringify(createArray)},
//data: JSON.stringify(episode),
dataType: "json",
success: function (results) {
alert("success");
}
});
});
ISSUE
The issue is that the value does not seem to be passed when I send both parameters to the action. Both are null/empty. Whereas, when i send a single parameter
//data: JSON.stringify(episode), or //data: JSON.stringify(createarray),
The above works fine.
Try:
data: {JSON.stringify({patientcontactepisode: episode, patientcontactepisodeprocedures:createArray})},
This should do the stuff for you.

jQuery call stack?

I have many instances of the same type of problem using jQuery. Probably because I am missing some basic knowledge (jQuery newb). In my $.Ajax calls to get data - on the success: I perform many calls to other functions based on the data that gets returned. The calls need to be made in a specific order but this does not seem to happen. If I have a call to another jQuery function that I wrote and then three line later have a call to yet another function (which depends on some events that happen in the first function call) the second call is happening first. Ran this with debugger set many times in two different $.Ajax calls and it happens this way. Am I doing something completely wrong?
BTW - the data is coming in just fine and populating my table and form items. Per request I am posting code below - the comments show that GetInventory needs to execute before BuidlNav
$(document).ready(function () {
$('#searchNow').css('visibility', 'hidden'); //Hide Search Now button
$("#popup").css("display", "none");
$('#submit').prop('disabled', true);
$.ajax({
type: "POST",
url: "mypage.aspx/mywebmethod",
contentType: "application/json; charset=utf-8",
data: "{}",
dataType: "json",
success: function (states) {
var jsonCodes = JSON.parse(states.d);
for (var i in jsonCodes) {
$("#Select0").append(new Option(jsonCodes[i].regionname, jsonCodes[i].region_id));
}
var first = getUrlVars()["region"];
if (first) {
debugger;
$.fn.SetAllSelectors(reg);
$.fn.GetInventory(1, 10, reg, 'rank', 'asc'); //This should happen first
$.fn.BuildNav(); // This depends on GetInventory having been executed already.
}
else {
var myText = 'United States';
$("#Select0 option").filter(function () {
return $(this).text() == myText;
}).first().prop("selected", true);
$.fn.GetChildRegions("Select0");
}
}
});
}
);
If GetInventory and BuildNav also use ajax, you'll need a structure more like this. When making ajax calls, the data is fetched while not holding up the next command line, so chances are your 2nd or 3rd function is being called before the first finishes.
$.ajax({
type: "POST",
url: "mypage.aspx/mywebmethod",
contentType: "application/json; charset=utf-8",
data: "{}",
dataType: "json",
success: function (states) {
getInventoryAndBuildNav(states);
},
...
});
function getInventoryAndBuildNav(states){
$.ajax({
....
url: "mypage.aspx/getinventory",
success: function (inventory) {
$.fn.BuildNav();
},
...
});
}
The best way to accomplish this is to build functions for each item and allow a callback method to be passed.
Think of it this way
$.ajax({
type: "POST",
url: "mypage.aspx/mywebmethod",
contentType: "application/json; charset=utf-8",
data: "{}",
dataType: "json",
success: function (states) {
//This will trigger second since we had to wait for the process to finish
alert('The Ajax call has been made, finished, and the data received');
}
});
//This will trigger FIRST since the ajax call was initiated, but we're still waiting
alert('The Ajax call has been made. We're moving on to the next call.');

$.post() behaves different than $.ajax( same paramenters )

I came across something weird, that I want to expose and know if someone as an explanation for it.
Some time back i had a simple post:
$.post("/Route/Save", { myObj: JSON.stringify(myObj), accessToken: getAccessToken()}, function(data)
{
//do stuff
});
and it was working nicely, now doesn't work, and only the accessToken paramenter is correctly received in the route controller
I changed it to:
$.ajax({
url: "/Route/Save",
data: '{ myObj:' + JSON.stringify(myObj) + ',accessToken:"' + getAccessToken()+'"}',
type: 'POST',
datatype: 'JSON',
contentType: 'application/json',
success: function (data)
{
//Do stuff
}
});
And now it works. I'm using firefox 4 and IE9 and believe the reason is connected to the way the browser is sending the info encoded... in the $.post() case it looks like it sends the data as application/x-www-form-urlencoded
I'll be glad to hear from you guys!
Regards,
byte_slave
I'm not sure why it was working before; perhaps a jQuery update changed behaviour?
As to your question on the content-type, $.post is a shorthand wrapper around $.ajax, and from the $.ajax api page, the default value for the contentType is 'application/x-www-form-urlencoded'.
AFAIK, you can't specify the contentType using $.post(). I could be wrong though.
The equivalent with $.ajax should be
$.ajax({
url: "/Route/Save",
data: { myObj: JSON.stringify(myObj), accessToken: getAccessToken()},
type: 'POST',
success: function (data)
{
//Do stuff
}
});