Why Javascript array doesn't implode in php?

138 views Asked by At

I actually have this array var checked_rls= ['24','56'];

            var checked_rls = []
            $("input[name='chk_cont[]']:checked").each(function ()
            {
                checked_rls.push($(this).val());
            });

and then I tried to pass it using AJAX

  $.ajax(
            {
                type :"POST",
                url : "sale_ajax.php",
                data: 
                {
                    rls :  checked_rls,
                    rls_date : $("#rls_date").val()
                },
                success: function(msg)
                {
                    alert('saved successfully');

                },
                error: function()
                {
                    alert("Failure");
                }
            });

and then i received the array in sale_ajax.php file like this $cont = $_POST['rls'];

Now the problem is that I can run this array in a forEach function, but when I tried to implode this array into a string it only returns one value.

For e.g. in this scenario I passed 24,56 and when I tried to implode(",",$cont); it only returns the very first value, 24:

var_dump($cont) output is
array(2){[0]=>string(2) "24" [1]=>string(2) "56"} 

and the php code is:

if(isset($_POST['rls']))
    {
        $rls_date = $_POST['rls_date'];
        $cont = $_POST['rls'];
        $rls_cont_sold = implode(",",$cont);

         $rls_insert = mysql_query("INSERT INTO release_details (release_date, cont_sold_id) VALUES (STR_TO_DATE('$rls_date', '%d-%m-%Y'), '$rls_cont_sold')")or die(mysql_error());          
         $id = mysql_insert_id();

        foreach($cont as $val)
        {       
          $cont_sold_update = "UPDATE cont_sold SET release_details_id = '$id' WHERE cont_sold_id = '$val'";
          $insert = mysql_query($cont_sold_update)or die(mysql_error());         
        }
    }

and the var_dump($_POST) is

array(2){ 
["rls"]=>(array(2){[0]=>string(2) "24" [1]=>string(2) "56"})
["rls_date"]=>string(10) "10-04-2015"
}

What is actually happening in this condition? Thank you

2

There are 2 answers

2
Domain On BEST ANSWER

Put below code in click event of chk_count element:-

$("input[name='chk_cont[]']").click(function(){         
          var checked_rls = [];
            $("input[name='chk_cont[]']:checked").each(function ()
            {
                checked_rls.push($(this).val());
            });
});
1
Deepak Nirala On

Rather than passing passing an array why don't you pass a string itself, it will reduce your number of steps.

       var checked_rls = "";
        $("input[name='chk_cont[]']:checked").each(function ()
        {
            checked_rls += $(this).val()+",";
        });