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.
Related
$.ajax({
type: "POST",
url: '/test/',
data: data,
beforeSend: function (xhr) {
xhr.setRequestHeader("X-CSRFToken", Cookies.get('csrftoken'));
},
success: function (data) {
console.log(data);
},
error: function name(resp) {
// this part is not working
$('#steps-uid-0-p-0').show();
$('#steps-uid-0-p-1').hide();
}
});
I am unable to show and hide a div, if the response from ajax is an error. It works well in the console. I have tried using setTimeout() but is there any other solution?
I'm trying to get data from external server using JSONP, but I've stuck on the callback function.
function processLinks(data) {
alert('IT WORKS!');
};
function getLinks() {
$.ajax({
type: 'GET',
url: 'https://external-site.com/test.cgi',
dataType: 'jsonp',
success: function (data) {
console.log(data)
}
});
};
When I call getLinks(), I get ReferenceError: processLinks is not defined.
External site returns processLinks({"mark": "dog", "number":"33"});.
Thank you for any help
Here, I have a function which needs to be called before any AJAX call present in the .NET project.
Currently, I have to call checkConnection on every button click which is going to invoke AJAX method, if net connection is there, proceeds to actual AJAX call!
Anyhow, I want to avoid this way and the checkConnection function should be called automatically before any AJAX call on the form.
In short, I want to make function behave like an event which will be triggered before any AJAX call
Adding sample, which makes AJAX call on button click; Of course, after checking internet availability...
//check internet availability
function checkConnection() {
//stuff here to check internet then, set return value in the variable
return Retval;
}
//Ajax call
function SaveData() {
var YearData = {
"holiday_date": D.getElementById('txtYears').value
};
$.ajax({
type: "POST",
url: 'Service1.svc/SaveYears',
data: JSON.stringify(YearData),
contentType: "application/json; charset=utf-8",
dataType: "json",
processData: true,
success: function (data, status, jqXHR) {
//fill page data from DB
},
error: function (xhr) {
alert(xhr.responseText);
}
});
}
And below is current way to call function:
<form onsubmit="return Save();">
<input type="text" id="txtYears" /><br />
<input type="submit" id="btnSave" onclick="return checkConnection();" value="Save" />
<script>
function Save() {
if (confirm('Are you sure?')) {
SaveData();
}
else {
return false;
}
}
</script>
</form>
You cannot implicitly call a function without actually writing a call even once(!) in JavaScript.
So, better to call it in actual AJAX and for that you can use beforeSend property of ajaxRequest like following, hence there will be no need to call checkConnection() seperately:
$.ajax({
type: "POST",
url: 'Service1.svc/SaveYears',
data: JSON.stringify(YearData),
contentType: "application/json; charset=utf-8",
dataType: "json",
processData: true,
beforeSend: function() {
if(!checkConnection())
return false;
},
success: function (data, status, jqXHR) {
//fill page data from DB
},
error: function (xhr) {
alert(xhr.responseText);
}
});
It reduces the call that you have made onsubmit() of form tag!
UPDATE:
to register a global function before every AJAX request use:
$(document).ajaxSend(function() {
if(!checkConnection())
return false;
});
The best way is to use a publish-subsribe pattern to add any extra functions to be called on pre-determined times (either before or after ajax for example).
jQuery already supports custom publish-subsrcibe
For this specific example just do this:
//Ajax call
function SaveData(element) {
var doAjax = true;
var YearData = {
"holiday_date": D.getElementById('txtYears').value
};
if (element === myForm)
{
doAjax = checkConnection();
}
if ( doAjax )
{
$.ajax({
type: "POST",
url: 'Service1.svc/SaveYears',
data: JSON.stringify(YearData),
contentType: "application/json; charset=utf-8",
dataType: "json",
processData: true,
success: function (data, status, jqXHR) {
//fill page data from DB
},
error: function (xhr) {
alert(xhr.responseText);
}
});
}
else
{
// display a message
}
}
Hope i understand correctly what you mean.
UPDATE:
in the if you can do an additional check if the function is called from the form or a field (for example add an argument SaveData(element))
If you use the saveData in html, do this: "saveData(this)", maybe you should post your html as well
You can use:
$(document)
.ajaxStart(function () {
alert("ajax start");
})
.ajaxComplete(function () {
alert("ajax complete");
})
That's it!!
use
beforeSend: function () {
},
ajax method
I want my button to do something onClick(), it has the ID btnSend. But nothing happens when I click the button which is weird and I can't figure out why.
The script is in my view for now within script tags.
$("#btnSend").click(function () {
var messageInfo = {
"Body": $("#Message").val(),
};
$.ajax({
type: "POST",
url: '/Api/Posts',
data: JSON.stringify(messageInfo),
contentType: "application/json;charset=utf-8",
processData: true,
success: function (data, status, xhr) {
alert("The result is : " + status);
},
error: function (xhr) {
alert(xhr.responseText);
}
});
});
Are you sure your script is running after the page is loaded?
Put your script at the bottom of the page and give it a try.
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