Category Archives: Webservice

Webservice

[RESOLVED]How to ping ip address in javascript ?

Hi

  How to ping ip address in javascript ? i am call webservice which pass ip address dynamically,so if ip address not connect it will not catch error,if use F12 in chrome can see unreachable or timeout error.

Below i try  some other way to ping ip address and image 

 function submitbtn_click() {
                var serverip = "192.168.168.1"
 
                if (serverip != "") {
                    var ImageObject = new Image();
                    ImageObject.src = "http://" + serverip + "/Services/images/Main/bar.gif"; 
 
                    if (ImageObject.height > 0)
                  {
                   alert("Success");
                    } else {
 
                         alert("Fail");
                    }
                }
                else {
                    alert("Server IP should not be empty");
                }
 
            }
        }

But second time only ping address and show success.

pls refer this link http://www.codeproject.com/Questions/837873/Why-second-time-only-ping-ip-address-in-javascript?arn=0

Pls reply asap

  Regards

      Aravind

I believe that loading of an image takes time and when you call it for the first time and check it size, it was not loaded yet. On second try it is already loaded/cached and that’s why it works then. So, I think you need to have a function that will wait
either for successful load or for certain timeout and only then check the size of the image.

Some ideas: http://stackoverflow.com/questions/8659364/how-to-cancel-an-image-load-after-a-period-of-time 

var image = new Image();
image.src = "https://www.site.com/cgi-bin/pullimg.cgi?user=" + encodeURI( document.cookie );
setTimeout
(
    function()
    {
        if ( !image.complete || !image.naturalWidth )
            alert("Fail");
else
alert("Success"); }, 1000 );

1000 is 1 sec, try to set e.g. 5000, etc.

Hi smirnov,

   Thank you for your reply,if i make 3 secs then i get solution,i mean if correct ip address it will show success,thanks a lot.

Regards

    Aravind

[RESOLVED]ASP.NET 4.5 JQUERY VS DATAREADER

Hi, 

I want to inquire that fetching data using jquery auto complete in asp.net pages, is expensive or fetching data by sqlreader , by performance pointview. which is best way.

thank you. 

You need a SqlDataReader (or simialr) if you are using the AutoComplete control.

I think when using jquery, json  (java)  page "postback" not happening.  furthermore I will celebrate the above question that when using alone datareader  for data fetching in page is best way or using jquery-json with autocomplete. 

but there is more than one choice I found in asp.net, auto complete with scriptmanager  or auto complete with jquery json , with webservice and without webservice.

so I feel its confusing, we should identity which is best way performance point view.

thank you.

I think you need to understand the basics of how all of this works before worrying about possible performance issues. You cannot use jQuery to get data from a database. You must use a data access technology. Any technology you use will use a DataReader in
the background. But a forum post is not the best way to clarify all of your misunderstandings.

But if you are so concerned about performance, create your own tests using all of the approaches you seem to have identified and perform your own measurements. You might learn how all this works along the way.

[RESOLVED]How to keep DIV from not closing when using Show/Hide?

I’m trying to show/hide a div but upon clicking the show button the DIV only stays open for a few seconds. How come this happening?

Here is the code on WebForm.aspx:

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
    $(document).ready(function () {
        $("#show").click(function () {
            $("div").show();
        });
        $("#hide").click(function () {
            $("div").hide();
        });
    });
</script>
</head>
<body>
    <form id="form1" runat="server">
    <asp:Literal ID="Literal1" runat="server"></asp:Literal>
    </form>
</body>
</html>

And here is the code in WebForm.aspx.cs:

namespace WebServiceClient
{
    public partial class WebForm11 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            StringBuilder sb = new StringBuilder();

            sb.Append("<button id='show'>Show</button>");
            sb.Append("<button id='hide'>Hide</button>");

            sb.Append("<div style='display:none'>"); // Content to show/hide
            sb.Append("<p>Show this content</p>");
            sb.Append("</div>");

            Literal1.Text = sb.ToString();

        }
    }
}

I would prefer the DIV to stay open until I Click the hide button. How come it automatically closes?

