function name does not exist in the current context is the error it gives me. I want a dynamic ajax call. Why does this happen? I get the handlers are processed server side, but I do not know how to go around this issue.
var getManager = function (functionName, contentDiv) {
console.log("aircraft manager refresh called");
$.ajax({
type: "GET",
url: '#Url.Action(functionName, "AdminTools")',
cache: false,
data: {},
error: function () {
alert("An error occurred.");
},
success: function (data) {
$("#".concat(contentDiv)).html(data);
}
});
}
I highly recommend you don't couple your server-side and client-side code like:
$.ajax({
type: "GET",
url: '#Url.Action(functionName, "AdminTools")', //THIS
It will turn into a maintenance nightmare. Instead:
<div id="#contentDiv" data-url="#Url.Action(functionName, "AdminTools")">
#* content *#
</div>
then
var getManager = function (functionName, contentDiv) {
console.log("aircraft manager refresh called");
var url = contentDiv.data("url");
$.ajax({
type: "GET",
url: url,
// .....
if you decide later to have multiple contentdivs each can have it's own url, and your code is reusable.
Related
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've been searching my brains out but I can't seem to wrap my head around the little help I find.
I'm running a database that is being fed by data from another DB. The csv transport is handled by a third party server providing executable "flows" which compile and deliver the data.
I have a php script to handle the request (can't be done directly via Javascript because of the missing 'Access-Control-Allow-Origin' header). But this runs nicely. I can trigger the flow.
This is not the problem though.
What I want to do: trigger the flow #onClick of a button with something like this:
function trigger_func(flowID) {
$.ajax({
url: './ajaxPHP_handler.php',
data: "flowid="+flowID,
dataType: 'json',
success: function(result) {
var jsonResult = jQuery.parseJSON(result);
console.log(jsonResult.runID);
}
});
}
With the flowID and the resulting runID I want to check back like every second or so.
function check_status(flowID, runID) {
$.ajax({
url: './ajaxPHP_handler.php',
data: "flowid="+flowID+"&action=status&runId="+runID,
dataType: 'json',
success: function(result){...}
});
}
This will return the status / progress of the flow.
It will start for a few seconds with status==null, then go on to status=='running' and finally status=='success'.
I have gotten check_status() to run for i.e. 15 times with a setTimeout in a for loop within the success-function of trigger_func() and it works fine too.
But I cannot for the life of me figure out how I would link this stuff together to have it checking until status is 'success' and then stop checking, update page content and so on...
I have also fiddled with something like
trigger_func(id).done(function(result){
console.log(result);
});
This works too but still I can't think my way further to the checking every second until 'success'. I guess it comes down to getting the variable 'status' back into my loop so I can break it.
Maybe someone knows of a comprehensible example somewhere online...
You could do this:
function periodically_check_status_until_success(flowID, runID) {
setTimeout(function() {
$.ajax({
url: './ajaxPHP_handler.php',
data: { flowid: flowID, action: status, runId: runID },
dataType: 'json',
success: function(result){
if (result != 'success') {
periodically_check_status_until_success(flowID, runID);
}
}
});
}, 5000); // Five seconds
}
Note: You can use an object for the data option, rather than concatenate the string yourself.
So just keep calling it
var flowID, runID;
function trigger_func(flowID) {
$.ajax({
url: './ajaxPHP_handler.php',
data: "flowid="+flowID,
dataType: 'json',
success: function(result) {
var jsonResult = jQuery.parseJSON(result);
runID= jsonResult.runID;
check_status();
}
});
}
function check_status() {
$.ajax({
url: './ajaxPHP_handler.php',
data: "flowid="+flowID+"&action=status&runId="+runID,
dataType: 'json',
success: function(result){
if (result is not what you want) {
setTimeout(check_status,1000);
}
}
});
}
ajax are async so you have to manage by this via some 3rd party variable
Like Init with value 0
var _status = 0
than change it on your first call set it 1
function trigger_func(flowID) {
$.ajax({
url: './ajaxPHP_handler.php',
data: "flowid="+flowID,
dataType: 'json',
success: function(result) {
var jsonResult = jQuery.parseJSON(result);
console.log(jsonResult.runID);
check_status(flowID, runID);
}
});
}
function check_status(flowID, runID) {
$.ajax({
url: './ajaxPHP_handler.php',
data: "flowid="+flowID+"&action=status&runId="+runID,
dataType: 'json',
success: function(result){
//at end status=='success'.
if(status=='success'){
// end part
}else{// running
check_status(flowID, runID);
}
// clear timeout will stop that time interval after success
}
});
}
I have an ajax function is called when a form is completed. It is suppose to redirect to a certain page if there is a success for a failure. When I run the form in IE, it works perfectly but in Firefox, the page does not redirect at all. It just refreshes the page. Here is the ajax code:
$.ajax({
url: "someURL",
type: "POST",
dataType: "xml",
data: params,
success: function () { window.location = 'success_page.htm' },
failure: function () { window.location = 'error_page.htm' }
});
Well, there's a minor mistake in your code: you are missing some semicolons:
$.ajax({
url: "someURL",
type: "POST",
dataType: "xml",
data: params,
success: function () { window.location = 'success_page.htm'; },
failure: function () { window.location = 'error_page.htm'; }
});
If this still doesn't resolve your problem, then I would guess there is something wrong with your params variable. Could you show us the whole code?
try
window.location = '/error_page.htm'
Sometimes working with IE I had the same problem, I use window.location.href instead of window.location
I have a code for pulling data from careerbuilders api. The link works well when tested on the browser, but I can't seem to parse anything from it. Care to tell me what is wrong?
html code:
<div class="main">
Companies:
</div>
jQuery code:
$(document).ready(function () {
$.ajax({
type: "GET",
url: "http://api.careerbuilder.com/v1/jobsearch?DeveloperKey=WDHL4Z86PBQY29Z7ZQQS&Location=Canada",
dataType: "xml",
success: xmlParser(xml)
});
});
function xmlParser(xml) {
$(xml).find("JobSearchResult").each(function () {
$(".main").append(
$(this).find("Company").text()
);
});
}
Here is a jsfiddle live example: http://jsfiddle.net/Cc4SY/
In your case xml won't be defined. You have to wrap the success callback in another function which in turn will call your xmlParser function.
What you are doing is calling the xmlParser function and assigning the return value as the success callback, which is not intended. So you have wrap it in another function and call xmlParser from that function and in that case the xml response will be properly passed to the xmlParser and you will able to parse it.
The code might look like this:
$(document).ready(function () {
$.ajax({
method: "GET",
url: "http://api.careerbuilder.com/v1/jobsearch?DeveloperKey=WDHL4Z86PBQY29Z7ZQQS&Location=Canada",
dataType: 'xml',
success: function (response) {
xmlParser(response);
}
});
});
function xmlParser(response){
var xml = $.parseXML(response);
$(xml).find("JobSearchResult").each(function () {
$(".main").append(
$(this).find("Company").text()
);
});
}
I think now it's working:
$(document).ready(function () {
$.ajax({
type: "GET",
url: "http://api.careerbuilder.com/v1/jobsearch?DeveloperKey=WDHL4Z86PBQY29Z7ZQQS&Location=Canada",
dataType: "xml",
success: function(xml)
{
xmlParser(xml);
}
});
});
Fiddle here: http://jsfiddle.net/Cc4SY/2/
Console response: XMLHttpRequest cannot load http://api.careerbuilder.com/v1/jobsearch?DeveloperKey=WDHL4Z86PBQY29Z7ZQQS&Location=Canada. Origin http://fiddle.jshell.net is not allowed by Access-Control-Allow-Origin.
It's a jsfiddle restriction.
I want to be able to call a function from the "on success" region instead of having to place my code in that region. I'll be using the code twice so I'm trying to figure out how to place it outside of the jQuery.ajax() function.
Here is my current code:
$.ajax({
type: "GET",
url: "ws/getweather.ashx?zip=" + vZip,
dataType: "xml",
success: function (xml) {
$(xml).find('weather').each(function () {
// Load New Data
...
});
},
error: function (xml) {
alert("Unrecognized Region. Please try again.");
}
});
So instead of having...
function (xml) {
$(xml).find('weather').each(function () {
// Load New Data
...
});
I'd like to put the name of another function, and pass the xml to that function. That way I can have other events call the same set of code.
Thanks in advance!
UPDATE===================================================
Thanks to Mike Richards for his timely response. I'm including the exact syntax below because I had to add a few details to make it work...meaning, pass the XML to the other function.
$.ajax({
type: "GET",
url: "ws/getweather.ashx?zip=32751",
dataType: "xml",
success: function (xml){
weatherize(xml);
},
error: function (xml) {
alert("Unrecognized Region. Please try again.");
}
});
And then somwhere below, my other function
function weatherize(xml) {
$(xml).find('weather').each(function () {
// Load New Data
...
})
};
you can just pass in a function for that parameter :)
success : successFunction,
and then, somehwere else:
function successFunction(data) {
// Do Something
}