Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I am trying to insert data from my select box options 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?

share|improve this question
1  
Don't use mysql_* functions. They're deprecated in all but name, old, insecure and are meant for interfacing with versions of mysql that have been obsolete for years now. Consider switching to mysqli or PDO – GordonM Sep 16 '12 at 8:39
2  
send json instead of array – NullPoiиteя Sep 16 '12 at 8:41
2  
var_dump($_POST); – Matthew Blancarte Sep 16 '12 at 8:44
1  
Have you outputed $_POST yet as suggested by @MatthewBlancarte, this will let you know what you ACTUALLY have. – Toby Allen Sep 16 '12 at 8:48

2 Answers

up vote 2 down vote accepted

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);
share|improve this answer

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()};
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.