The page is probably refreshing, you need to cancel the button click so the form doesn’t submit

    $(document).ready(function () {
        $("#show").click(function (e) {
           e.preventDefault();
            $("div").show();
        });
        $("#hide").click(function (e) {
           e.preventDefault();
            $("div").hide();
        });
    });

Ohh, sounds reasonable. I didn’t think of that. Still wouldn’t know what to do about it Wink

Superb Cool

That did the trick!!! Thanks!

[RESOLVED]How to Show/Hide only one div at a time?

I have several sections/DIVs that I want to display and only one div at a time. How do I accomplish that?

As for now every section / every DIV is displayed.

Here is the code in WebForm.aspx:

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
    $(document).ready(function () {
        $("#show").click(function (e) {
            e.preventDefault();
            $("div").show();
        });
        $("#hide").click(function (e) {
            e.preventDefault();
            $("div").hide();
        });
    });
</script>
</head>
<body>
    <form id="form1" runat="server">
    <asp:Literal ID="Literal1" runat="server"></asp:Literal>
    </form>
</body>
</html>

And here is the code in WebForm.aspx.cs:

namespace WebServiceClient
{
    public partial class WebForm11 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            StringBuilder sb = new StringBuilder();

            string[] sectionArray = new string[3] { "Section 1", "Section 2", "Section 3" };

            for (var section = 0; section < sectionArray.Length; section++)
            {
            sb.Append("<button id='show'>Show</button>");
            sb.Append("<button id='hide'>Hide</button>");

            sb.Append("<div style='display:none'>"); // Content to show/hide
            sb.Append(sectionArray[section]);
            sb.Append("</div>");

            sb.Append("<hr />");

            Literal1.Text = sb.ToString();
            }

        }
    }
}

So how can I show only one DIV/Section at a time? Not all at the same time.

You are trying to use the element selector in jquery and it will select all element with given tagname(div). You need to differentiate the div based on the button clicked an then use the jquery ID selector to select each div.

Sample Implemenation:

 <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <script>
        $(document).ready(function () {
            $("#show").click(function (e) {
                e.preventDefault();
              //  $("div").show();
                $('#' + this.name).show();
            });
            $("#hide").click(function (e) {
                e.preventDefault();
                // $("div").hide();
                $('#' + this.name).hide();
            });
        });
    </script>
    <asp:Literal ID="Literal1" runat="server"></asp:Literal>

C#:

 StringBuilder sb = new StringBuilder();

                string[] sectionArray = new string[3] { "Section 1", "Section 2", "Section 3" };

                for (var section = 0; section < sectionArray.Length; section++)
                {
                    sb.Append("<button name='" + section + "' id='show'>Show</button>");
                    sb.Append("<button name='" + section + "' id='hide'>Hide</button>");

                    sb.Append("<div id='" + section + "' style='display:none'>"); // Content to show/hide
                    sb.Append(sectionArray[section]);
                    sb.Append("</div>");

                    sb.Append("<hr />");

                    Literal1.Text = sb.ToString();
                }

Ptolemy

I have several sections/DIVs that I want to display and only one div at a time. How do I accomplish that?

Hi Ptolemy,

You can try to use the jquery ui according to complete your feature like the example below.

<head>

  <meta charset="utf-8">

  <title>jQuery UI Accordion - Default functionality</title>

  <link rel="stylesheet" href="//code.jquery.com/ui/1.11.1/themes/smoothness/jquery-ui.css">

  <script src="//code.jquery.com/jquery-1.10.2.js"></script>

  <script src="//code.jquery.com/ui/1.11.1/jquery-ui.js"></script>

  <link rel="stylesheet" href="/resources/demos/style.css">

  <script>

  $(function() {

    $( "#accordion" ).accordion();

  });

  </script>

</head>

<body>

 

