WebDevDanno
WebDevDanno

Reputation: 1122

Submitting basic form data with AJAX to PHP web service

I'm trying to submit some form data using jQuery / Ajax to a PHP web service (php file) and simply echo the results, for now.

Here is my index.html file

<html>
<head>
<title>PHP web service &amp; AJAX</title>
<link rel="stylesheet" type="text/css" href="style.css" />
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
</head>

<body>
    <h1>Hello! Is it me you're looking for?</h1>

    <form id="submit">
        <label>Name</label>
        <input id="name" type="text" name="name" />
        <label>Email</label>
        <input id="email" type="email" name="email" />
        <input class="submit" type="submit" value="Submit details" />
    </form>

    <script type="text/javascript">
        $(document).ready(function(){
            $(".submit").click(function(e) {
                e.preventDefault();

                // BUILD DATA STRING
                var name = $("#name").val();
                var email = $("#email").val();
                var dataString = "subName=" + name + "&subEmail=" + email;

                $.ajax({
                    type: 'POST',
                    url: 'results.php',
                    data: dataString,
                    success: function() {
                        window.location.href = "results.php";
                    }
                });
            });
        });
    </script>

And the PHP (results.php) file

<?php
    echo $_POST['subName'] . "<br />" . $_POST['subEmail'];
?>

Having no luck so far, can anyone help me out? I've tried this tutorial and this one as well but they haven't helped.

Upvotes: 2

Views: 3482

Answers (3)

Tilak Madichetti
Tilak Madichetti

Reputation: 4346

check out this awesome video where , Mr.Adam explains all the basics in a very simple and clear way. You do not even have to make use of third party JS libraries to do the job.

This code accepts value from a form , processes it ,and returns back to client 's HTML through Javascript

Link:- Return data from PHP with AJAX

source code : Source code of video

index.html

<html>
    <head>
        <script>
            function ajax_post(){
                // Create our XMLHttpRequest object
                var hr = new XMLHttpRequest();
                // Create some variables we need to send to our PHP file
                var url = "my_parse_file.php";
                var fn = document.getElementById("first_name").value;
                var ln = document.getElementById("last_name").value;
                var vars = "firstname="+fn+"&lastname="+ln;
                hr.open("POST", url, true);
                // Set content type header information for sending url encoded variables in the request
                hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
                // Access the onreadystatechange event for the XMLHttpRequest object
                hr.onreadystatechange = function() {
                    if(hr.readyState == 4 && hr.status == 200) {
                        var return_data = hr.responseText;
                        document.getElementById("status").innerHTML = return_data;
                    }
                }
                // Send the data to PHP now... and wait for response to update the status div
                hr.send(vars); // Actually execute the request
                document.getElementById("status").innerHTML = "processing...";
            }
        </script>
    </head>
    <body>
        <h2>Ajax Post to PHP and Get Return Data</h2>
        First Name: <input id="first_name" name="first_name" type="text">  <br><br>
        Last Name: <input id="last_name" name="last_name" type="text"> <br><br>
        <input name="myBtn" type="submit" value="Submit Data" onclick="ajax_post();"> <br><br>
        <div id="status"></div>
    </body>
</html>

my_parse_file.php

<?php 
echo 'Thank you '. $_POST['firstname'] . ' ' . $_POST['lastname'] . ', says the PHP file';
?>

Upvotes: 0

PeterKA
PeterKA

Reputation: 24638

In the success handler you want to catch the data returned by the ajax call, then output it on the page using $('#results').html(data). Additionally, if desired, you want to hide the form using $('#submit').hide(). Your code should then look like this:

$(document).ready(function () {
    $("#submit").on('submit', function (e) {
        e.preventDefault();
        $.ajax({
            type: 'POST',
            url: 'results.php',
            data: $(this).serialize(),
            success: function (data) {
                $('#results').html(data);
                //$('#submit').hide();
            }
        });
    });
});

Then you should add the following div to your page:

<div id="results">Results will go here</div>

Upvotes: 1

Ben
Ben

Reputation: 9001

With your code, you aren't actually looking out for the output of results.php and, even if you were, you're just redirecting the user to the page (which won't also POST any data).

What you want to do is this:

$.ajax({
    type: 'POST',
    url: 'results.php',
    data: dataString,
    success: function(data) { //where "data" is the output of results.php
        alert(data); //will bring up an alert box with subName and subEmail
    }
});

Upvotes: 1

Related Questions