Peanut
Peanut

Reputation: 3295

Javascript load() with data, how to grab params in PHP?

Ok so this is my following javascript code:

    $( '#listings' ).load( 'ajax/listingFind.php', {
        id: id, 
        name: name,
        logo: encodeURIComponent(logo),
        address: address,
        city: city,
        state: state,
        zip: zip,
        phone: phone,
        email: email,
        web_link: encodeURIComponent(web_link),
        distance: distance
      } );

All of the id, name, etc has values assigned previously in javascript. However, in listingFind.php, how do I grab these data values that are being passed in? I load the file into the div and echoed out the entire url and it doesn't seem as if the data is getting passed into the url. Whenever I manually type it like so:

$( '#listings' ).load( 'ajax/listingFind.php?id=' + id + '&name=' + name + '&logo=' + encodeURIComponent(logo) + '&address=' + address + 
          '&city=' + city + '&state=' + state + '&zip=' + zip + '&phone=' + phone + '&email=' + email + '&web_link=' + encodeURIComponent(web_link) + 
          '&distance=' + distance );

etc etc etc... It throws an error saying :

Uncaught Error: Syntax error, unrecognized expression: Example Inc&logo=http%3A%2F%2Fstuff.blah.localhost%2Flisting%2Flogo%2glarb.png&address=123 Any Street N&city=Anytown&state=OH&zip=44123&phone=3305551234&[email protected]&web_link=http%3A%2F%2Fexample.com%2F&distance=16.85833142631359

Upvotes: 0

Views: 33

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074088

You'll find the data in $_POST. From the load documentation:

Request Method

The POST method is used if data is provided as an object; otherwise, GET is assumed.

Since you're providing the data as an object, jQuery is using POST.

Whenever I manually type it like so...It throws an error

Yes. If you provide a string, you're expected to provide a valid query string, but the string you provided is not a valid query string. In general, stick to the object notation, but if you need to build a string like that, use encodeURIComponent to ensure that the values are encoded correctly.

'ajax/listingFind.php?id=' + encodeURIComponennt(id)

Technically, both the key and value must be encoded:

'ajax/listingFind.php?' + encodeURIComponent('id') + '=' + encodeURIComponennt(id)

...but if your keys consist solely of the letters a-z (lower or upper case), the encoded form is exactly the same as the raw form, so you can skip it.

Upvotes: 2

Related Questions