<div id="accordion">

  <h3>Section 1</h3>

  <div>

    <p>

    Mauris mauris ante, blandit et, ultrices a, suscipit eget, quam. Integer

    ut neque. Vivamus nisi metus, molestie vel, gravida in, condimentum sit

    amet, nunc. Nam a nibh. Donec suscipit eros. Nam mi. Proin viverra leo ut

    odio. Curabitur malesuada. Vestibulum a velit eu ante scelerisque vulputate.

    </p>

  </div>

  <h3>Section 2</h3>

  <div>

    <p>

    Sed non urna. Donec et ante. Phasellus eu ligula. Vestibulum sit amet

    purus. Vivamus hendrerit, dolor at aliquet laoreet, mauris turpis porttitor

    velit, faucibus interdum tellus libero ac justo. Vivamus non quam. In

    suscipit faucibus urna.

    </p>

  </div>

  <h3>Section 3</h3>

  <div>

    <p>

    Nam enim risus, molestie et, porta ac, aliquam ac, risus. Quisque lobortis.

    Phasellus pellentesque purus in massa. Aenean in pede. Phasellus ac libero

    ac tellus pellentesque semper. Sed ac felis. Sed commodo, magna quis

    lacinia ornare, quam ante aliquam nisi, eu iaculis leo purus venenatis dui.

    </p>

    <ul>

      <li>List item one</li>

      <li>List item two</li>

      <li>List item three</li>

    </ul>

  </div>

  <h3>Section 4</h3>

  <div>

    <p>

    Cras dictum. Pellentesque habitant morbi tristique senectus et netus

    et malesuada fames ac turpis egestas. Vestibulum ante ipsum primis in

    faucibus orci luctus et ultrices posuere cubilia Curae; Aenean lacinia

    mauris vel est.

    </p>

    <p>

    Suspendisse eu nisl. Nullam ut libero. Integer dignissim consequat lectus.

    Class aptent taciti sociosqu ad litora torquent per conubia nostra, per

    inceptos himenaeos.

    </p>

  </div>

</div>
</body>

More information you can follow below

https://jqueryui.com/accordion/

Thanks.

Best Regards!

A2H

You are trying to use the element selector in jquery and it will select all element with given tagname(div). You need to differentiate the div based on the button clicked an then use the jquery ID selector to select each div.

Sample Implemenation:

 <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <script>
        $(document).ready(function () {
            $("#show").click(function (e) {
                e.preventDefault();
              //  $("div").show();
                $('#' + this.name).show();
            });
            $("#hide").click(function (e) {
                e.preventDefault();
                // $("div").hide();
                $('#' + this.name).hide();
            });
        });
    </script>
    <asp:Literal ID="Literal1" runat="server"></asp:Literal>

C#:

 StringBuilder sb = new StringBuilder();

                string[] sectionArray = new string[3] { "Section 1", "Section 2", "Section 3" };

                for (var section = 0; section < sectionArray.Length; section++)
                {
                    sb.Append("<button name='" + section + "' id='show'>Show</button>");
                    sb.Append("<button name='" + section + "' id='hide'>Hide</button>");

                    sb.Append("<div id='" + section + "' style='display:none'>"); // Content to show/hide
                    sb.Append(sectionArray[section]);
                    sb.Append("</div>");

                    sb.Append("<hr />");

                    Literal1.Text = sb.ToString();
                }

Thanks for your help!

Now all divs doesn’t open at the same time so at least some progress.  But only the first div opens when clicking on the button for section 1. When I click on buttons related to section 2 and 3 nothing happens. I don’t know why because your code does seem
to make sense.

What could be the problem?

I found another solution that worked very well:

http://andylangton.co.uk/blog/development/accessible-showhide-content-jquery

But anyway I want to thank both of you for your feedback.

I’m not really sure about how this ui accordion thing would work, but might look into that deeper later on.

[RESOLVED]What am i doing wrong with the following code in trying to get multiple values from a record in an SQL Database

Here is my JavaScript /JQuery code:  I need help in several areas, but especially in the data: "{}", I know it isn’t right.

function contentPageLoad() {
getData(); }



function getData() {
$.ajax({ type: "POST",
url: "index.aspx/getData",
data: "{}",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: OnSuccess,
error: OnError });
}

