I want to pass multiple variables city1
and area1
(JavaScript variables) in a URL to a PHP page I but got stuck in on the part shown below. What am I doing wrong?
$("#list").load("selectcity.php?city1="+city1&"area1="+area1);
$.ajaxSetup({ cache: false });
The &
character should be inside quotes and not outside quotes. This is the corrected code :
$("#list").load("selectcity.php?city1="+city1+"&area1="+area1);
$.ajaxSetup({ cache: false });
GET parameters are separated by the character &
. You are passing 2 parameters to the file separated by &
. The ?
sign in the URL indicates that the next characters coming after it is the GET
parameters.
Or you can use $.get
which is very easy to set up and works fine like $.load
:
$.get("selectcity.php", {"city1": city1, "area1": area1}, function(response){
$("#list").html(response);
});
It is better not to form query string manually, since you will constantly encounter not-so-notable bugs. jQuery offers a way to construct query string automatically from object:
var ajaxData = {
city1: city1,
area1: area1
};
$.get('selectcity.php', ajaxData, function(data) {
$('#list').html(data);
});
It requires slightly more code but is guaranteed to be safe. There is also a .load(url, data)
shortcut, but it will send a POST request instead of GET request, and that's probably not what you want.
Also, i'm not sure jQuery will automatically urlencode manually-formed query strings, so string concatenation approach may introduce even more bugs.