1

I want to use the jQuery ajax method to process a form. In the php script that I call (myScript.php) I'd like to use the GET value that is set by submitting the form within the php script but it is not passing through properly.

<script>
 $('#myForm').submit(function(event) {
        event.preventDefault();
         $.ajax ( {
            url: "myScript.php",
            success: function (data) {
               console.log(data);
            }
        } );
    });
</script>

My form has one field (username):

<form id='myForm' action="" method="get">
    Username: <input type="text" id="username" name="username" value="" />
    <button id='submitButton' name="">Search</button>
<form>

And finally, my php script will just return back the get value.

<?php 
$returnString = array();
$returnString['username'] = $_GET['username'];
echo json_encode($returnString);
?>

The console returns: {"username":null} regardless of what value you type in the input box.

2
  • You're not passing any data into your AJAX request. Commented Mar 18, 2014 at 19:42
  • 1
    You have to send the data the user has submitted using the data attribute of the .ajax() method. Search stackoverflow, there are tons of answers. Commented Mar 18, 2014 at 19:42

2 Answers 2

1

You just need to serialize the form data:

$('#myForm').submit(function(event) {
    event.preventDefault();

    var formData = $(this).serialize();

     $.ajax ( {
        url: "myScript.php",
        data: formData,
        success: function (data) {
           console.log(data);
        }
    } );
});

Anything in the data property will get appended to the end of the URL according to spec.

Sign up to request clarification or add additional context in comments.

Comments

0

You can use the get feature of your ajax string:

type (default: 'GET')
Type: String
The type of request to make ("POST" or "GET"), default is "GET". 
Note: Other HTTP request methods, such as PUT and DELETE, can 
also be used here, but they are not supported by all browsers.   

https://api.jquery.com/jQuery.ajax/

Or, you can just make the window redirect with the variable in the URL as a string: how do I pass Jquery value to a different page?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.