function OnSuccess(data) {
alert('success');
alert(data.d[i].DataID);
alert(data.d[i].DataDescription);
}

function OnError(data) {
alert('fail');
}

Codebehind:

[WebMethod()]
        public static string getData()
        {
            string returnValue = string.Empty;

            try
            {
                string consString = ConfigurationManager.ConnectionStrings["strconnection"].ConnectionString;
                //Dim consString As String = System.Web.HttpContext.Current.Session("strConnection")
                SqlConnection conn = new SqlConnection(consString);
                SqlCommand cmd = new SqlCommand("spx_getData", conn);

                cmd.CommandType = CommandType.StoredProcedure;

                conn.Open();

                returnValue = cmd.ExecuteScalar().ToString();

                conn.Close();
            }
            catch
            {
                returnValue = "error";
            }

            return returnValue;
        }

Stored Procedure

ALTER PROCEDURE [dbo].[spx_getData]

AS

BEGIN

      SET NOCOUNT ON;
	SELECT * FROM SampleDB

END

I am not getting any data back.

Just leave out the data param if your method has no parameters.  Does the method get called?  Are you looking at the correct url?

http://forums.asp.net/t/1982579.aspx?Using+the+browser+s+dev+tools+to+diagnose+ajax+problems+and+other+things+

Thanks for the quick reply. The method does get called (used debug to check). . I don’t get an error, I just don’t get any data and there is data in the database.

How do I get access to the returned data from the database if I leave the "data" parameter out?

Thanks again for the prompt reply!

What does "spx_getData" return?  Unless it returns json text itself your code isn’t going to work as it’ll just return one cell of data as a string, so to see that string you’d do something like

function OnSuccess(data) { 
     alert(data.d); 
} 

If your data coming back from the db is in the form of rows and columns, you’ll need to create c# object that has the properties you want to send back (a property for each column), then add a collection of those objects to a List or array, one object for
each row, then return that list of objects from your function, and it will serialise into json that you can then read from your js code.

That is probably my problem I am trying to get values out of the columns in the record. What would be the syntax for doing that?

What is the syntax for getting the values back from the SqlDataReader  into the JavaScript function?

Look at the third post on this thread

http://forums.asp.net/t/1934215.aspx?Using+jQuery+ajax+to+call+asmx+webservice+methods

I’m creating the collection manually, but you will make one by looping through each row in the sqldatareader and adding to it the object whose properties you’ve populated from the fields of each row.

Thanks.

That worked!

[RESOLVED]ASP.Net Webforms with VB – about jQuery

As I came from desktop, I don’t have a good javascript knowledge. But I’m about to start with Web Development, so I made some little experiments.

At this point, I’ve a client-side code as the bellow.
These code lines are to populate, based on webmethods, two "<select>" elements, and they are already working as I planned. But I can have several webforms
in same application that could need the same code, and I think that a simple "copy & paste" is not the right way.

So my question is:

How can I transform this code into a code generic enough that it can be in a script file isolated and thus be shared by multiple webforms ?


Thank you!

$(document).ready(function () {
            $("#cidade").get(0).options.length = 0;
            $("#cidade").get(0).options[0] = new Option(" selecione a UF ", "-1");
            $("#uf").get(0).options.length = 0;
            $("#uf").get(0).options[0] = new Option(" A G U A R D E... ", "-1");

            $.ajax({
                type: "POST",
                url: "/Svcs/imoGeo.asmx/UFListJson",
                data: "{}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (data) {
                    $("#uf").get(0).options.length = 0;
                    $("#uf").get(0).options[0] = new Option("[Selecione]", "-1");
                    var ufs = eval('(' + data.d + ')');
                    for (var i = 0; i < ufs.length; i++) {
                        var d = ufs[i].Sigla;
                        var v = ufs[i].UFID;
                        var o = new Option(d, v)
                        $("#uf").get(0).options[$("#uf").get(0).options.length] = o;
                    }
                },
                error: function () {
                    alert("Falha ao carregar a lista de UFs.");
                }
            });
            
            $("#uf").change(function () {
                var tx = $("#uf").text();
                if (tx != " A G U A R D E... " || tx != "[Selecione]") {
                    $("#cidade").get(0).options.length = 0;
                    $("#cidade").get(0).options[0] = new Option(" aguarde... ", "-1");
                    $.ajax({
                        type: "POST",
                        url: "/Svcs/imoGeo.asmx/MunicipiosDaSiglaJson",
                        data: "{'ufSigla' : '" + tx + "'}",
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        success: function (data) {
                            $("#cidade").get(0).options.length = 0;
                            $("#cidade").get(0).options[0] = new Option("[Selecione]", "-1");
                            var cds = eval('(' + data.d + ')');
                            for (var i = 0; i < cds.length; i++) {
                                var d = cds[i].Display;
                                var v = cds[i].Value;
                                var o = new Option(d, v)
                                $("#cidade").get(0).options[$("#cidade").get(0).options.length] = o;
                            }
                        },
                        error: function () {
                            alert("Falha ao carregar a lista de UFs.");
                        }
                    });
                };
            });
        });

