I am trying to insert data from my select
box option
s into my database table. My database table fields are id_country
and country_name
.
The database field id_country
is populated from the select
option
value and the country_name
is from the corresponding option
text. the code is like this..
<select id="id_country" name="id_country">
<option value="17" >USA</option>
<option value="16" >Canada</option>
<option value="7" >France</option>
</select>
<script>
$(document).ready(function(){
var data=new Array();
$('#id_country').find('option').each(function() {
var id=$(this).val();
data[id]=$(this).text();
});
$('#btn_insert').click(function(){
$.ajax({
type: "POST",
url: "ajax.php",
data: data,
success: function(response){
alert(response);
}
});
});
});
</script>
The server side script:
<?php
//echo $_POST['data'];
$arr=$_POST['data'];
foreach($arr as $key => $value){
$sql="INSERT INTO Country($key,$value)";
$query=mysql_query($sql);
if(mysql_num_rows($query)>0){
echo "success";
}
}
?>
I can't get $_post['data']
value. How do I get the Javascript Array in the PHP script?
Try as below:
First serialize your array and then pass to jquery ajax function.
data.serializeArray();
In PHP Script, at the beginning of file,
$arr = json_decode($_POST['data'], true);
There must be an data-member inside the data-object when you want to fetch all sended data using $_POST['data']
Change this:
data:data,
into
data:{'data':data}
when you want to post only the data of the selected option, you must build the data-object inside the click-handler, like this:
var data={'id_country':$('option:selected','#id_country').val(),
'country_name':$('option:selected','#id_country').text()};