JQuery server side method call internal - javascript

i often call my aspx server side method with the help of jquery....like
$.ajax({
type: "POST",
url: "login.aspx/Authenticate",
data: JSON.stringify(DTO),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
sHtml = data.d;
if (sHtml != "") {
alert(sHtml);
location.href = sHtml;
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
but the funny things is that i dont know how jquery call my static method from outside.
i saw that when i call my server side method then page_load does not fire but in case of updatepanel partial postback page_load execute first.
so i want to know the internal logic of jquery that how it can call server side method directly........looking for good explanation. thanks

so i want to know the internal logic of jquery that how it can call server side method directly
It can't.
jQuery can cause the browser to make an HTTP request to a URI.
The server can run code in response to a URI being requested in order to decide what content and headers to return.

What happens in jquery case is that the method is marked as webmethod which means that it works as an endpoint for an httprequest as if it is a webservice and when you do that, then the jquery make a httprequest to this method as if he is calling a webservice.
this URL will give you a deep view on what happen when you are making any ajax call http://msdn.microsoft.com/en-us/magazine/cc163499.aspx

your server side methods are marked with the [WebMethod] attribute, right? this attribute exposes the method as an xml web service.
http://msdn.microsoft.com/en-us/library/byxd99hx(v=vs.71).aspx
since this autogenerated "webservice" has nothing to do with the page, page_load is not called.

Related

Call WCF rest service with Javascript (JQuery) do not receive any response

The WCF service gets called for sure (the debug kicks in).
No response back to javasript callbacks.
If i configure the call with dataType:JSON the error callback is called.
If i configure dataType:JSONP no error occurs and no response is received (no callback happens neither error or sucess or done).
$.ajax({
type: "GET",
dataType: "jsonp",
contentType: "application/json;charset-uf8",
crossDomain: false,
async: true,
url: "http://myurl",
done: function (results) {
// Uhm, maybe I don't even need this?
var parsed = JSON.parse(results);
alert(parsed);
return results;
},
success: function (data, text) {
alert(text);
alert(data);
},
error: function (request, status, error) {
alert(request);
alert(status);
alert(error);
}
});
I'm running this on localhost.
I have no clue at all, i don't even know how to get more in depth error details.
Any help appreciated.
Directly sending an HTTP request to call the WCF service applies the Restful style service. Thereby we should ensure that WCF service is restful style whereas mostly WCF service based on the SOAP web service, and the invocation is completed by using client proxy class.
From the description, I suggest you add a breakpoint on the JS statement then debug it in the browser. Besides, Success event is deprecated in Jquery, I suggest you use the Done event callback after the AJAX method.
$.ajax({
method:"Get",
url: "http://10.157.13.69:11000/Service1.svc/GetData?value=34",
contentType:"application/json"
}).done(function(data){
console.log(data);
})
I would like that you could post the code details on the server-side so that I try to make an example as much as possible.
At last, please refer to my previous demo on this topic, wish it is useful to you.
How to fix "ERR_ABORTED 400 (Bad Request)" error with Jquery call to C# WCF service?
Feel free to let me know if there is anything I can help with.

How to send ajax request on one page and receive response on another page

I'm trying to send Ajax request using jquery and HTML5.
I have several pages in my application.
Is it possible to make Ajax request on a page(e.g sync.html) and receive response on a different page(e.g home.html).
I know there are other approaches to this like web-sockets and long pooling but if it's possible to achieve this using Ajax then that will make my work easier preventing me from changing any server configurations.
I'm using ASP.NET,C# on the server side.
The reason why I'm doing this is to prevent users from waiting for the response before they resume doing any other activity because this might take long depending on the size of data sent to server and the internet speed.
$.ajax({
dataType: 'jsonp',
jsonp: 'jsonp_callback',
url: server_url,
data: {
number_chunksdone : num_chunksdone,
sync_data: round_1_sync_data,
organisation_id: organisation_id,
sync_id: sync_id,
instrument_id: instrument_id,
user_id: user_id,
sync_data_2: round_2_sync_data
},
success: function (j) {
},
error: function (jqXHR, textStatus, errorThrown) {
}
});
Any idea?
You can try writing Location.replace() or Location.assign() method inside success function. For e.g., document.location.replace('home.html');
The Location.replace() method replaces the current resource with the one at the given URL.

Using ASP.Net session in Javascript

I have to process an operation in Javascript using data stored in session (System.Web.HttpContext.Current.Session["Filtre"])
Is it even possible to catch and do operation in Javascript using the asp.net session ?
I already tried some sample like this one without success :
var f = '<%=Session["Filtre"]%>';
In the case where this is impossible (for security issues I guess), is it possible to call a aspx.cs function in javascript who will perform the operation ?
Have a good day.
You cannot mix client side javascript and server side code (such as sessions). The processes do not run at the same time.
Your code
var f = '<%=Session["Filtre"]%>';
could work, BUT:
First the server needs to execute the <% %> block to generate a string, which is placed in some text
That text is sent to the browser, possibly as part of a page
Only in the browser it is interpreted and executed as javascript
There is no easy way for the browser to execute random server side code.
Complicated ways use AJAX calls to call specifically designed methods on the server (instead of arbitrary code).
using <scriptmanager> you can do
Please go through the below article
http://www.codeproject.com/Articles/525364/AJAX-for-Beginners-Part-3-Calling-Server-Side-Meth
Yes, your JavaScript can call a C# method if you annotate the method with WebMethod. This makes the method callable from remote Web clients (i.e. it becomes a 'page method'). MSDN.
You would need the EnableSession property set to true in order to use the Session. Example:
[WebMethod(EnableSession=true)]
public static int Example() {
...
Then call the page method from JavaScript, probably using jQuery.
$.ajax({
type: "POST",
url: "MyPage.aspx/Example",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: "{ }",
error: function (XMLHttpRequest, textStatus, errorThrown) { alert(langError + " " + textStatus); },
success: function (msg) {
alert(msg.d);
}
});

Jquery ajax success response is string not javascript object

I'm making a jQuery AJAX call to my Rails app (all run on localhost) which is responding with Javascript. The javascript is running because I'm getting the alert. But, I would like to read the my_var variable in the js.erb file. However, when I try to look at the data parameter of the success function it sees the data as a string. So doing data.my_var is undefined.
js.erb file
var my_var = "hi";
alert('this ran');
javascript
$.ajax({
url: "/a/validate?a_id=" + "<%= params[:id] %>",
context: this,
dataType: "script",
data:
{
json_a: JSON.stringify(this.a),
model_to_validate: model,
target_class: target_class,
current_class: current_class
},
success: function (data, textStatus, jqXHR) {
if(!this.orderFormViewed) {
this.orderFormViewed = data.order_block_opened;
}
},
error: function (data) {
console.log("error in ajax validate call");
debugger;
}
})
That's because that's exactly what you told it to do with dataType: "script" - look at the dataType options below. The script is run in it's own context and so you won't see that variable (I believe). You're going to need to communicate differently if you want that set. Or if you just need data send json.
https://api.jquery.com/jQuery.ajax/
"script": Evaluates the response as JavaScript and returns it as plain text. Disables caching by appending a query string parameter, "_=[TIMESTAMP]", to the URL unless the cache option is set to true. Note: This will turn POSTs into GETs for remote-domain requests.
try to change your dataType to json if you only need to get an object and be sure your server return a json.

What/when does a call to the jQuery AJAX method return?

A little background:
I am trying to implement and AJAX powered SlickGrid. There isn't much documentation so I used this example as a base.
In this example there is the following code that hits the desired web service to get the data:
req = $.jsonp({
url: url,
callbackParameter: "callback",
cache: true, // Digg doesn't accept the autogenerated cachebuster param
success: onSuccess,
error: function(){
onError(fromPage, toPage)
}
});
req.fromPage = fromPage;
req.toPage = toPage;
I'm not exactly sure what jsonp does but from what i've read it appears to be very similar to the ajax method in jQuery except it returns json and allows cross domain requests. The webservice that I happen to be calling only returns XML so I changed this chunk of code to:
req = $.ajax({
url: "/_vti_bin/lists.asmx",
type: "POST",
dataType: "xml",
data: xmlData,
complete: onSuccess,
error: function (xhr, ajaxOptions, thrownError) {
alert("error: " + xhr.statusText);
alert(thrownError);
},
contentType: "text/xml; charset=\"utf-8\""
});
req.fromPage = fromPage;
req.toPage = toPage;
My issue is that my page errors out at req.fromPage = fromPage; because req is null.
Am I wrong to think that I can just replace my jsonp call with a call to the ajax method? Is req just not set because my ajax call hasn't finished by the time that code is executed? How can I get around either of these issues?
If I comment out the last two lines and hard-code those values elsewhere everything runs fine.
Am I wrong to think that I can just replace my jsonp call with a call to the ajax method?
No, that should work just fine.
Is req just not set because my ajax call hasn't finished by the time that code is executed?
Yes, that is correct.
The ajax methods starts the request and returns immediately. If you want to do something after the response has arrived you should do that in the success event handler.
You might actually want to use the success event instead of the complete event, as the complete event happens even if there is an error.
You could specify async: false, in your settings to make the ajax call wait for the response, but that means that the browser freezes while it's waiting.
As Guffa stated, $.ajax() works asynchronically. Thus, you have to specify a callback that will be called when the request has returned a response, rather than to just use whatever $.ajax() returns.
There are a couple of different callback methods you can specify:
complete - runs when you recieve a response, regardless of its status.
success - runs when you recieve a response with a successful status code (usually 200).
error - runs when you recieve a response with an error code (for example 404 or 500).
To do something with the response body after a successful request, you should do something like
$.ajax({
...
success: function(body) {
alert('This is the method body:' + body);
}
});
Read up in the documentation on the different methods to see what more parameters you can use.

Categories