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. !!!
Related
I am now in javascript, I am trying to display a indictor icon when ajax starts and hide it when it finishes, below is my code:
CSS:
div.ajax-progress {
//some setting and url
}
<body>
<div class="ajax-progress"></div>
</body>
Javascript:
$('#fileToUpload').on('change', function(e) {
var file = e.target.files[0];
var formData = new FormData($('form')[0]);
imageId = cornerstoneWADOImageLoader.fileManager.add(file);
$.ajax({
url: 'loadfile.php',
type: 'POST',
data: formData,
async: false,
dataType: 'json',
timeout : 60000,
beforeSend :function(){
$(".ajax-progress").show();
},
success: function (html) {}
$(".ajax-progress").hide();
//doing something}
});
});
but nothing happens, any idea? appreciated.
Maybe if you put $(".ajax-progress").show(); before the call of ajax $.ajax({}); and them hide it in the succes.
I don't know if that's the same to what you have in your code but you commented out the success closing bracket }
you can also use console.log() or alert() to see what's going on in your code.
Try rewriting your ajax as below:
$.ajax({
url: 'loadfile.php',
type: 'POST',
data: formData,
async: false,
dataType: 'json',
timeout : 60000,
beforeSend :function(){
//do something
},
success: function (html) {
//doing something
}
});
$(document).ajaxStart(function() {
$(".ajax-progress").show();
});
$(document).ajaxStop(function() {
$(".ajax-progress").hide();
});
This will show and hide $(".ajax-progress") in all your ajax requests within the application.
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>
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);
}
});
How do I get part of code in block #id like .load('url #id') ,but .load() doesn't get script inside #id
function ocmenu(linkurl) {
$.ajax({
url: linkurl,
cache: true
}).done(function (html) {
$('.new').append(html);
});
}
html.filter('#id') doesn't work
Try and see if this works:
$.get(linkurl,function(resp)
{
content = $("#id",resp);
$('.new').append(content);
});
try the below code snippet
function ocmenu(linkurl) {
$.ajax({
url: linkurl,
cache: true
}).done(function (html) {
$('.new').append("<div id='id'>foo</div>").append(html);
});
}
now
$("div").filter('#id')
will return desired result
Use jQuery.getScript() method:
Description: Loads a JavaScript file from the server using a GET HTTP request, then execute it.
http://api.jquery.com/jQuery.getScript/
Alternatively you can use data type:text on your AJAX call, which will return a plain text string.
i.e:
function ocmenu(linkurl) {
$.ajax({
url: linkurl,
dataType: 'text',
cache: true
}).done(function (html) {
$('.new').append(html);
});
}
i am currenty using jquery plugin to read a data file (data.html)
data.html has below format
[10,20,30,40,50]
my jquery data request and the javascript to return values is below
function test(){
var result=$.ajax({
url:'data.html',
type:'get',
dataType:'text',
async:false,
cache:false
}).responseText
return result;};
var my=test();
alert(my[0])
i want to get these values in the array format i.e i want my[0] to be value 10, but instead i get "[".
If i use eval function
my=eval(test());
i can get 10, but is there any other better way to store the returned ajax calls into an array instead of string?
Thanks
i tried the below answer and i am bit puzzled, the follow code results in myArray is null (in firebug), but i put async:false then it works. why do i need async:false to store the values into array ? (http://stackoverflow.com/questions/133310/how-can-i-get-jquery-to-perform-a-synchronous-rather-than-asynchronous-ajax-req)
jQuery.extend({getValues: function(url) {
var result = null;
$.ajax({
url: url,
type: 'get',
dataType: 'json',
cache: false,
success: function(data) {result = data;}
});
return result;}});
myArray=$.getValues("data.html");
alert(myArray[1]);
You don't need eval. Just indicate the proper dataType: 'json':
function test() {
return $.ajax({
url: 'data.html',
type: 'get',
dataType: 'json',
async: false,
cache: false
}).responseText;
}
var my = test();
alert(my[0]);
or even better do it asynchronously:
function test() {
$.ajax({
url: 'data.html',
type: 'get',
dataType: 'json',
cache: false,
success: function(result) {
alert(result[0]);
}
});
}
test();
I think jquery $.getScript('data.html',function(){alert("success"+$(this).text())} might be simpler. I have not had time to try it so if I'm on right track, improve this answer, if not I'm happy to learn now...