AJAX call in jQuery form submit function - c#

I'm using ASP.NET MVC. So I have a form on my page:
<form id="MyForm" name="MyForm" method="post" action="http://www.mysite.com">
<input id="hdnType" name="hdnType" type="hidden" />
</form>
I'm using the jQuery submit action to do some validation before the form is posted. I also need to make an AJAX call to set "hdnType" based on other values from several dropdowns that I didn't include in this example:
$('#MyForm').submit(function()
{
if (!ValidForm())
return false;
$.ajax({
type: "POST",
url: '/Home/GetType',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(response)
{
$('#hdnType').val(response);
}
});
return true;
}
Everything in the submit() function is supposed to run before the form posts. This was working correctly before I added that AJAX call, but now when the code reaches my AJAX call, the form posts before I can set "hdnType".
Is there a way around this?

The ajax call has a parameter async. By default it is true. This causes execution to not be held and the function to complete. Try changing it to
$.ajax({
async:false,
type: "POST",
url: '/Home/GetType',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(response)
{
$('#hdnType').val(response);
}
});
This may be a poor practice as it will freeze the browser until it is done. Consider using an asyc call back function as Dave suggests

The success function is called asynchronously, after the ajax call gets a response. If you want to set hdnType before the form is posted you'd have to move that call outside the $.ajax call. It looks like you need to get the result for hdnType from your POST action first, in a separate function, then call submit on the form.

Related

Consume ASP .Net WebService using HTML AJAX

I am trying to call a simple hellowworld function of ASP .NET WebService using JQuery AJAX call written in separate HTML file i.e. Not aspx file in ASP .NET.
Here is code of my AJAX call which works fine in aspx based web client.
$.ajax({
type: "POST",
url: "/Test1/RSSReader.asmx/GetRSSReader",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
$("#output").text(msg.d);
},
error: function (e) {
$("#output").html("WebSerivce error " + e.responseText);
}
});
I want to call same webservice and same method using .html file but it is returning error. I tried giving server address i.e. localhost but still no response.

Is there a way to capture JavaScript PageMethods calls with jQuery? (To show Loading Screen)

I'd like to know if someone knows a way, using jQuery, to capture PageMethods calls made from JavaScript in order to show a loading screen when a call begins and to hide it when it ends (when the PageMethod responds).
I know there are ways to capture ajax calls when they are made like this:
$.ajax({
type: "POST",
url: "PageName.aspx/MethodName",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
// Do something interesting here.
}
});
but is there a way to capture them and then do something when they are called like this?
JavaScript
PageMethods.serverSideMethod(responseFromServer);
CodeBehind
[WebMethod()]
public static string serverSideMethod()
{
return response;
}
I'm using jQuery 1.9.2, programming in C# and need this script to be compatible with IE6.
it's almost the same,use this url in jQuery
url: "PageName.aspx/serverSideMethod",
insert your method name without parantheses,it should work.
Edit:
you can capture start and complete event with using these ajax events:
$.ajax({
beforeSend: function(){
// Handle the beforeSend event
},
complete: function(){
// Handle the complete event
}
// ......
});
Then you can show or hide whatever you want... here is the full documentation: http://api.jquery.com/Ajax_Events/
You can just show the loading message right after or before the PageMethod call and then hide it in the callback:
PageMethods.serverSideMethod(responseFromServer);
//Show loading using jQuery Here
function responseFromServer(results){
//process results
//hide loading using jQuery
}
UPDATE:
Have you tried Sys.WebForms.PageRequestManager beginRequest Event and endRequest Event: http://msdn.microsoft.com/en-us/library/bb397432(v=vs.100).aspx and http://msdn.microsoft.com/en-us/library/bb383810(v=vs.100).aspx

unable to render Json string on client side

