简体   繁体   中英

How do I post HTML form data to a php file another server using jQuery

I am a bit of a noob with jQuery and am learning for Uni.

I am working on a HTML web site with an associated HTML mobile application that I will compile in phonegap build.

I have a HTML form that I want to include on both the site and the app which I have coded and is successfully validating with jQuery. I would also like to post the form data with jQuery but am struggling to find how best to achieve this.

My form looks like this

    <form action="http://myaddress.com/process.php" method="post" name="jform" id="jform">
    <div>
    <label for="name"><b>Name:</b></label><br>
    <input type="text" name="name" id="name">
    </div>
    <div>
    <label for="dob"><b>Date of Birth:</b></label><br>
    <input type="text" name="dob" id="dob">
    </div>
    <div>
    <label for="visit"><b>Date of Visit:</b></label><br>
    <input type="text" name="visit" id="visit">
    </div>
    <div class="labelBlock">
    <b>Favourite Exhibit:</b>
    <div class="indent">
            <input  type="radio" name="fave" id="exhibit1" value="Exhibit1">
            <label for="exhibit1">Exhibit 1</label><br>
            <input type="radio" name="fave" id="exhibit2" value="Exhibit2">
            <label for="exhibit2">Exhibit 2</label><br>
            <input type="radio" name="fave" id="exhibit3" value="Exhibit3">
            <label for="exhibit3">Exhibit 3</label>
        </div>
    </div>
    <div>
    <label for="comment"><b>Comments:</b></label><br>
    <textarea name="comment" id="comment" rows="10" cols="40" draggable="false"></textarea>
    </div>
    <div id="center-button">
    <input name="submit" type="submit" id="submit" value="Submit" class="center-text">
    </div>
    </form>

My validation script looks like this:

    <script>
    $(document).ready(function() {
    $('#jform').validate({

    rules: {
    name: "required",
    dob: "required",
    visit: "required",
    fave: "required",
    comment: "required"
    }, //end rules
    messages: {
    name: {
    required: "Please tell us your name"
    },
    dob: {
    required: 'Please select your Date of Birth'
    },
    visit: {
    required: 'Please select the date you visited'
    },
    fave: {
    required: 'Please select your favourite exhibit'
    },
    comment: {
    required: 'Please tell us about your visit'
    }
    },//end messages

    errorPlacement: function(error, element) { 
    if ( element.is(":radio") ) {
    error.appendTo( element.parent()); 
    } else {
    error.insertAfter(element);
    } 
    } 
    }); // end validate 
    submitHandler: function(form) { //This is the submit handler. 
    var name = $('#name').val();
    var dob = $('#dob').val();
    var visit = $('#visit').val();
    var fave = $("input[name='fave']:radio:checked").val();
    var comment = $('#comment').val();
    $.ajax({
    type: 'POST',
    url: 'process-post.php',
    data: {name:name, dob:dob, visit:visit, fave:fave, comment:comment},
    success: function(data1){
    if (data1 == 'success') {
    window.location.href = 'index.html';
    }
    else {
    alert('Oops! It looks like something has gone wrong. Please try again.');
    }
    }
    });
    }}); // end ready

I really am struggling with this so would appreciate any help.

My PHP Looks like this

    <?php # PROCESS JOURNAL ENTRY.

    # Check form submitted.
    if ($_SERVER['REQUEST_METHOD'] == 'POST')
    {
    # Open database connection.
    require ( '../connect_db.php' ) ;

    # Execute inserting into 'forum' database table.
    $q = "INSERT INTO journal(name,dob,visit,fave,comment,date) 
    VALUES ('{$_POST[name]}','{$_POST[dob]}','{$_POST[visit]}','{$_POST[fave]}','{$_POST [comment]}',NOW() )";
    $r = mysqli_query ( $dbc, $q ) ;

    # Report error on failure.
    if (mysqli_affected_rows($dbc) != 1) { die ('Error' . mysqli_error($dbc)); } else { echo "success"; }

    # Close database connection.
    mysqli_close( $dbc ) ; 
    }

    ?>

You will need jQuery ajax . This is a very powerful function that is used any time jQuery validation is used. It also lets you submit to the PHP file and get the results without refreshing the page.

EDIT:

Depending on the complexity of your project, ajax may be overkill. You can just normally submit the form after it is validated like this:

<script>
$(document).ready(function() {
$('#jform').validate({

rules: {
name: "required",
dob: "required",
visit: "required",
fave: "required",
comment: "required"
}, //end rules
messages: {
name: {
required: "Please tell us your name"
},
dob: {
required: 'Please select your Date of Birth'
},
visit: {
required: 'Please select the date you visited'
},
fave: {
required: 'Please select your favourite exhibit'
},
comment: {
required: 'Please tell us about your visit'
}
},//end messages

errorPlacement: function(error, element) { 
if ( element.is(":radio") ) {
error.appendTo( element.parent()); 
} else {
error.insertAfter(element);
} 
} 
}); // end validate

submitHandler: function(form) { //This is the submit handler.  
    $(form).submit();
}

}); // end ready
</script>

Here is the part that I add:

submitHandler: function(form) { //This is the submit handler.  
    $(form).submit();
}

This will submit a form normally, meaning that it will run the PHP script and then refresh the page.

If you decide you want to use ajax, you can just replace $(form).submit(); with this:

var name = $('#name').val();
var dob= $('#dob').val();
var visit = $('#visit').val();
var fave = $("input[type='radio'][name='fave']:checked").val();
var comment = $('#comment').val();
$.ajax({
    type: 'POST',
    url: 'http://myaddress.com/process.php',
    data: {name:name, dob:dob, visit:visit, fave:fave, comment:comment},
    success: function(data){
        if (data == 'success') {
            //do something
        }
        else {
            //do something
        }
    }
});

The data that I am using in the success portion of the function is the value returned from the PHP script. Since you mentioned comments, I am assuming that you PHP is not returning data, but more or less a completion message. In that case, you would just have your PHP echo 'success'; if it was successful. Then fill in the "do somethings" in the jQuery.

Yes he is correct jquery's ajax will accomplish this or http post. You will use one of the mentioned methods to get the data from the HTML form and send it to the sever.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM