Click here to Skip to main content
15,892,537 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I am having a lot of trouble posting to the backend using AJAX $POST and php. Basically I want the text entered into the search bar to get posted to a php file and then get echo'd back.

HTML
<body>
    
	<form id="foo">
    <label for="bar">A bar</label>
    <input id="bar" name="bar" type="text" value="" />

    <input type="submit" value="Send" />
</form>

<script src="php.js"></script>


JavaScript
    $inputs.prop("disabled", true);

    // Fire off the request to /form.php
    request = $.ajax({
        url: "/form.php",
        type: "post",
        data: serializedData
    });

    // Callback handler that will be called on success
    request.done(function (response, textStatus, jqXHR){
        // Log a message to the console
        console.log("Hooray, it worked!");
    });

    // Callback handler that will be called on failure
    request.fail(function (jqXHR, textStatus, errorThrown){
        // Log the error to the console
        console.error(
            "The following error occurred: "+
            textStatus, errorThrown
        );
    });

    // Callback handler that will be called regardless
    // if the request failed or succeeded
    request.always(function () {
        // Reenable the inputs
        $inputs.prop("disabled", false);
    });

    // Prevent default posting of form
    event.preventDefault();
});


PHP
<?php
$bar = $_POST['bar'];
?>
Posted
Comments
Sergey Alexandrovich Kryukov 20-Jul-15 11:56am    
URL looks wrong. Do you mean "post.php"?
—SA
Member 11849794 20-Jul-15 13:23pm    
nope, I have a file named php.php that I was referencing
Kornfeld Eliyahu Peter 20-Jul-15 14:40pm    
And what the exact problem?
Do you hit the server side at all?
Mohibur Rashid 20-Jul-15 21:31pm    
What are you doing with $bar after getting the value from $_POST? Are you echoing? printing or doing something else?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900