Unohoo Unohoo - 2 months ago 5
Ajax Question

Passing URL variables in Ajax

I'm sure if I'm going about this the right way, but I need to pass the form variables in the URL redirect. The redirect is working, but I can't get the data to output.

$("#promoForm").on('submit', function(e) {
e.preventDefault();
var data = {
firstname: $("#firstname").val(),
lastname: $("#lastname").val(),
email: $("#email").val(),
code: $("#code").val()
};

if ( isValidEmail(data['email']) && (data['firstname'].length > 1) && (data['lastname'].length > 1) && (data['code'].length > 1) ) {
$.ajax({
type: "POST",
url: "php/promo.php",
data: data,
success: function() {
$('.success.pf').delay(500).fadeIn(1000);
$('.failed.pf').fadeOut(500);
setTimeout(function() {
window.location.href = "http://demo.example.com/signup?firstname=+data['firstname']+lastname=+data['lastname']+email=+data['email']+code=+data['code']"
}, 3000);
}
});
} else {
$('.failed.pf').delay(500).fadeIn(1000);
$('.success.pf').fadeOut(500);
}

return false;
});

Answer

You are not using variables to construct the URL:

window.location.href = "http://demo.example.com/signup?firstname=+data['firstname']+lastname=+data['lastname']+email=+data['email']+code=+data['code']"

Instead, close the string with " and append the values and follow-up strings:

window.location.href = "http://demo.example.com/signup?firstname=" + data['firstname'] + "lastname=" + data['lastname'] + "email=" + data['email'] + "code=" + data['code']

Additionally, you seem to be missing the parameter separators (&), so I should probably be:

window.location.href = "http://demo.example.com/signup?firstname=" + data['firstname'] + "&lastname=" + data['lastname'] + "&email=" + data['email'] + "&code=" + data['code']