0

I am creating a simple form input demo. Values are stored from a form in variables then they are put into json object and it is sent via ajax.

My Json object validates but how do I reference it in the data field in $.ajax? My code:

$(document).ready(function() {
  $('.submitForm').on('click',function(event){
event.preventDefault();

    var firstName = $('#firstName').val();
    var lastName  = $('#lastName').val();
    var phone     = $('#phoneNumber').val();
    var address   = $('#address').val();
    var $out      = $("#formResults");

    $out.append("<p>" + firstName  +' '+ lastName + "</p>" +                                       
                "<p>" + $('#phoneNumber').val() + "</p>" + 

                    //json object
                     {
                       "firstName" : "firstName", 
                        "lastName" : "lastName",
                        "phoneNumber" : "phoneNumber",
                        "address" : "address"
                       }


                         $.ajax({
                         url: 'http://localhost/xyz/markup/',
                         method:  'GET',
                         data: jsonObject
                         error: alert("error")
                         complete: alert ("complete")
                                                 });
                                     });            
                                     });

thanks!

1
  • you have some commas missing: error: alert("error"), complete: alert ("complete")... Commented Oct 23, 2012 at 14:39

1 Answer 1

4
"firstName" : "firstName",

should be

"firstName" : firstName,
              ^---     ^---note lack of quotes

and similarly for the other 3 fields.

you're trying to do string:string, instead of string:variable.

As well, nowhere in your code is jsonObject actually defined.

Major note: do not build JSON text yourself. It's very risky. One single syntax error (misplaced quote usually) and the whole json object becomes invalid. You'd be better off building a normal JS data structure, then using the provided json encoding facilities to produce the json string.

Sign up to request clarification or add additional context in comments.

2 Comments

if i remove the quotes it will not validate in jsonlint. How come?
because you're producing something like "firstname":John Doe which is not valid json. like I said, don't try to build your own json string. Unless you know exactly what you're doing and what json's syntax requirements are, you'll just end up in trouble. have the JSON object do the encoding/stringfying for you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.