2

New to AJAX. A little unsure about how to submit a GET request without having the entire page reload.

  1. User visits www.example.com/products/
  2. Types 'Gardening Tools`
  3. Results load inline with URL changes to www.example.com/products/results?search=Gardening+Tools all done without page reloading.
  4. Any user can use the URL www.example.com/products/results?search=Gardening+Tools and get the same result.

Note: Bullet point 4 is important. It must not be some hacky way of just adding the parameters to the URL to make it look like that. Some users might want to bookmark (besides that's why I used a GET request in the first place).


So here is a basic representation of my code that works for a POST:

The form: your basic submission using POST, I want this to be GET.

<form id="submit" action="" method="POST">
   <input type="text" name="search"/>
   <button type="submit"></button>
</form>

jQuery: Using .ajax() we send a POST request to /products/results.php

$('form#submit').submit(function (e) {
e.preventDefault();
$.ajax({
        type: 'POST',
        url: 'results.php',
        data: "search="+encodeURIComponent($('input[name="search"]').val()),
        dataType: 'json',
        success: function(data) {
            //inject some html into page
        }
    });
 }

results.php: (also just to be sure am I protected against SQL injects here? magic quotes are off).

$query = $_POST['search'];
$query = mysql_real_escape_string($query);
$query = htmlspecialchars($query);
//you get the point: straight forward db connect, query and return as json

So I've tried changing all the POSTs to GETs but it did not work. Is there a concept I'm not understanding?

I think it could be something to do with the $('form#submit').submit(function (e) and preventDefault() functions. However preventDefault is required for stopping the page reloading.

meiryo
  • 11,157
  • 14
  • 47
  • 52
  • To really protect your site from SQL injection, use PDO (or mysqli) and prepare your queries with placeholders. `mysql` has been deprecated. – elclanrs Apr 16 '13 at 03:57
  • Have you used firebug or a equivalent application to debug? – Daryl Gill Apr 16 '13 at 04:10
  • @DarylGill I'm using Chrome's native developer tools. Since I haven't gotten a response: what I did was correct? – meiryo Apr 16 '13 at 04:11
  • Try using `data: { search: $('input[name=search]').val() },`. Even if this doesn't make GET work, it is a cleaner way to do it. – John S Apr 16 '13 at 04:35
  • possible duplicate of [How does GitHub change the URL but not the reload?](http://stackoverflow.com/questions/4973777/how-does-github-change-the-url-but-not-the-reload) – Quentin Apr 16 '13 at 05:11
  • @Quentin this looks like a HTML5 feature, unfortunately. – meiryo Apr 16 '13 at 05:25

2 Answers2

1
<input type="text" name="search" id="search"/>

AND

$('form#submit').submit(function (e) {
e.preventDefault();
var search = $('#search').val();
$.ajax({
        type: 'POST',
        url: 'results.php',
        data: {search:search},
        dataType: 'json',
        success: function(data) {
            //inject some html into page
        }
    });
 }
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
Amir
  • 4,089
  • 4
  • 16
  • 28
  • There's a problem here: queries containing space will return as `Gardening%20Tools` when I output search to console. – meiryo Apr 16 '13 at 05:15
  • For some reason the question was encoding the data as a URI twice, once with jQuery and one before passing the data to jQuery. – Quentin Apr 16 '13 at 05:21
  • These solutions *almost work*. The URL still remains the same @Amir – meiryo Apr 16 '13 at 10:23
-1

Let me take a very simple example.

The form:- Action and Method are not required here for using AJAX

 <form id="form1">
       <input type="text" class='search' name="search"/>
       <button type="button" onclick="funcAjax()">Load Results</button>
 </form>

jQuery:- here we will define the function "funcAjax()".

xmlhttp.responseText is the value returned from your php page

function funcAjax()
{
    //value to be searched
    var searchVal= $('.search').val();
    var xmlhttp;
    if (window.XMLHttpRequest){
        // code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();
    }
    else{
        // code for IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }

    xmlhttp.onreadystatechange=function(){
        if (xmlhttp.readyState==4 && xmlhttp.status==200){
             document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
             //xmlhttp.responseText is the value returned from your php page
        }
    }

    xmlhttp.open("GET","results.php?q="+searchVal,true);
    xmlhttp.send();
}

results.php:

$query = $_GET['q'];
//rest follow your code