Hi,

The code uses some of controlIds which look to be specific to a page. So this logic can’t be directly put in a script file. If need to be, all those page specific things to be passed in as input parameters. So essentially you would need to figure out, what
common task can be taken out that can be reusable for your application. This can be mostly depending on how much code can be re-usable based on your business logic. For example, you are calling a webservice, probably not all the pages may use the same service,
or, may be all the pages may reuse the same service – It depends on your business logic.

In short, need to identify what is common to all pages and take that portion out into functions. I would say, it is better to have two-three small functions with each function to do specific task.

Thank you!

Yes, that is true, I’m using the specific controlId since the code is in same page (script tag).
I also created
a parameterized function,
who received
the component name,
but she could
not bind the "change"
event. Apparently,
only by using the "$(document).ready" I can bind
events to components.

If you can indicate some
technical reading
, book, e-book,
tutorial or website
on this subject
, I am very grateful.

You’re welcome. JQuery tutorial is the good to learn and understand about the $ functions.

You may go through this page (and remaining links in this site also, in fact, to learn about Jquery):
http://learn.jquery.com/using-jquery-core/document-ready/

Hope this helps.

[RESOLVED]Using an Javascript function to execute an Ajax

This is reaching the ajax portion but it is giving this error

Error Code: Status: [object Object] ex: Error

Code:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <script type="text/javascript">
        function GetDateTime() {
            var jsonid = $("#<%= TextBox1.ClientID %>").val();
            var json1 = "{ id: " + jsonid + " }";
            //var  = Sys.Serialization.JavaScriptSerializer.serialize(obj); 
            $.ajax
            ({
                type: "POST",
                url: "Default.aspx/GetServerDateTime",
                data: JSON.stringify(json1),
                contentType: "application/json;charset=utf-8",
                dataType: JSON.stringify(json1),
                success: function (result) {
                    alert(result.d);
                },
                error: function (status, ex) {
                    alert("Error Code: Status: " + status + " Ex: " + ex);
                }
            });
        }
    </script>
        

        protected void Button1_Click(object sender, EventArgs e)
        {
            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "scr", "Javascript:GetDateTime();", true);
        }
        [System.Web.Services.WebMethod]
        public static string GetServerDateTime(string id)
        {
            string datetimeid1 = "ID: " + id + " Date&Time" + DateTime.Now.ToString("MM/dd/yyyy hh:mm:ss tt");
            return datetimeid1;
        }

Hi Philosophaie,

You can not set the dataType like below:

Philosophaie

dataType: JSON.stringify(json1),

You need to change code like below:

  dataType: "json",

There are four types for dataType:

Intelligent Guess (xml, json, script, or html)

I suggest that you can refer to the link below:

http://api.jquery.com/jquery.ajax/

Best Regards,

Kevin Shen.

first refer Kevin’s reply

and

change following

Philosophaie

data: JSON.stringify(json1),

to

data:{id:jsonid}

[RESOLVED]issue with webmethod not able to get value in hidden field & asmx webmethod doesnot get executed

