Ajax asp.net
You have seen my previous post of form submission with ajax.In my previous post we submit a form using jquery ajax.There we are using php for server side script.But today I am going to discuss about jquery ajax implementation in asp.net as server side script.
Jquery library for ajax
Here we are using juqery CDN(Content delivery network).We are using google CDN for juqery library.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Definition and usage of ajax method
ajax() method is used to perform an AJAX (asynchronous HTTP) request.AJAX stands for Asynchronous JavaScript and XML.Most of the web application using ajax method to access server side script.As you know if we use ajax then we don’t need to reload the page.We can easily access the server side script.
Script for ajax
Here we are implementing the ajax method. We have to add the code to the view page.
I am creating a view page basket.aspx. Here we are taking a button. When clicking on the button ajax method will be executed.
<button class="btn btn-green" onClick="runAjax()">Click me</button>
Now we declare the runAjax method. Inside this function, we write the ajax code.
function runAjax(){ $.ajax({ url:"basket.aspx/myMethod", data:'{id:"'+id+'"}', contentType:"application/json;charset=utf-8", dataType:"json", type:"POST", success:function(res){ console.log(res); }, error:function(error){ console.log(error); } }); }
Here inside ajax there are few parameter.some of them given below.
1. url: Here we have to set the path for server side script access.Inside basket.cs.aspx we declare myMethod
2. data: Here we are passing id to the server script.
3. contentType: The content type used when sending data to the server.
4. dataType: The data type expected of the server response.
5. type: Specifies the type of request(GET or POST).We are using post here.
6. success: A function to be run when the request succeeds.You get the response by using res variable.
7. error: A function to run if the request fails.
Server side script of asp.net
[System.Web.Services.WebMethod] public static string myMethod(string id){ return "new ID: "+id; }
Here we simply receive the id and returning to ajax method.If you like our post ,please share it and make a good comment.
I simply would like to give a huge thumbs up for the good data you’ve Write here on this post. I shall be coming again to your weblog for extra soon.
Packers And Movers Bangalore