Solved

JQuery - passing one parameter worked but not multiple

Posted on 2014-03-11
22
252 Views
Last Modified: 2014-03-15
I've decided that I have to learn jQuery. No turning back :)

I think Rob (tagit) helped me with this once and I'm following the example.

I have an aspx page with this in code behind:

 [WebMethod]
    public static string SendContactInformation(string fullname, string phonenumber, string emailaddress, string reason)//string code,  string email, string mess
    {
         try {

         return 1;
          }

          catch (Exception ex)
        {
            //HttpContext.Current.Response.Write(ex.Message);
            return "3";
        }
        
      }

Open in new window


I first tried it with one parameter and it worked. Then I added the 3 more parameters. I get an error. I've attached the screenshot.

This I what I have:

  $.validator.setDefaults({
	submitHandler: function() {
	    alert("test");
	    
                      $.ajax({
                        type: "POST",
                        url: "ContactUsOld.aspx/SendContactInformation",
                        data: {
                                  fullname: JSON.stringify($('#fullname').val()),
                                  phonenumber: JSON.stringify($('#phonenumber').val()),
                                  emailaddress: JSON.stringify($('#emailaddress').val()),
                                  reason: JSON.stringify($('#reason').val())
                              },
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        success: function (msg) {
                            
                            if (msg.d == 1) {
                                $("#msg").text("Thank you for contacting DoctorAccessNow");
                            }

                            if (msg.d == 2) {
                                $("#msg").text("Invalid Verification code");
                            }

                            if (msg.d == 3) {
                                alert(msg.d);
                                $("#msg").text("Your contact was not sent. Please call us at 222555");
                            }
                        },
                        error: function (xhr, ajaxOptions, thrownError) {
                            alert(thrownError);
                            alert(xhr.status);
                            alert(xhr.responseText);

                            $("#msg").text("Your contact was not sent. Please call us at 222555");

                        }
                    }); }
});

Open in new window


I tried this as well:

data: JSON.stringify({ fullname: $('#fullname').val(), phonenumber: $('#phonenumber'), emailaddress: $('#emailaddress'), reason: $('#reason') }),

Open in new window


this is my form

<form action="/" method="post" runat="server" id="frmContact" role="form">
				
				<div class="row">			
					<div class="col-sm-9">
						
						<div class="row">
						    <div class="form-group col-sm-4">
								<label for="fullname">Name (Required)</label>
								<input id="fullname" name="fullname" type="text" class="form-control">
							</div>
							
							<div class="form-group col-sm-4">
								<label for="phonenumber">Phone Number</label>
								<input id="phonenumber" name="phonenumber" type="text" class="form-control">
							</div>
							<div class="form-group col-sm-4">
								<label for="emailaddress">Email address (Required)</label>
								<input id="emailaddress" name="emailaddress" type="email" class="form-control">
							</div>
                            
                             <div class="form-group col-sm-4"> 
                            <label for="reason">Comments/Questions (Required)</label>
							<textarea class="form-control" name="reason" id="reason" cols="10" rows="5"></textarea>
                            </div>
                          
						</div><!-- /.row -->
					</div><!-- /.col-sm-9 -->
                  
				</div><!-- /.row -->
                <br/>
				<input type="submit" id="btnSubmit" class="btn btn-default" value="Submit" />
                <p id="msg" style="color: red"></p>
			</form>

Open in new window

0
Comment
Question by:Camillia
  • 8
  • 7
  • 4
  • +1
22 Comments
 
LVL 82

Expert Comment

by:leakim971
ID: 39921938
Try :

data: $("#frmContact").serializeArray(),
0
 
LVL 58

Accepted Solution

by:
Gary earned 250 total points
ID: 39921950
data: 
	JSON.stringify({
		fullname: $('#fullname').val(),
		phonenumber: $('#phonenumber').val(),
		emailaddress: $('#emailaddress').val(),
		reason: $('#reason').val()
	})

Open in new window

0
 
LVL 82

Expert Comment

by:leakim971
ID: 39921965
Try this too :
data: $("#frmContact").serialize(),
0
3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

 
LVL 42

Expert Comment

by:Rob Jurd, EE MVE
ID: 39921971
No points, just clarifying
For scalability of your form, leakim's solution is the best as it wraps up everything in the form to send to the server in nice name value pairs.
Gary's on the other hand has shown you that you need to use the val() function on each of your parameters to get it's value.
0
 
