Coder
Coder

Reputation: 7721

It is possible to get the variables sent by Ajax in php file

I have my form defined as follows in the PHP file (Using jquery-2.1.4.min.js) :

<form id = "testForm" action="" method="post" >
    First name: <input type="text" name="FirstName" id="FirstName" value="Mickey"><br>
    Last name: <input type="text" name="LastName" id="LastName" value="Mouse"><br>
    <button type = "button" onclick="submit()">Submit Top Test </button>
</form>

The following functions is called when the button is clicked.

function submit(){  
        var firstName = $('#FirstName').val();
        alert("Inside SubmitQuery  "+firstName);// Work fine

        var request = $.ajax({
                url: 'php/<path to php file>/processPost.php',
                type:'POST',
                data:{title:firstName},
                success: function(msg) {  

                     alert(msg);// I can see the var_dumps here

                 }

                });

    }   

In processPost.php file, I have defined the following two var_dumps :

1) var_dump(isset($_POST['title']));

2) var_dump ($_POST['title']);

I can see the values getting printed in the alert(msg) window. Same is true in the Response tab of the Network tab of developers tools window. But I want to have these variables available in the processPost.php file so that I could use it to make a curl request to webservice call. Is it possible to get these variables inside processPost.php file?

Upvotes: 0

Views: 47

Answers (2)

AndrewR
AndrewR

Reputation: 6748

Yes, and you already have it.

Look closer at what's happening here. You are making an Ajax request to a php file. That file processes the $_POST variable and outputs it using var_dump(). Since the came from jQuery, the response goes back to jQuery. You have used an alert() to display that message.

In your php script, you can use $_POST['title'] to create your curl request.

Please be careful that you sanitize or validate your input so you don't create an injection hole. Don't take user input and run it directly.

Upvotes: 0

Xhynk
Xhynk

Reputation: 13840

I mean, you basically answered your own question in your question. The fact that you have this file:

processPost.php:

<?php
    var_dump( $_POST['title'] );
?>

and your success: function(msg){ alert(msg); } is properly alerting "Coder" (or whatever name you submit) Literally means that the variable $_POST['title'] is available in your processPost.php file. If alert(msg) gave you nothing, or an error, then you'd know something is wrong.

success: function(msg) means that, if successful, take the output value from your url (in this case, processPost.php), and make it available to your javascript as a variable named msg.

Upvotes: 0

Related Questions