Skip to content Skip to sidebar Skip to footer

JQuery/PHP Dynamic Dropdown Issue

I've been building a script for dynamic dropdowns using PHP and JQuery and I'm having an issue with some of the data being sent from the form to be queried. Basically the user will

Solution 1:

Your instincts were right, the problem is with non-escaped characters (url encoding). For debugging AJAX calls you should use your browser's console (I highly recommend FireBug, but to each his own).

Before you send the parameters via AJAX, you have to encode them using encodeURI(). For example:

$("#series").change(function() {
    var val = document.getElementById('series').value;
    // $("#series").val() == document.getElementById('series').value
    // but the latter is faster!
    $("#range").load(encodeURI("findbackend.php?series=" + val));
});

You would also have to adjust your other .change function calls accordingly. Since the data your PHP script will receive has been encoded, you need to decode it using urldecode(). Example:

$series = mysql_real_escape_string(urldecode($_GET['series']));

This should work just fine.

On a side note, you are using a deprecated MySQL API, you should use MySQLi or PDO. Also, your jQuery calls could do with some caching (you create the $("#series") object three separate times).


Solution 2:

the easy way to use ajax so you need two php pages and one js at least
the first php will have the first dropdown and then send it`s value to the second php by ajax it's simply example

first php code like this

<!DOCTYPE html>
<html>
<head>
<title>Hello!</title>
<script type="text/javascript" src="jquery-2.0.3.min.js"></script>
<script type="text/javascript" src="dropdown.js"></script>
</head>
<body>
<select name="first" id="first">
<option value="1">a</option>
<option value="2">b</option>
<option value="3">c</option>
</select>
<div id="second"></div>
</body>
</html>

dropdown2.php code is

<?php
if(isset($_GET['first'])){
  $first=$_GET['first'];
echo"
<select name='second' id='secondselect'>
<option value='4'>$first a</option>
<option value='5'>$first b</option>
<option value='6'>$first c</option>
</select>
";
}
?>

and dropdown.js

$(document).ready(function(){
$("#first").change(function(){
str=$("#first").val();
xmlhttp=new XMLHttpRequest();
xmlhttp.open("GET","dropdown2.php?first="+str,false);
xmlhttp.send();
document.getElementById("second").innerHTML=xmlhttp.responseText;
});
});

Post a Comment for "JQuery/PHP Dynamic Dropdown Issue"