Home > Web Front-end > JS Tutorial > How to Correctly Post Form Data Within $.load Using AJAX?

How to Correctly Post Form Data Within $.load Using AJAX?

Mary-Kate Olsen
Release: 2024-11-11 14:04:03
Original
566 people have browsed it

How to Correctly Post Form Data Within $.load Using AJAX?

Using AJAX to Correct Form Posting Within $.load

When attempting to post data from a form within an $.load call, you may encounter an issue where the post is not properly sent to the target PHP script. This can lead to the page reloading instead of processing the submitted data.

To resolve this, consider implementing AJAX. AJAX allows you to send data to a server-side PHP file without reloading the page. Here's how it works:

FILE #1:

This file contains the HTML and JavaScript code for the form.

<html>
    <head>
        <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
        <script type="text/javascript">
            $(document).ready(function() {
                $('#Sel').change(function() {
                    var opt = $(this).val();
                    var someelse = 'Hello';
                    var more_stuff = 'Goodbye';
                    $.ajax({
                        type: "POST",
                        url: "receiving_file.php",
                        data: 'selected_opt=' + opt + '&amp;something_else=' +someelse+'&amp;more_stuff='+more_stuff,
                        success:function(data){
                            alert('This was sent back: ' + data);
                        }
                    });
                });
            });
        </script>
    </head>
<body>

<select id = "Sel">
    <option value ="Song1">default value</option>
    <option value ="Song2">Break on through</option>
    <option value ="Song3">Time</option>
    <option value ="Song4">Money</option>
    <option value="Song5">Saucerful of Secrets</option>
</select>
</body>
</html>
Copy after login

FILE #2: receiving_file.php

This file is the PHP script that will process the submitted data.

    $recd = $_POST['selected_opt'];
    echo 'You chose: ' . $recd;
Copy after login

This method ensures that the form data is posted without reloading the page, allowing you to process the data and respond appropriately.

The above is the detailed content of How to Correctly Post Form Data Within $.load Using AJAX?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template