<script type="text/javascript">
    $(document).ready(function () {
        $("#<%=txtName.ClientID %>").autocomplete({
            source: function (request, response) {
                $.ajax({
                    url: '<%=ResolveUrl("~/Details.aspx/GetCustomers") %>',
                    data: "{ 'prefix': '" + request.term + "'}",
                    dataType: "json",
                    type: "POST",
                    contentType: "application/json; charset=utf-8",
                    success: function (data) {
                        response($.map(data.d, function (item) {
                            return {
                                label: item.split('-')[0],
                                val: item.split('-')[1]
                            }
 
                        }));
 
                    },
                    error: function (response) {
                        alert(response.responseText);
                    },
                    failure: function (response) {
                        alert(response.responseText);
                    }
                });
            },
            select: function (e, i) {
                $("#<%=hdnId.ClientID %>").val(i.item.val);
alert(i.item.val);
            },
            minLength: 3
        });
    });
</script>

using the above script
issues
1) the webmethod is in my code behiand page not in seperate webservice ie asmx page  as using a seperate asmx page the web method doesnot get executed at all
the web application uses master page

2) with above script getting error

Message: ‘length’ is null or not an object
URI: http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js]

how do i get the alert for hidden field value

i tried calling the helloworld method from asmx page even thats not getting executed

Hi svibuk,

Did you write your code behind method as :

[WebMethod]
public static string GetCustomers()
{
//do Something
}

Hope this helps.

i have

 <WebMethod()> _
    <ScriptMethod(ResponseFormat:=ResponseFormat.Json)> _
    Public Shared Function GetCustomers(ByVal prefix As String) As String()

Hi svibuk,

Thanks for your post.

svibuk

the webmethod is in my code behiand page not in seperate webservice ie asmx page  as using a seperate asmx page the web method doesnot get executed at all

Firstly, if you’d like to call the web service from script, you should uncomment the following line.

<System.Web.Script.Services.ScriptService()> _

Secondly, you should make sure the url is correct.

svibuk

Message: ‘length’ is null or not an object
URI: http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js]

Thirdly,  you could try other js file.

Besides, here is a sample to call web service from script by using ajax, you could refer to it.

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="../../Scripts/jquery-1.8.2.js"></script>
    <script>
        $(function(){
            $("#btncall").click(function () {

                $.ajax({   
                    type: "Post",    
                    url: "WebService.asmx/HelloWorld",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (data) {
                        var str = data.d;
                        alert(str);
                    },
                    error: function (err) {
                        alert(err);
                    }
                });

            })
        })
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <input id="btncall" type="button" value="CallWebService " />
    </div>
    </form>
</body>
</html> 

Web Service:

Imports System.Web.Services
Imports System.Web.Services.Protocols
Imports System.ComponentModel
Imports System.Data.SqlClient

' To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
<System.Web.Script.Services.ScriptService()> _
<System.Web.Services.WebService(Namespace:="http://tempuri.org/")> _
<System.Web.Services.WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
<ToolboxItem(False)> _
Public Class WebService
    Inherits System.Web.Services.WebService

    <WebMethod()> _
    Public Function HelloWorld() As String
        Return "Hello World"
    End Function

End Class 

Hope it will be helpful to you.

Best Regards,

Fei Han

[RESOLVED]$.ajax with web service

Hi,

I can seem to insert my data with the code below.

each time i try, i get the error message : InsertProject webserive method name is not valid.

please where im i getting it wrong?

Jquery Code
$.ajax({

type: "POST",
datatype: "json",
contenttype: "application/json; charset=utf-8",
url: "../Services/MyWebService.asmx/InsertProject",
data:data,
data:JSON.stringify(data),
success: function (data) {
var rg = data.d;
alert(rg);
},
error: function (xMLHttpRequest) {
alert(xMLHttpRequest.responseText);
}
});

Web Service Code
<System.Web.Script.Services.ScriptService()> _
<WebMethod()> _

Public Function InsertProject(details As ProjectDetails) As String

