Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 258
  • Last Modified:

JQuery - passing one parameter worked but not multiple

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
Camillia
Asked:
Camillia
  • 8
  • 7
  • 4
  • +1
2 Solutions
 
leakim971PluritechnicianCommented:
Try :

data: $("#frmContact").serializeArray(),
0
 
GaryCommented:
data: 
	JSON.stringify({
		fullname: $('#fullname').val(),
		phonenumber: $('#phonenumber').val(),
		emailaddress: $('#emailaddress').val(),
		reason: $('#reason').val()
	})

Open in new window

0
 
leakim971PluritechnicianCommented:
Try this too :
data: $("#frmContact").serialize(),
0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
RobOwner (Aidellio)Commented:
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
 
GaryCommented:
leakim's solution makes more sense (and easier to write) unless you need it in JSON format for some reason.
0
 
CamilliaAuthor Commented:
Gary's solution worked.

leak's gave me the error attached. I tried both code.
error-serializeArray.png
0
 
leakim971PluritechnicianCommented:
Will work :

data: JSON.stringify(   $("#frmContact").serializeArray()    ),
0
 
CamilliaAuthor Commented:
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
 
RobOwner (Aidellio)Commented:
0
 
leakim971PluritechnicianCommented:
I don't see anytjing to do to le it work, without change on your service or HTML... So go for Gary solution.
0
 
CamilliaAuthor Commented:
thanks
0
 
CamilliaAuthor Commented:
Thanks, Rob. Just saw your post. I'll look thru.
0
 
RobOwner (Aidellio)Commented:
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
 
RobOwner (Aidellio)Commented:
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
 
RobOwner (Aidellio)Commented:
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
 
CamilliaAuthor Commented:
Isn't using "WebMethod" required? or is there another way of doing this without using WebMethod?
0
 
RobOwner (Aidellio)Commented:
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
 
CamilliaAuthor Commented:
Let me take a look. That code works for now. But I'll read these today to get a better understanding.
0
 
CamilliaAuthor Commented:
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
 
CamilliaAuthor Commented:
Good articles, Rob. Thanks
0

Featured Post

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

  • 8
  • 7
  • 4
  • +1
Tackle projects and never again get stuck behind a technical roadblock.
Join Now