Rob
Rob

Reputation: 6370

Add url parameter via jquery and ajax

I have a form that on submit I want to pass the email address value to the url as a parameter. How can I incorporate that into my current setup below:

<form action="/event/" method="POST" id="signupForm">

And here's my

$("#signupForm").submit(function(e) {
    e.preventDefault();
    var form = $(this);
    var email = $("#EmailAddress").val();

    $.ajax({
           type: "POST",
           url: form.attr('action'),
           data: form.serialize(),
           success: function(data)
           {
               console.log(data); //data contain response from your php script
               register_signup();
               form.replaceWith("<br /><p>Thanks for signing up!</p>");
           }
         });

});

Upvotes: 1

Views: 2224

Answers (3)

Thallius
Thallius

Reputation: 2619

As an alternative you can add an input field with hidden flag to your form and set its value to the email address before serializing.

Upvotes: 1

Isma
Isma

Reputation: 15180

You could just append it to the url:

$("#signupForm").submit(function(e) {
    e.preventDefault();
    var form = $(this);
    var email = $("#EmailAddress").val();

    $.ajax({
           type: "POST",
           url: form.attr('action') + '?email=' + email,
           data: form.serialize(),
           success: function(data)
           {
               console.log(data); //data contain response from your php script
               register_signup();
               form.replaceWith("<br /><p>Thanks for signing up!</p>");
           }
         });
});

In the server you will need to retrieve the data from the query string for the parameters in the URL and from POST for the data posted from your form:

parse_str($_SERVER['QUERY_STRING'], $query);
echo $query['email'];

And for post values just simply use $_POST['input_name'].

Upvotes: 2

Nijin P J
Nijin P J

Reputation: 1322

instead of using url: form.attr('action') use it like

url: "/event/?email="+email

OR

url: form.attr('action') + '?email=' + email

So,the ajax will be like

$("#signupForm").submit(function(e) {
  e.preventDefault();
  var form = $(this);
  var email = $("#EmailAddress").val();

$.ajax({
  type: "POST",
   url:  "/event/?email="+email, //OR  url: form.attr('action') + '?email=' + email,
   data: form.serialize(),
   success: function(data){}
 });

});

Upvotes: 0

Related Questions