Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery onchange select submit a form to PHP

Tags:

jquery

I have no code to really show you here, but let's say I have a form with 3 HIDDEN fields that contain date, city and address. I also have a select with 3 options (let's say Apple, Microsoft and Google).

What I want is that when a user changes the select to a different option, jquery should send the value of the selectbox + the 3 hidden fields to a PHP page, say proces.php. Proces.php handles the mysql_query etc, and it doesn't give anything back.

Can anyone show me how this is done? I don't expect anyone to write a whole script for me since I didn't provide any html code, but just the outline, or maybe a link to a tutorial or something.

like image 951
Student Avatar asked Jun 04 '26 01:06

Student


2 Answers

First of all your form should look something like this:

<form action="process.php" method="post" id="myForm">
    <select name="site" id="site">
        <option>Apple</option>
        <option>Google</option>
        <option>Microsoft</option>
    </select>
    <input type="hidden" name="date" value="01/05/2012" />
    <input type="hidden" name="city" value="London" />
    <input type="hidden" name="address" value="[... address ...]" />
</form>

Then to submit via AJAX you would use the serialize() method to gather the form data:

$("#site").on("change", function() {
    var $form = $("#myForm");
    var method = $form.attr("method") ? $form.attr("method").toUpperCase() : "GET";
    $.ajax({
        url: $form.attr("action"),
        data: $form.serialize(),
        type: method,
        success: function() {
            // do stuff with the result, if you want to 
        }
    });
});

Alternatively if you don't want to use AJAX, just the standard form submission, you can trigger the form to submit, like this:

$("#site").on("change", function() {
    $("#myForm").submit();
});
like image 55
Rory McCrossan Avatar answered Jun 05 '26 16:06

Rory McCrossan


if you want to send the form using jquery you can use Jquery Form plugin<
http://jquery.malsup.com/form/ so what basically u can do is to use

$(document).ready(function(){
$('form selector').ajaxForm(opts);
//u can define the opt urself itz easy look at the link
$("selects selector").change(function(){
$(form selector).ajaxSubmit(function(){//something you wanna do if form is submitted successfully})
});
});
like image 22
Parv Sharma Avatar answered Jun 05 '26 16:06

Parv Sharma



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!