When I put an #Url.Action inside a javascript function, Visual Studio will not recognize that function. There will be not collapse/expand option.
function exeAjax(id, destination) {
$("#contents").show();
destination.html("loading...");
$.ajax({
cache: false,
type: "GET",
url: '#Url.Action("MyAction")',
data: { "id": id },
success: function (data) {
destination.html(data);
},
error: function (xhr, ajaxOptions, thrownError) {
alert('failed');
}
});
}
The line will be recognizable if I change from:
url: '#Url.Action("MyAction")'
To:
url: 'MyAction'
Edit:
There's no error and the code runs exactly as expected.
It's just the function region is not recognized by the IDE.
Firstly you should not add any Razor code in Javascript/ Jquery. Because you will ideally like to have all the Javascript/ Jquery in a .js file, and # will try to invoke a razor code. for your issue you can do
$.ajax({
cache: false,
type: "GET",
url: '../MyAction', // path to your action
data: { "id": id },
success: function (data) {
destination.html(data);
},
error: function (xhr, ajaxOptions, thrownError) {
alert('failed');
}
});
Hope it works, happy coding
Related
I am using ASP.net MVC, and following is the Html code
$.ajax({
type: "POST",
url: urlAjax,
dataType: 'json',
data: dataValue,
async: false,
beforeSend: function () {
$("#waitscreen").show();
},
complete: function () {
$("#waitscreen").hide();
},
success: function (data) {
alert("success")
},
error: function (jqXHR, textStatus, error) {
alert("fail")
}
});
<div id=waitscreen>
//some code
</div>
Code in external js
function _post(someparameter)
{
$.ajax({
type: "POST",
url: urlAjax,
dataType: 'json',
data: dataValue,
async: false,
beforeSend: function () {
$("#waitscreen").show();
},
complete: function () {
$("#waitscreen").hide();
},
success: function (data) {
alert("success")
},
error: function (jqXHR, textStatus, error) {
alert("fail")
}
});
}
Also tried adding document ready in above code it is still not working
Above code worked fine and it show and hide as expected, but now I need to repeat ajax call in every page so I decided to move in external JS file now same code is not showing waitscreen.
Things I tried:
Loaded external script in head - Not working
Loaded external script at end of page - Not working
Question: I want to make hide and show work from external JS file
The following code snippet should help you. Tested by including the external JS file in the <head> of the main document and just below the inclusion of jQuery.
// main window
var json = {"key": "value"}
console.log('before calling _post()');
_post(json); // call external JS
// code in external JS say test.js
function _post(someparameter)
{
console.log('external JS called!');
$.ajax({
type: "POST",
url: 'http://www.niketpathak.com',
dataType: 'json',
data: someparameter,
async: true,
beforeSend: function () {
$("#waitscreen").show();
},
complete: function () {
// $("#waitscreen").hide();
},
success: function (data) {
alert("success")
},
error: function (jqXHR, textStatus, error) {
//delaying the error callback
setTimeout(function() {
$("#waitscreen").hide();
console.log('after completing the http-request');
}, 500);
}
});
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id=waitscreen>
Waitscreen....
</div>
Also, note that I have used async: true (which is also the default) since setting it to false is deprecated and not a good idea as it blocks the UI.
My ajax code in External.js file,
function _post()
{
var data = {
Email: "a#a.com",
Password:"1111"
}
$.ajax({
type: "POST",
url: "/Home/hello/",
dataType: 'json',
data: data,
async: false,
beforeSend: function () {
$("#waitscreen").show();
},
complete: function () {
$("#waitscreen").hide();
},
success: function (data) {
alert("success")
},
error: function (jqXHR, textStatus, error) {
alert("fail")
}
});
}
In my HomeController, I have hello method like this,
[HttpPost]
public ActionResult hello(LoginViewModel data)
{
ViewBag.Message = "Your contact page.";
return Json(data, JsonRequestBehavior.AllowGet);
}
And in my all the views I have the "waitscreen" div.
Now I just reference the External.js file to my _Layout page, I just drag and drop after jquery reference.
<script src="~/Scripts/External.js"></script>
Then in end of the same _Layout page, i just call the method like this,
<script>
_post();
</script>
Everything working properly.
Note: If you have only one parameter in your hello action method and suppose you have written like (int x) then in that case it will through 500 error. Because in your RouteConfig.js its mentioned that, by default the parameter name should be id. So you need to write int id.
Hope its help.
Minor question (solution seems simple but i can't seem to find it on google). I would like to use the data-setting inside my error: function. I know this may sound cryptic but allow me to use an example.
I have the following Ajax-Call (Jquery).
$.ajax({
type: "GET",
url: "Search.aspx",
data: {
action: 'GetUsers',
userSearchString: $("#txtUserSearchText").val(),
Docbase: docbase
},
success: function (data) {
.... (Do something when successfull)
},
error: function (xhr, errStatus, thrownError) {
// RIGHT HERE, i want to use action,userSearchString,Docbase that were passed to Search.aspx
// Prefferably i would like to use the data as a whole object and pass it too LogException
$("#FindUsersModal").modal("hide")
LogException(errStatus, thrownError, "SearchUsersByInput", params);
}
})
Would anyone care to point me in the right direction?
Thnx for your time.
why not creating the data as an object on the function level and then access it from error callback? for example:
function foo(){
var jsonData = {
action: 'GetUsers',
userSearchString: $("#txtUserSearchText").val(),
Docbase: docbase
}
$.ajax({
type: "GET",
url: "Search.aspx",
data: jsonData,
success: function (data) {
.... (Do something when successfull)
},
error: function (xhr, errStatus, thrownError) {
// RIGHT HERE, i want to use action,userSearchString,Docbase that were passed to Search.aspx
var something = jsonData.action;
$("#FindUsersModal").modal("hide")
LogException(errStatus, thrownError, "SearchUsersByInput", params);
}
})
}
The idea here is simple, just store your data in a variable outside the scope of the function, and you can use it where ever you want it within the function.
Here is what you need to do
var myData = {
action: 'GetUsers',
userSearchString: $("#txtUserSearchText").val(),
Docbase: docbase
}
$.ajax({
type: "GET",
url: "Search.aspx",
data: myData,
success: function (data) {
.... (Do something when successfull)
},
error: function (xhr, errStatus, thrownError) {
console.log(myData);
//You can perform any action with myData here
}
})
I suspect that I have a missing bracket but I can't find one if there is
$(document).ready(function () {
$("#additional_info_submit").click(function (e) {
e.preventDefault();
jQuery.ajax({
type: "POST",
url: "advice_response.php",
//contentType: "text/json; charset=utf-8",
dataType: "json",
data: $('#form').serialize(),
success: function (response) {
alert('yay');
},
error: function (xhr, ajaxOptions, thrownError) {
alert(thrownError);
}
});
});
});
The json_encode on the advice_response.php was missing a semi colon at the end.
I had the same problem for "PUT" method but I'm using Web Api server side so I had to change in my Web Api Controller Put Method from this :
return Request.CreateResponse(HttpStatusCode.OK);
to this:
return Request.CreateResponse(HttpStatusCode.OK, MyUpdatedObject);
I had a problem with combining som javascript functions through one function. I'm trying to build a little system to show at work. A kind a show how it could improve. Not for deployment.
The functions look like this.
// To choose an errand or with a zero start a new errand.
function buildErrandBox(number)
{
$.ajax({
url: 'db/buildErrandBox.inc.php',
type:'POST',
dataType: 'json',
data: { customerNumber: $("#customerNumber").val(), errandNumber: number },
success: function(build){ $('#newErrandsBoxResult').empty(); $('#newErrandsBoxResult').append(build.buildForm); $('#newErrandsBoxTextResult').empty(); $('#newErrandsBoxTextResult').append(build.buildText); showMinorContent('#newErrands'); $('#errandArea').val(build.area); $('#errandGroup').val(build.group); $('#errandType').val(build.type); escalateOptions(); getEscalationGroups(); },
error: function (xhr, ajaxOptions, thrownError) { alert(xhr.status); alert(thrownError); }
});
}
// To save changes on a errand.
function saveErrand()
{
$.ajax({
url: 'db/saveErrandsForCustomer.inc.php',
type:'POST',
dataType: 'json',
data: { id: $("#errandID").val(),
telephone: $("#errandTelephoneNumber").val(),
email: $("#errandEmail").val(),
area: $("#errandArea").val(),
group: $("#errandGroup").val(),
type: $("#errandType").val()
},
success: function(output_string){ showCustomerErrands(); },
error: function (xhr, ajaxOptions, thrownError) { alert(xhr.status); alert(thrownError); }
});
}
// To save a new note on an errand.
function saveTextForErrand()
{
$.ajax({
url: 'db/saveErrandsText.inc.php',
type:'POST',
dataType: 'json',
data: { id: $("#errandID").val(), text: $("#newTextForErrandTextArea").val() },
success: function(output_string){ buildErrandBox($("#errandID").val()); },
error: function (xhr, ajaxOptions, thrownError) { alert(xhr.status); alert(thrownError); }
});
}
These are three seperate functions that work when a use the buttons on the webpage. First click to start a new errand. The change what type of errand it is. Put in some notes. And save the errand. All works fine.
In the background the build errand function build the whole box of inputs and selects to show the errand. But the next function to save the errand recognizes the errand number and saves the errand in the database.
But when i combine these like below
function preMadeErrand(area, group, type, text, servicetext)
{
buildErrandBox(0);
alert($("#errandID").val());
$('#errandArea').val(area);
changeErrandBoxes();
$("#errandGroup").val(group);
changeErrandBoxes();
$("#errandType").val(type);
$("#newTextForErrandTextArea").val(servicetext);
saveTextForErrand();
$("#newTextForErrandTextArea").val(text);
saveTextForErrand();
alert($("#errandID").val());
saveErrand();
}
The errandID becomes undefined. Any ideas?
Update!
When i had the alert in the beginning of the function it works. It seems as the function for building the box is not finished before it try to use the errandID. With two alerts the second gets the errandID.
Is there any way to make it finish execution one function like buildErrandBox(0) before it continues?
If you want the AJAX function to complete before proceeding, set the async option to false:
$.ajax({
url: 'db/buildErrandBox.inc.php',
type:'POST',
dataType: 'json',
async: false, // <-- add this line
...
This will block further execution of the next statement until the result has been returned (or timeout).
Documentation
This is because ajax is asynchronous.. when alert is called. the ajax function is not yet executed..... one way you can fix it is by rearranging your functions and calling others, after the ajax success function of buildErrandBox(0).. this way we can make sure the other function is called only after buildErrandBox() is executed
function buildErrandBox(number)
{
$.ajax({
url: 'db/buildErrandBox.inc.php',
type:'POST',
dataType: 'json',
data: { customerNumber: $("#customerNumber").val(), errandNumber: number },
success: function(build){
//your stuff..
alert($("#errandID").val());
$('#errandArea').val(area);
changeErrandBoxes();
...
saveTextForErrand();
.........
// function you want to execute here
},
error: function (xhr, ajaxOptions, thrownError) {
//your stuff
}
});
}
You should have a look into using jQuery Deferred's when doing async requests like this.
http://api.jquery.com/jQuery.Deferred/
This will ensure that the requests are complete and returned before calling the next function.
Other deferred resources:
http://addyosmani.com/blog/digging-into-deferreds-1/
http://net.tutsplus.com/tutorials/javascript-ajax/wrangle-async-tasks-with-jquery-promises/
You have to make sure that all your AJAX calls have finished and then you should try to further process the server respones.
I am trying to call c# function from javascript the code i have tried is as below.
C# code
[System.Web.Services.WebMethod]
public void myFun()
{
Response.Redirect("http://google.com");
}
In javascript i have tried following two codes
function CallMe(src, dest) {
//First code i have tried
//var ctrl = document.getElementById(src);
// call server side method
//PageMethods.myFun(CallSuccess, CallFailed, dest);
//Second code i have tried
$.ajax({ type: "POST",
url: myFun, contentType: "application/json; charset=utf-8",
//data: "{passedVal:" + JSON.stringify(clientRequest) + "}", dataType: "json",
success: function (result, status) {
alert("success");
},
error: function (xhr, status, error) {
alert("ERROR");
}
});
}
function CallSuccess(res, destCtrl) {
alert("success");
}
function CallFailed(res, destCtrl) {
alert("fail");
}
but both are not woking.
Can anyone tell me what i am doing wrong?
"myFun" is a function of a WS?
If it is, in the url parameter you need to write the full function url on the WS, and not only it's name.
Hope that will solve the problem.