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!
"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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.