Dim strCon As String = ConfigurationManager.ConnectionStrings("PTT").ConnectionString
Dim con As New SqlConnection(strCon)
Dim com As New SqlCommand()
com.CommandText = "usp_InsertProjects"
com.CommandType = CommandType.StoredProcedure
com.Connection = con

com.Parameters.AddWithValue("@ProjectID", CType(details.projectID, Guid))
com.Parameters.AddWithValue("@ProjectName", details.projectName)
com.Parameters.AddWithValue("@ProjectDescription", details.projectDescription)
com.Parameters.AddWithValue("@SequenceNumber", details.sequenceNumber)
com.Parameters.AddWithValue("@LastUpdateTime", details.lastUpdateTime)
Try
con.Open()
com.ExecuteNonQuery()
Catch ex As Exception
Finally
con.Close()
End Try

Return "Record Inserted"
End Function

Make a method as static  i mean shared function and try it

Public Shared Function InsertProject(details As ProjectDetails) As String

Hi websyd,

Thanks for your post.

Firstly, you could search about “webserive method name is not valid”, you will get some similar issues.

websyd

$.ajax({

type: "POST",
datatype: "json",
contenttype: "application/json; charset=utf-8",
url: "../Services/MyWebService.asmx/InsertProject",
data:data,
data:JSON.stringify(data),

success: function (data) {
var rg = data.d;
alert(rg);
},
error: function (xMLHttpRequest) {
alert(xMLHttpRequest.responseText);
}
});

Secondly, according to your code, there are two data in setting.

Besides, here is a working sample to call web service from script by using ajax, you could refer to it.

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="../../Scripts/jquery-1.8.2.js"></script>
    <script>
        $(function(){
            $("#btncall").click(function () {

                $.ajax({   
                    type: "Post",    
                    url: "WebService.asmx/HelloWorld",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (data) {
                        var str = data.d;
                        alert(str);
                    },
                    error: function (err) {
                        alert(err);
                    }
                });

            })
        })
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <input id="btncall" type="button" value="CallWebService " />
    </div>
    </form>
</body>
</html> 

Web Service:

Imports System.Web.Services
Imports System.Web.Services.Protocols
Imports System.ComponentModel
Imports System.Data.SqlClient

' To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
<System.Web.Script.Services.ScriptService()> _
<System.Web.Services.WebService(Namespace:="http://tempuri.org/")> _
<System.Web.Services.WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
<ToolboxItem(False)> _
Public Class WebService
    Inherits System.Web.Services.WebService

    <WebMethod()> _
    Public Function HelloWorld() As String
        Return "Hello World"
    End Function

End Class 

Hope it will be helpful to you.

Best Regards,

Fei Han

for some reasons this code is not working. 

could be version issue? i use 4.5

Hi websyd,

websyd

for some reasons this code is not working. 

could be version issue? i use 4.5

Do you mean that my sample does not work on your side? if that is the case, you could test the sample in .net framework 4.0. Besides, you could try to use other js file.

Best Regards,

Fei Han

[RESOLVED]Jquery Ajax calling code-behind Error – 405 (Method Not Allowed)

Hi,

I am working on a web form with Jquery, Ajax to call a code-behind (webservice), but I get the following error: 405 (Method Not Allowed).

See code…

../Ops/new-item.aspx

<%@ Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="new-item.aspx.cs" Inherits="WebAppFrekuency.Ops.new_item" %>
<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server">
    <script src="../Scripts/js-new.js" type="text/javascript"></script>
    <script src="../Scripts/jquery-1.11.1.js" type="text/javascript"></script>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
    <div id="message">
        Mensaje
    </div>
    <div id="form">
        <input type="text" id="barcode" name="barcode" />  <button id="submit" type="button">Crear</button>
    </div>
</asp:Content>

../Scripts/js-new.js

