Forum Moderators: open

Message Too Old, No Replies

jQuery, passing a variable to PHP through .load

         

csdude55

11:01 am on Feb 7, 2016 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



I'm new to jQuery, and this is my first real foray in to building a function. I'm replacing my current XMLHttpRequest function with what I hope will be a plug-n-play jQuery function.

Here's where I am:


jQuery.fn.ajax = function(whichID, url, query_string) {
if (url) {
$(document).ready(function() {
$('#' + whichID).load(url, query_string);
});
}
}


That's not the whole function, of course, just the relevant parts.

In practice, I have a button that is clicked in the HTML, which then loads the PHP script ("url") that has its own echo. That echo replaces the "whichID" tag in the HTML.

The issue I'm having is when I try to send PHP variables to url manually, they get lost. In the old XMLHttpRequest script, I just passed them like a regular GET:

whatever.php?var1=this&var2=that

Which I tried, but none came through. I understood the documentation to say that you could just place the query string in the second parameter, like:

load("whatever.php", "var1=this&var2=that");

but still, nothing comes through.

So how do I send these variables to the PHP script correctly?

Andy Langton

5:54 pm on Feb 7, 2016 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



There's no reason why you can't pass values as before:

load('whatever.php?var1=this&var2=that')


This should pass GET values to whatever.php. You might try adding this to whatever.php just to check it isn't a problem with your PHP script:

var_dump($_GET);


You can check on the various requests and responses using the dev console in your browser (usually accessible by pressing F12).

The other (and slightly tidier) way to do it is to use jQuery.param [api.jquery.com]:

$('#' + whichID).load(
"whatever.html?" + $.param({
var1: "this",
var2: "that"})
);

csdude55

4:01 am on Feb 8, 2016 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Thanks for the help, Andy! The $.param() option helps.

When I do this, I get the expected alert, but the PHP doesn't load:


jQuery.fn.ajax = function(whichID, url) {
$(document).ready(function() {
alert(url);
$('#' + whichID).load(url);
});
}


I couldn't tell you why; there aren't any special characters in what I'm sending or anything. The error is definitely in JS, though.

This variation kind of worked:


jQuery.fn.ajax = function(whichID, url) {
var query_string = this_url.substring(url.indexOf('?') + 1);

if (query_string) {
var qsStr = '';
var qsArr = query_string.split("&");

for (i = 0; i < qsArr.length; i++) {
var qs_data = qsArr[i].split('=');
qsStr += qs_data[0] + ': "' + qs_data[1] + '", ';
}

qsStr = qsStr.replace(/([,\s]+$)/, '');
}

$(document).ready(function() {
$('#' + whichID).load(
this_url + '?' + $.param({ qsStr })
);
});
}


The parameters aren't sent as individual $_GET params, though. Instead, var_dump($_GET) gave me:

array(1) { ["qsStr"]=> string(83) "?var1: "this", var2: "that"" }

Seeing how those params came through, I realized that I could just send the query string through like this:


jQuery.fn.ajax = function(whichID, url) {

// have to remove the ? manually or it thinks "var1" is "?var1"
var this_url = url.substr(0, url.indexOf('?'));
var query_string = url.substring(url.indexOf('?') + 1);

$(document).ready(function() {
$('#' + whichID).load(
this_url + '?' + $.param({ query_string })
);
});
}


And then in the loaded PHP:

parse_str($_GET['query_string']);

That kind of works, but it's still not perfect because it means I have to modify all of my PHP scripts that are loaded via ajax. It would be a lot better if I could figure out how to get those parameters to show up in the loaded PHP's $_SERVER['QUERY_STRING'], which is how everything came through when I used XMLHttpRequest.

Andy Langton

10:42 am on Feb 8, 2016 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Can I ask how you're troubleshooting this? I would be looking at the network section of the browser developer console to check that the request for whatever.html is sent correctly, and what the response is from that script if the request is correct. You can then know at which point your code is not working as expected.

csdude55

4:38 am on Feb 9, 2016 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



I'm just using Chrome's Developer Tools. I just double checked, and using the original script (without $.param) I don't have any errors in the console when I click, but nothing opens, either.

Maybe there's a minor typo somewhere that I'm overlooking? I really don't know. Here's my exact script, though; the only thing changed is that I removed my domain, because I don't think that's allowed on this site.


<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquerymobile/1.4.5/jquery.mobile.min.js"></script>

<script>
jQuery.fn.ajax = function(whichID, url, refreshRate, noh) {
if (url) {
// Variable "noh" lets the system load from cache; this forces a fresh page
if (!noh) url += (new Date).getTime();

var this_url = url.substr(0, url.indexOf('?'));
var query_string = url.substring(url.indexOf('?') + 1);

$(document).ready(function() {
//// This includes the query_string, and doesn't work
url

//// This separates the query_string, and works
// this_url + '?' + $.param({ query_string })
});

//// Untested
// if (refreshRate)
// setTimeout("$().ajax('" + whichID + "', '" + url + "', " + refreshRate + ")", refreshRate);
}

else document.getElementById(whichID).style.display = 'none';
}
</script>

<div class="left d_main_con"
onMouseOver="this.style.cursor= 'pointer';"
onClick="
toggle(event, 'county_box');
$().ajax('county_box', 'http://www.example.com/includes/whatever.php?default=example&select=example&ddID=county_menu&dd_more=margin-left: 50px', '', '1');">
<span style="margin-right: 3px">EDITION: Site Name</span>
<span class="d_main_arrow">&#9660;</span>

<div id="county_box" class="abs" style="display: none"></div>
</div>