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.

user2755541
  • 536
  • 2
  • 10
  • 25

2 Answers2

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.

Josh
  • 44,706
  • 7
  • 102
  • 124
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?

Community
  • 1
  • 1
ntgCleaner
  • 5,865
  • 9
  • 48
  • 86