Jean Ouédraogo Jean Ouédraogo - 5 months ago 11
Ajax Question

PHP can't receive data sent using jquery . lead to undifined variable on php file

I'm trying to send data from a HTML

select
to a PHP file using jQuery. Unfortunately it does not work. I have looked at all the solutions proposed here and it's still not working. Here is the code:

<select id="city" name="city" >
<optgroup label="Popular Cities">
<option selected style="display:none;color:#eee;">Entire country</option>
<option value="city1">city 1</option>
<option value="city2">city 2</option>
<option value="city3">city3</option>
<option value="city4">city4</option>
<option value="city5">city5</option>
</select>


$("#city").change(function() {
$.ajax({
url: 'post.php',
type: 'POST',
data: { city: $(this).val() },
success: function(data) {
alert(data);
window.location.replace("post.php");
window.location.reload("post.php");
}
});
});


$city = isset($_POST['city']) ? $_POST['city'] : false;
echo "".$city."";


The
alert()
works but I still have no data received in
post.php
. I have tried with the code below as well but still can't have it.

$.post("post.php", { city: $(this).value }, function(data) {
alert(data);
window.location.reload("post.php");
window.location.replace("post.php");
});


Any help?

Answer

You need to use form for this as said in comments

<form action="post.php" method="get" id="frmForm">
 <select id="city" name="city" >
<optgroup label="Popular Cities">
    <option selected style="display:none;color:#eee;">Entire   country</option>
    <option value="city1">city 1</option>
    <option value="city2">city 2</option>
    <option value="city3">city3</option>
    <option value="city4">city4</option>
    <option value="city5">city5</option>
 </select>
</form>

Then use jquery to submit form on city selection

$(document).ready(function() {

$("#city").change(function() {
$('#frmForm').submit();    

});

Then you can find city name with $_GET['city'];