function getData(cardNumber) {
var path = g_contextPath + '/test/demo/searchdata';
var vData = {"cardNumber":cardNumber};
$.blockUI();
$.ajax({
type: 'GET',
url : path,
data : vData,
cache : false,
dataType : "json",
async : true,
success : function(output) {
console.log("No data found for the card number : " + output);
$.unblockUI();
},
error : function(jqXHR, textStatus, errorThrown ){
alert(errorThrown);
$.unblockUI();**`strong text`**
}
});
}
While calling above function works absolutely fine in chrome, but when test in Internet Explorer 9, its called twice one expected and other anonymous call.
My eclipse console showing following error:
ERROR [org.apache.struts2.dispatcher.Dispatcher] (http-/0.0.0.0:8080-8) Exception occurred during processing request: There is no Action mapped for namespace [/test/demo] and action name [undefined] associated with context path [/myapp].: There is no Action mapped for namespace [/test/demo] and action name [undefined] associated with context path [/myapp]. - [unknown location].
When I comment $.blockUI(); then I don't get any error in my eclipse console.
For other requirements i have used following js
Using jQuery blockUI plugin V2.53, jQuery JavaScript Library V1.8.2, jquery-ui-1.9.1.custom.js,jquery.dataTables.js,
And java backend using Struts 2
I have also added $j = jQuery.noConflict(); in jquery(document).ready(function(){});
Otherwise $.blockUI isn't working.
Switched to latest version(Version 2.70.0) of JqueryBlockui.js solved my problem
Related
I am currently working on an ASP.NET MVC site and I am having trouble with ajax posts in my release build. The site has two database connections, one to a "dummy" server that allows me to test code without affecting the live server. So, I had to configure the site to point to the live server for the release configuration, and the dummy server for the debug configuration.
Everything other than the database connection is the same, but for some reason my ajax call works fine on the debug build but throws an error on the release build. I get an ERROR THROWN: Not found alert on the ajax failure, but it only fails in the release build.
My call to the controller method looks like this:
$.ajax({
type: "GET",
url: "#Url.Action("ReleasePlotFieldName", "TestRecord")" + '?fieldName=' + x + '&fileName=' + filename,
contentType: "application/json; charset=utf-8",
data: {},
dataType: "json",
success: function (data) {
alert("success");
for (var key in data) {
let b = {
name: data[key][0],
value: data[key][1],
line: data[key][2],
arc: data[key][3]
};
chartData.push(b);
}
PlotData();
//the parameter data contains the array returned from the json PlotFieldName function
},
error: function (xhr, textStatus, errorThrown) {
alert('STATUS: ' + textStatus + '\nERROR THROWN: ' + errorThrown);
}
and the controller method looks like this:
[HttpPost]
public JsonResult ReleasePlotFieldName(string fieldName, string fileName)
{
var spiData = (DataDecoder)Session["dataDecode"];
var selectedItem = fieldName;
spiData.DecodeData(selectedItem);
List<float[]> toPlot = spiData.returnPlotVector();
return new JsonResult()
{
Data = toPlot,
JsonRequestBehavior = JsonRequestBehavior.AllowGet,
MaxJsonLength = int.MaxValue // Use this value to set your maximum size for all of your Requests
};
}
I have absolutely no clue why the release build is not executing as expected (as the debug build is doing). I welcome any and all suggestions.
Here is the network tab of the browser when the call is made
Your controller action is decorated with a [HttpPost] attribute but your jquery .ajax() request is a GET. Change one or the other depending on your use case (looks like GET could be more appropriate).
I'm getting: this error message:
No route found for "GET /module/%3C" (from
"http://site/app_dev.php/module/page")
using the following ajax call:
timeStamp = ( new Date() ).getTime();
$.ajax( {
method : 'POST',
url : 'http://site/app_dev.php/module/page/Delete/' +
timeStamp,
data : formData,
dataType : 'json',
async : true,
cache : false,
contentType : false,
processData : false,
success : function( data ) { ... },
error : function( jqXHR, textStatus, errorThrown ) { ... }
} );
Here is the page route annotation and function definitions that I'm trying to call:
/**
* #Route("/module/page")
* #Route("/module/page/{timeStamp}")
* #Route("/module/page/Delete/{timeStamp}")
*
* #return: page response HTML string, JSON encoded action results or
* JSON encoded error results.
*/
public function pageAction( $timeStamp=NULL ) { ... }
What is strange is that this function is successfully used to produce the page that contains several other similar ajax calls that do work in addition to the one above.
Here is one of the calls that work:
$.ajax( {
method : 'POST',
data : formData,
dataType : 'json',
async : true,
cache : false,
contentType : false,
enctype : 'multipart/form-data',
processData : false,
success : function( data, textStatus, jqXHR ) { ... ),
error : function( data ) { ... }
} );
The primary difference is that the ajax call that fails has an explicit url and the one that works uses the implicit address string of the page being displayed.
I tried the call with and without these two parts in the url, but get the same result either way.
I don't know if this is significant, but when I use the debugger in Chrome, the breakpoint at the first code line in the success function briefly highlights and then the page is replaced with the one displaying the 'No route found ...'
Since, the call uses message: 'POST', why would the error say 'Get' and using the explicit url that includes '/Delete' and '/' + timeStamp, why aren't these shown in the error message?
Incidentally. In the ajax call with the explicit url, I'm adding a timeStamp to prevent a previously cached response from being returned rather than making the actual call to the server to delete the information referenced in the formData object.
In another ajax call that returns the information that is supposed to be deleted by the failing call, I found that even though 'cache: false' was set, the call would return an outdated response from the a previous call if I didn't include the timeStamp in the explicit url, but with the timeStamp included, that case works fine.
The problem was that the html element, an anchor tag, that called the function containing the ajax I thought wasn't working, also had an 'href' that maked it's own request to the server for a page that didn't exist, and which contained the strange '%3C' characters.
So the real answer is the don't get wrapped around the axle and be sure to check out everything leading up to the apparent problem.
The give-away in this case was that the call leading to the error message was occurring slightly before the ajax server-side call to the right function, which is why the debugger was showing that even though the execution stopped at the right breakpoint in the success function control was 'yanked' away as the Not found error displayed.
I am running an ajax call to a servlet on click of a link. The link does not have the servlet called directly. Its called from an 'onClick' function instead.
$('#exportExcelLink').on("click", function(e) {
e.preventDefault();
var docStatus=JSON.stringify(g_checkboxVal);
$.ajax({
type : "GET",
url : '/bin/servlets/dashboardexcelexport',
data : { docStatus: docStatus },
contentType: 'application/json',
success : function(data) {
console.log("excel export call success");
},
error : function(data) {
console.log("error occured in excel export call");
}
});
});
I can see the excel being generated in my server logs and the response headers also show the file name and type (seen in network tab of console).
But the file does not pop up for me to open or save. There is no activity on the page at all.
Do I need to do something else ?
Use the built-in createObjectURL method to create a URL with your Ajax response. Then create a hidden link and make the href the object you created. Then use JavaScript to click the link
I'm using the following code to call a partial view:
$('#btnGetMilestones').click(function () {
$.ajax({
url: "GetMilestones",
type: "get",
success: function (result) {
$('#milestonesContainer').html(result);
},
error: function (xhr, status, error) {
var msg = "Response failed with status: " + status + "</br>"
+ " Error: " + error;
$('#milestonesContainer').html(msg);
},
complete: function (xhr, status) {
var doneMsg = "Operation complete with status: " + status;
alert(doneMsg);
}
});
});
for this ActionResult:
public PartialViewResult GetMilestones()
{
return PartialView("_GetMilestones");
}
The partial view has the milestones for a project (milestones and project are models). When I call the partial view like this:
<div id="milestonesContainer">
#Html.Partial("_GetMilestones")
</div>
it works fine, it gets all the milestones for the project.
But when I try to call the partial view via ajax, the error gets called: Response failed with status: error
Error: Bad Request
I'm in the details view of a projects so the url is like this http://localhost:55623/Projects/Details/2002
I'm new in ajax and javascript, so please if possible, explain me like you do to a beginner.
UPDATE:
After getting some answer and playing around to find a solution, I understand why the error appears.
I'm inside the details view, so the url is like this: http://localhost:55623/Projects/Details/2002 see there is an ID parameter.
When I make the ajax call, the url is like this http://localhost:55623/Projects/Details without the id parameter. So in return I get a 400 error code
To build on my comment:
Sorry, I was being ambiguous with the term url. Here's what I meant:
Unless your currentl url in the browser is http://<hostname>/<Controller that contains GetMilestones>, your AJAX url is incorrect. The AJAX url needs to be /<Controller>/GetMilestones.
The beginning / takes you to the root of the project, then the rest is taken care of by your route config (typically /Controller/Method/Id). That's why the AJAX url usually needs to be /Controller/Method. However, if you are at the Index view, your url is typically http://<hostname>/Controller. So, if this is the case and your AJAX url is just Method, it will take you to http://<hostname>/Controller/Method since you didn't prepend your AJAX url with a /.
Instead of url: "GetMilestones", try using url: "#Url.Action("GetMilestones")" which will render the actual relative path of the action i.e. /{Controller}/GetMilestones.
Also ensure that you are referring to the correct file name in your controller, as in your view you refer to "_GetMilestone" and you say that works, but in your controller you reference "_GetMilestones" which would not resolve if your filename is indeed "_GetMilestone"
If you're getting a 500 error, that means it's likely that you're hitting the action and an exception is occurring before or while it renders the partial view. Try navigating directly to the partial view's action in your browser by typing localhost:port/Projects/GetMilestones and see if an exception page appears. Make sure you do something like this in the Configure method of your Startup class:
public void Configure (IApplicationBuilder app)
{
app.UseDeveloperExceptionPage();
}
You should consider taking advantage of the helper methods like Url.Action to generate the correct relative path to the action method you want to call via ajax. If you are js code is inside the view, you can simply call the method like
url: "#Url.Action("GetMilestones","Project")",
If it is in an external js file, you can still use the helper method to generate the path and set it to a variable which your external js file. Make sure to do javascript namespacing when you do so to avoid possible overwriting of js global variables.
so in your view/layout you can do this
<script>
var myApp = myApp || {};
myApp.Urls = myApp.Urls || {};
myApp.Urls.mileStoneUrl= '#Url.Action("GetMilestones","Project")';
</script>
<script src="~/Scripts/PageSpecificExternalJsFile.js"></script>
And in your PageSpecificExternalJsFile.js file, you can read it like
$(function(){
$('#btnGetMilestones').click(function () {
$.ajax({
url: myApp.Urls.mileStoneUrl,
//Your existing code goes here
})
});
});
You need to change first url to something that match the route:
'/<Controller>/GetMilestones/'
switch from PartialViewResult to ActionResult
go for ajax like:
url: "GetMilestones",
type: "get",
contentType: 'application/html; charset=utf-8',
dataType : 'html'
Thanks to all for answering. I got an answer for my problem, maybe it's kinda not expected. Her it is:
change the ajax method:
$('#btnGetMilestones').click(function () {
$.ajax({
url: '/Projects/GetMilestones/' + "?id=" + window.location.href.split('/').pop(),
type: "GET",
success: function (data) {
$('#milestonesContainer').html(data);
},
error: function (xhr, status, error) {
var msg = "Response failed with status: " + status + "</br>"
+ " Error: " + error;
$('#milestonesContainer').html(msg);
},
complete: function (xhr, status) {
var doneMsg = "Operation complete with status: " + status;
alert(doneMsg);
}
});
});
and the action result:
public ActionResult GetMilestones(int? id)
{
var forProject = db.Projects.Where(x => x.ID == id).SingleOrDefault();
return PartialView("_GetMilestones",forProject);
}
Or same action result but the ajax request slightly dirrent:
$('#btnGetMilestones').click(function () {
var id;
id = #Model.ID;
$.ajax({
url: '/Projects/GetMilestones',
type: "GET",
data: "id="+id,
success: function (data) {
$('#milestonesContainer').html(data);
},
error: function (xhr, status, error) {
var msg = "Response failed with status: " + status + "</br>"
+ " Error: " + error;
$('#milestonesContainer').html(msg);
},
complete: function (xhr, status) {
var doneMsg = "Operation complete with status: " + status;
alert(doneMsg);
}
});
});
I'm loading this Handlebars.js template:
<ul></ul>
with AJAX using the following code
$.ajax({
url : 'collection.handlebars',
success : function (data) {
Handlebars.templates["collection"] = Handlebars.compile(data);
},
async : false
});
The template compilation fails with the following message in the browser console:
Uncaught Error: You must pass a string to Handlebars.compile. You passed [object Document]
After debugging I noticed that the data returned in the success callback is an HTML document and not a string. However, if I change the template to:
<ul></ul>  
the data in the success callback is received as a string and everything works.
I'm using Handlebars 1.0 RC2 and Chrome 24. Any suggestions?
You need to specify the datatype for the ajax:
$.ajax({
url : 'collection.handlebars',
success : function (data) {
Handlebars.templates["collection"] = Handlebars.compile(data);
},
dataType: "text",
async : false
});