LVL 58

Expert Comment

by:Gary
ID: 39921977
leakim's solution makes more sense (and easier to write) unless you need it in JSON format for some reason.
0
 
LVL 42

Assisted Solution

by:Rob Jurd, EE MVE
Rob Jurd, EE MVE earned 250 total points
ID: 39922095
0
 
LVL 7

Author Comment

by:Camillia
ID: 39922406
Gary's solution worked.

leak's gave me the error attached. I tried both code.
error-serializeArray.png
0
 
LVL 82

Expert Comment

by:leakim971
ID: 39922409
Will work :

data: JSON.stringify(   $("#frmContact").serializeArray()    ),
0
 
LVL 7

Author Comment

by:Camillia
ID: 39922414
I got the attached error. I can use Gary's solution but would be good to get this one working as well.
error.png
0
 
LVL 42

Expert Comment

by:Rob Jurd, EE MVE
ID: 39922417
0
 
LVL 82

Expert Comment

by:leakim971
ID: 39922418
I don't see anytjing to do to le it work, without change on your service or HTML... So go for Gary solution.
0
 
LVL 7

Author Comment

by:Camillia
ID: 39922421
thanks
0
 
LVL 7

Author Comment

by:Camillia
ID: 39922434
Thanks, Rob. Just saw your post. I'll look thru.
0
 
LVL 42

Expert Comment

by:Rob Jurd, EE MVE
ID: 39922436
Camilla,
There isn't really any reason that leakim's suggestion shouldn't work
See here for a demo
http://jsbin.com/negez/1/edit

You may need to specify the first element of the serialized array add demonstrated in the demo ie data1[0]
0
 
LVL 42

Expert Comment

by:Rob Jurd, EE MVE
ID: 39922441
I was going to say that it could be the web method requires certain formatting of parameters but that would time out Gary's solution, which you know works. See what the article can give you re jQuery Ajax and web methods
0
 
LVL 42

Expert Comment

by:Rob Jurd, EE MVE
ID: 39922565
Thinking about this some more, this isn't about sending form data to a server as such but it is about calling a WebMethod, which requires certain parameters.

You're wanting to call a WebMethod called SendContactInformation that has the parameters fullname, phonenumber, emailaddress and reason.

Therefore you should only be JSON encoding these elements of the form.

It's not smart enough to only take the required parameters from the serialized data.

In another scenario where you might be submitting a form to a server side script for processing you may serialize it but the server script will parse the serialized data into its constituants for processing. Very differnt from calling a method.
0
 
LVL 7

Author Comment

by:Camillia
ID: 39923115
Isn't using "WebMethod" required? or is there another way of doing this without using WebMethod?
0
 
LVL 42

Expert Comment

by:Rob Jurd, EE MVE
ID: 39923146
It's not the only way.
Working with Forms : The Official Microsoft ASP.NET Site

This shows how form data is sent and processed on the server side.

Microsoft also have their own JavaScript framework that I suggest you look at rather than jQuery. It may cause compatibility issues and the event model works slightly different.
0
 
LVL 7

Author Comment

by:Camillia
ID: 39923154
Let me take a look. That code works for now. But I'll read these today to get a better understanding.
0
 
LVL 7

Author Comment

by:Camillia
ID: 39923542
In the link above, the "Working with Forms"

@Html.ValidationMessage("employees") 

Open in new window

 

This is not C#. It's "cshtml"?

I always use the ASP.Net method of postback and calling the database, etc. I don't want to say the "old" way but since I'm learning jQuery and another way of coding, I have to call it the "old" way
0
 
LVL 7

Author Comment

by:Camillia
ID: 39923630
Good articles, Rob. Thanks
0

Featured Post

DevOps Toolchain Recommendations

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Error in script 11 58
Error in JQuery 5 54
Show/Hide ASP.NET controls with JQuery best practices 3 50
Jquery get each value 2 32
Introduction HyperText Transfer Protocol (http://www.ietf.org/rfc/rfc2616.txt) or "HTTP" is the underpinning of internet communication.  As a teacher of web development I have heard many questions, mostly from my younger students who have come to t…
This article demonstrates how to create a simple responsive confirmation dialog with Ok and Cancel buttons using HTML, CSS, jQuery and Promises
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)

831 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question