user2755541
user2755541

Reputation: 546

Process form and url with GET using jQuery ajax

I'd like to process a form using the jQuery $.ajax GET method and also have the query parameters end up in the url. If I process the form without jquery, I can accomplish this, but if I do it through jQuery's $.ajax method I have to prevent the browser's default action with event.preventDefault(), in which case the parameters never end up in the url. Basically, what I'd like this to do is submit/process the form if someone types in the query from the url (i.e. mysite.com?param1=myValue ) OR if they click the submit button.

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

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

myScript.php:

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

Upvotes: 0

Views: 230

Answers (1)

Branden Tanga
Branden Tanga

Reputation: 174

Build a standard button (not submit), and on the onClick of that button, build your query string and do your ajax call. That's easier than trying to short circuit the standard form submit. Your code is nearly there already.

If someone manually types in a url with parameters and clicks "go", your server side code will return the same response as an ajax call, because the server doesn't care who calls it, so no worries there. What I would do is add an extra parameter to the ajax call, and on the server side, if this param is present (meaning it was called from ajax and data will return to an existing page), just return the json. If the parameter is missing (meaning it was called from a standard submit), return an entire html document, most likely the same page but with the json already processed in the dom.

It's pretty common to have server side code go "if it's an ajax, return this, else return this AND a full html document".

Upvotes: 2

Related Questions