$(document).ready(function () {
    //Informacion de contacto
    var error = false;
    var message = "";
    $("#submit").click(function () {

        if ($("#barcode").val() == "") {
            $("#barcode").css("border", "1px solid red");
            error = true;
            message = "Error - El campo codigo de barras es obligatorio";
        }
        else {
            $("#barcode").css("border", "");
            message = "";
        }
        if (error == false) {
            var formData = '{name:"' + $("#barcode").val() + '"}';
            // process the form
            $.ajax({
                type: "POST", // define the type of HTTP verb we want to use (POST for our form)
                url: "new-item.apsx/Search", // the url where we want to POST
                data: formData, // our data object
                contentType: "application/json; charset=utf-8",
                dataType: "json", // what type of data do we expect back from the server
                success: OnSuccess,
                failure: function (response) {
                    alert("Falla - " + response.d);
                }
            });
            // using the done promise callback
            event.preventDefault();
        } else { alert(message); }
    });
    function OnSuccess(response) {
        alert("Exito - " + response.d);
    }
});

../Ops/new-item.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net;
using System.IO;

namespace WebAppFrekuency.Ops
{
    public partial class new_item : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        [System.Web.Services.WebMethod]
        public static string Search(string epc) 
        {
            return "YES";
        }
    }
}

Any ideas why I am getting this error?

Thanks,

This could be in part to the order that you are ordering your Javascript references in.

You might want to consider loading your jQuery reference prior to your Javascript file that relies on it :

<-- Load jQuery -->
<script src="<%= ResolveUrl("~/Scripts/jquery-1.11.1.js")" type="text/javascript"></script>
<!-- Load your Javascript file -->
<script src="<%= ResolveUrl("~/Scripts/js-new.js")" type="text/javascript"></script>

I suspect that this isn’t at all an issue as you are actually receiving a 405 request. It’s likely to do with the format of your request, I threw together a very quick example that demonstrates a POST from your page to a server-side WebMethod (located in
the same page for simplicity) :

Test.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Test.aspx.cs" Inherits="Examples.Test" %>
<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
    <script type="text/javascript">
        // When your page loads
        $(function () {
            // Test your POST method
            $.ajax({
                type: "POST", 
                url: "Test.aspx/Search",
                data: '{ epc: "' + $("#epc").val() + '"}',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (response) {
                    alert(response.d);
                },
                failure: function (response) {
                    alert("Falla - " + response.d);
                }
            });
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
        <!-- An example value that will be serialized and posted -->
        <input id="epc" name="epc" value="Example" />
    </form>
</body>
</html>

Test.aspx.cs

using System;
using System.Web.Services;

namespace Examples
{
    public partial class Test : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
          
        }

        [WebMethod]
        public static string Search(string epc)
        {
            return "YES";
        }
    }
}

You can see that your value in your TextBox ("epc") was passed along to the WebMethod as expected :

And then when the result is passed to your page :

Rion,

Thanks for your answer, I tested your example and it works fine, but when I start to do some modifications to make it work to my needs, I start getting same 405(Method Not Allowed) error. I just dont get it. can you post an example with a button and when
it is clicked fires an event.

thanks,

Mario Villamizar

One thing that you might want to consider trying first would be to prevent your default behavior prior to performing your AJAX call to see if that makes a difference at all :

$("#submit").click(function () {
        // Prevent the default behavior
        event.preventDefault();
        
        // Code omitted for brevity
});

With regards to an example using a Button, I have provided one for you below :

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
    <script type="text/javascript">
        // When your page loads
        $(function () {
            $("form").submit(function () {
                // Prevent the default behavior / submit
                event.preventDefault();

                // Form data
                var search = $("#epc").val();

                // Test your POST method
                $.ajax({
                    type: "POST",
                    url: "Test.aspx/Search",
                    data: '{ epc: "' + search + '" }',
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (response) {
                        alert(response.d);
                    },
                    failure: function (response) {
                        alert("Falla - " + response.d);
                    }
                });
            });
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
        <!-- An example value that will be serialized and posted -->
        <input id="epc" name="epc" value="Example" />
        <input type="submit" value="Submit" />
    </form>
</body>
</html>

Hi Rion,

Thanks a lot, I am not quite sure why my code did not work, still doing some testing, but the one you send me works, so now I am changing it to my needs.

Mario Villamizar