1

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?

2
  • 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 Commented Sep 16, 2012 at 8:39
  • 1
    Have you outputed $_POST yet as suggested by @MatthewBlancarte, this will let you know what you ACTUALLY have. Commented Sep 16, 2012 at 8:48

2 Answers 2

2

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);
Sign up to request clarification or add additional context in comments.

Comments

1

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()};

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.