ascx.cs
protected string BindData()
{
List<Product> products = product.GetRepeaterData(prod);
string json = JsonConvert.SerializeObject(products);
return json;
}
ascx
<script type="text/javascript" language="javascript">
function doSomething() {
$.ajax({
type: "POST",
url: "/ProgramListSimple.aspx/BindData",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert(msg);
}
});
};
I am not able to see any alert ..I dont know if the ajax function is doing what it is suppose to do..this code is for user control & not on the aspx page does that matter? while debugging I am able to see the serialized data in json string. Its just that its not rendering on the client side....working on it since morning now I need some help please..any examples or any doc can also be useful..
You have to use the d property
alert(msg.d);
If you are using Chrome or Firefox to debug use the following to inspect a JavaScript object:
console.log("%o", msg);
In Chrome press Ctrl + Shift + J to show the developer console
I created a new aspx page. Transfered all the code behind logic to the aspx.cs from ascx.cs. The just called the url of the aspx page from my ascx page using ajax callback
type: "GET",
url:'<%=VirtualPathUtility.ToAbsolute("~/ProgramListSimpledetail.aspx") %>',
data: dataObject,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data)
I just added a small part of the fix that is very important for this to work other then this there were bunch of things that were added to make the ascx page inherit the properties from the apsx page.... but I think that was mainly related to my code...so I hope this helps someone in future...thanks for all those who tried to contribute..

How to optimize multiple $.ajax({...}) function loading in Asp.net?

I calling multiple function on page load in my asp.net web application.
All function run on page ready method
see the below code
$(document).ready(function(){
func1();
func2();
func3();
//.... so on.
});
function func1()
{
$.ajax({
type: "POST",
url: "Contents.asmx/GetText",
data: "{ }",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
/some code
}
});
}
function func2()
{
$.ajax({
type: "POST",
url: "Contents.asmx/GetTitles",
data: "{ }",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
/some code
}
});
}
.... like wise others
For backend I using SQL server-05.
When page is loading It getting more time to load,
above functions takes 30+ seconds to load.
How to optimze function calling?..
You could aggregate all the queries into a new web method which will perform all the SQL queries at once. Then send a single AJAX request to this new method. And as far as your SQL server is concerned you could also send multiple SQL queries into a single round-trip. Try optimizing the SQL queries as much as possible. Also you could cache the results of some expensive queries.
As long as /some code is not too much there is not really much you can do. These ajax calls area light-weight. Your problem is probably in the backend, where you send your requests to.
To debug/profile your problem, first check your ajax requests. Check them in a web-tool like Firebug and see that your request is expected. There you can also check which of your requests takes how long.
As you now see your bottleneck (e.g. requesting Contents.asmx/GetTitles is what takes so long), check your server that provides that page. As you did not provide code of that one, we can not help you there. But that’s where you have to look for next.

jQuery Postback with Webforms

We're redevloping a major section of our website and rather than use a 90k AJAX file I'd rather use a 19K jquery script.
I've seen the following articles;
Using jQuery for AJAX with ASP.NET
Webforms
jQuery autocomplete in ASP.NET webforms?
Autocomplete with ASP.Net MVC and
JQuery
The thing I don't get is how to do a postback to a specific method in either the code behind or another class.
I know in ASP.NET-MVC I can post back to a controller / action. How do I call a particular method in WebForms?
Something along the lines of; $.post("class and action", ( param:value}......
Any thoughts, code etc???
It is very easy to call specific methods in code-behind. Here is nice article with all the details by Dave.
Simply declare a method like this:
[WebMethod]
public static string GetDate()
{
return DateTime.Now.ToString();
}
This is all you need in jQuery:
$.ajax({
type: "POST",
url: "PageName.aspx/MethodName",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg, status, xhr) {
// Do something interesting here.
}
});
Caveats:
WebMethod must be on a static method
Must stringify posted data if sending anything (i.e. JSON.stringify(yourDataObject)), will be deserialized according to method parameters
msg is the response, the return result from your method is in the property msg.d

Categories