0

When using the get method on an HTML form the submitted data shows up in the URL. This page shows what I mean. I have been trying to get this to work with JQuery and AJAX using the get method but the data is not showing up in the URL for some reason. Does anyone know why? Here is my code:

$(function() {
    $('#mylink').click(function () {    
        $.get("submit.php", { name: 'John' }, function(data) {
            // blah blah blah
        });
    });
});

I want the end of the URL to be appended with ?name=John and be able to access it with the $_GET variable. How can I do this?

3 Answers 3

5

What you have works: jQuery's AJAX converts { name: 'John' } to submit.php?name=John.

And you'd access it in your PHP script like this:

<?php
echo $_GET["name"]; //ECHOs out "John"
?>

BTW don't forget to prevent the link from changing the page -

$('#mylink').click(function() {    
    $.get("submit.php", { name: 'John' }, function(data) {
        // blah blah blah
    });
    return false; //Prevents the default behavior of the link
});
Sign up to request clarification or add additional context in comments.

5 Comments

It's still not working. I changed the PHP script to be identical to the one you posted and and used alert on the data variable and it came out to be John. However, the URL remained static throughout, even with the return false. Any ideas?
@John You're using AJAX so the URL will not change. If you're getting John back in the data variable, then it's working as expected
Exactly...otherwise you need a <form>.
I want the URL to change though. I want users to be able to edit the URL and have the page react accordingly.
@NeXXeuS or a normal link with no click handler <a id="mylink" href="submit.php?name=John">Link Text</a>
1

Looks like you're missing return false; in the click handler. Probably why you're not seeing what you expect.

Eg

$(function() {
    $('#mylink').click(function () {    
        $.get("submit.php", { name: 'John' }, function(data) {
            // blah blah blah
        });
        return false;
    });
});

Comments

0

Why not just append it to the link?

$.get("submit.php?name=" + username), function(data){ ... });

BTW...please heed all the normal warnings out there about server side sanitation of your input url. No one wants to meet Little Bobby Tables...

1 Comment

I find the object map format much cleaner to look at and maintain

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.