How to set cache to false on httpget from mvc4 controller action - javascript

I have the following httpget that calls a controller action:
$.get('/Course/ExplanationCorrect/', postData, function (data) {
$('#SurveyDiv').html(data);
});
This is working on all four other browsers but not on IE10 second pass through. I believe that this is a caching issue and I want to set cache to false. How can I do this?
I have tried the following:
$.get('/Course/ExplanationCorrect/', postData, function (data) {
cache: false,
$('#SurveyDiv').html(data);
});

Using this line of code will set the caching to false for all of your jQuery get requests
<script type="text/javascript">
$.ajaxSetup({ cache: false });
</script>
You can put that anywhere after your jQuery script tag
Alternatively, if you don't want to globally disable caching, you can use the following code for this request
$.ajax({
url: '/Course/ExplanationCorrect/',
cache: false,
data: data,
success: function (data) {
$('#SurveyDiv').html(data);
}
});

Related

Loading HTML in the Ajax Response

So I am dealing with this weird service when returns a html page as the ajax response which has a form and the form is triggered automatically by some scripts in the page (so when you render the page a post request will be sent to you). What I am trying to do is to load this page I am getting from the response.
Say this is my Ajax call:
var ajax_call_test = function() {
var formData = new FormData($('#documentForm')[0]);
console.log("doc form: " + formData);
$.ajaxSetup({
xhrFields: {
withCredentials: true
}
});
$.ajax("/documents/upload/", {
type: 'POST',
data: formData,
processData: false,
contentType: false,
cache: false,
async: false,
dataType: 'html',
success: function(html){
// ?
},
error: function(jqXHR, textStatus, errorThrown) {
console.log("failed: " + errorThrown);
}
});
}
So I tried to use .html to set the response to a hidden <div>. It sets the html but never triggers the form. I am guessing the javascript in that page is not loaded when I use .html.
I also cannot use jQuery.parseHTML() since the version of library I am using does not support that functionality. Any idea what should I do with response?
When ever you load new html into the DOM. The javascript does not know about it.
I have to re invoke my javascript to work with the new DOM.
Lets say I have some click events
$(function(){invokeClicks()}) // onload call
function invokeSomeAction(){
$("selector").off(); // disable previous events from old html
$("selector").on("event", function(){
// handle event
})
}
function invokeClicks(){
invokeSomeAction();
// ... etc
}
So when this JS loads, the invokeClicks() method gets called.
Now, if I replace the HTML through a $.ajax() call, all I have to do is call invokeClicks() again to clear the old events and now the new HTML will work with the javascript
$.ajax({
url: "somepath",
data: {id: 1},
method: "GET",
success: function(html){
$("container_selector").html(html);
invokeClicks(); // reinit
},
})

Cross-domain bypass?

I am currently trying to obtain this JSON array from
http://d.yimg.com/aq/autoc?query=goo&region=US&lang=en-US
However, which ever I use, it does not seem to work.
Using
$.ajax({
type: 'GET',
url: 'http://d.yimg.com/aq/autoc?query=goo&region=US&lang=en-US',
cache : false,
dataType : 'json',
success: function(data){
alert('got it!');
}
}
And also tried
$.getJSON("http://d.yimg.com/aq/autoc?query=goo&region=US&lang=en-US, function(data) {
});
As well as looking into a bypass for cross domain, and I tried using a proxy, not did not work, Maybe I am implementing it wrong? I can not seem to properly obtain the data (nothing return to data).
EDITED
I used this bypass php proxy to try and bypass the missing CORS and JSONP, and it does not seem to return the data correctly either (I followed an example). The php is within my directory.
$(document).ready(function() {
$("#tickBox").on("input", function(e) {
'use strict';
var tick = document.getElementById("tickBox").value;
$.ajax({
type: 'GET',
url: 'http://d.yimg.com/aq/autoc?query=goo&region=US&lang=en-US',
crossOrigin : true,
//dataType : 'json',
context: {},
success: function(data){
alert(data.ResultSet.Result[0].name);
}
});
});
});

Using AJAX call in MVC5

I have tried to use AJAX call in an MVC5 project as many similar examples on the web, but every time there is an error i.e. antiforgerytoken, 500, etc. I am looking at a proper AJAX call method with Controller Action method that has all the necessary properties and sending model data from View to Controller Action. Here are the methods I used:
View:
#using (Html.BeginForm("Insert", "Account", FormMethod.Post, new { id = "frmRegister" }))
{
#Html.AntiForgeryToken()
//code omitted for brevity
}
<script>
AddAntiForgeryToken = function (data) {
data.__RequestVerificationToken = $('#__AjaxAntiForgeryForm input[name=__RequestVerificationToken]').val();
return data;
};
$('form').submit(function (event) {
event.preventDefault();
//var formdata = JSON.stringify(#Model); //NOT WORKING???
var formdata = new FormData($('#frmRegister').get(0));
//var token = $('[name=__RequestVerificationToken]').val(); //I also tried to use this instead of "AddAntiForgeryToken" method but I encounter another error
$.ajax({
type: "POST",
url: "/Account/Insert",
data: AddAntiForgeryToken({ model: formdata }),
//data: { data: formdata, __RequestVerificationToken: token },
//contentType: "application/json",
processData: false,
contentType: false,
datatype: "json",
success: function (data) {
$('#result').html(data);
}
});
});
</script>
Controller: Code cannot hit to this Action method due to antiforgerytoken or similar problem.
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public JsonResult Insert(RegisterViewModel model)
{
try
{
//...
//code omitted for brevity
}
}
I just need a proper AJAX and Action methods that can be used for CRUD operations in MVC5. Any help would be appreciated.
UPDATE: Here is some points about which I need to be clarified:
1) We did not use "__RequestVerificationToken" and I am not sure if we send it to the Controller properly (it seems to be as cookie in the Request Headers of Firebug, but I am not sure if it is OK or not). Any idea?
2) Should I use var formdata = new FormData($('#frmRegister').get(0)); when I upload files?
3) Why do I have to avoid using processData and contentType in this scenario?
4) Is the Controller method and error part of the AJAX method are OK? Or is there any missing or extra part there?
If the model in your view is RegisterViewModel and you have generated the form controls correctly using the strongly typed HtmlHelper methods, then using either new FormData($('#frmRegister').get(0)) or $('#frmRegister').serialize() will correctly send the values of all form controls within the <form> tags, including the token, and it is not necessary to add the token again.
If your form does not include a file input, then the code should be
$('form').submit(function (event) {
event.preventDefault();
var formData = $('#frmRegister').serialize();
$.ajax({
type: "POST",
url: '#Url.Action("Insert", "Account")', // do not hard code your url's
data: formData,
datatype: "json", // refer notes below
success: function (data) {
$('#result').html(data);
}
});
});
or more simply
$.post('#Url.Action("Insert", "Account")', $('#frmRegister').serialize(), function(data) {
$('#result').html(data);
});
If you are uploading files, then you need you need to use FormData and the code needs to be (refer also this answer and
$('form').submit(function (event) {
event.preventDefault();
var formData = new FormData($('#frmRegister').get(0));
$.ajax({
type: "POST",
url: '#Url.Action("Insert", "Account")',
data: formData,
processData: false,
contentType: false,
datatype: "json", // refer notes below
success: function (data) {
$('#result').html(data);
}
});
});
Note that you must set both processData and contentType to false when using jQuery with FormData.
If you getting a 500(Internal Server Error), it almost always means that your controller method is throwing an exception. In your case, I suspect this is because your method is returning a partial view (as suggested by the $('#result').html(data); line of code in you success callback) but you have specified that the return type should be json (your use of the datatype: "json", option). Note that it is not necessary to specify the dataType option (the .ajax() method will work it out if its not specified)
If that is not the cause of the 500(Internal Server Error), then you need to debug your code to determine what is causing the expection. You can use your browser developer tools to assist that process. Open the Network tab, run the function, (the name of the function will be highlighted), click on it, and then inspect the Response. It will include the details of the expection that was thrown.
contentType should be application/x-www-form-urlencoded
Try this code
<script>
$('form').submit(function (event) {
event.preventDefault();
$.ajax({
method: "POST",
url: "/Account/Insert",
data: $(this).serialize(),
contentType:"application/x-www-form-urlencoded",
success: function (data) {
$('#result').html(data);
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(errorThrown);
}
});
});
</script>

How to pass `Cache: false` in $.getJSON()

I have a ajax call cacheing issue in IE 10. For that solution is to pass cache: false in ajax call. I am facing issue with that. How can I pass Cache: false in that?
$.getJSON(url , function(data){ //some code here }
Try like this:
$(document).ready(function() {
$.ajaxSetup({ cache: false });
});
i.e, you need to call the jQuery.ajaxSetup() method and pass the value false to the cache property which will causes jQuery to disable caching on ajax calls.
As answered here by Jitesh you can try this:
$.ajaxSetup({ cache: true});
$.getJSON("/MyQueryUrl",function(data,item) {
// do stuff with callback data
$.ajaxSetup({ cache: false});
});
You can't pass any configuration parameters to $.getJSON. As the documentation states, it is a shorthand function for this:
$.ajax({
dataType: "json",
url: url,
data: data,
success: success
})
So you could just use that code and then set cache: false or set it globally with $.ajaxSetup.
$(document).ready(function() {
$.ajaxSetup({ cache: false });
});
OR:
$.ajax({
type: "GET",
cache: false,
url: "yourURL",
//other settings
success: function(data) {
//do something with data
}
});
JSONObject jsobj = new JSONObject();
JSONArray jsobjs = new JSONArray();
I had a similar issue. I tried all the above suggestions but problem was not resolved. Then I found that in my servlet class I was declaring above two objects at class level. I moved these declarations inside doPost() method.
The issue got resolved. !!!

Ajax appending nonce to js files

I'm getting a unique nonce (i think a timestamp) appended to all and any of my js files every time I send a request to my rails web service:
I'm fairly sure the error has to do with the ajax call, because of jquery.ajax documentation which states cache:true in your ajax request will stop ajax from appending "_={timestamp}" to the get parameters.
I have set cache: true with no luck. How else can I stop these nonces from being applied?
ajax:
$.ajax({
beforeSend: function (xhr) {
xhr.setRequestHeader ('Authorization', api_key);
},
cache: true,
dataType: 'html',
type: 'GET',
url: url+'/gwsearch/ajax_search?d1='+d1_val+'&d2='+d2_val,
crossDomain: true,
success:function(result) {
$("#display").html(result);
},
error: function(result) {
$('#display').html('Unauthorized client.');
}
});
I solved this using an ajax prefilter:
$.ajaxPrefilter('script', function(options) {
options.cache = true;
});

Categories