user3070028
user3070028

Reputation: 35

Send javascript array to php using json

This question might be repetitive but i got confused reading all posts relating to this.(sincere apologies!) Basically, I want to send a javascript array to a php file and inturn write the array to a text file . I learnt the best way to go about it is using JSON and AJAX. My code is displays "success" for the ajax part, and also creates a file (php code),but an empty text file.

 $('#tabletomodify').on('change','.street', 
        function (event) 
        {
                event.preventDefault();             
            var row=( $(this).closest('tr').prop('rowIndex') );
            var optionSelected = $("option:selected", this);
                var valueSelected = this.value;
            var ideSelected= this.id;               
            var values = [valueSelected];
            for ($i=3;$i<row;$i++)
            {                   
                var dv="selectstate"+$i;
                var dv1=document.getElementById(dv).value;
                var sl="selectstreet"+$i;
                var sl1=document.getElementById(sl).value;
                var po="selectbuilding"+$i;
                var po1=document.getElementById(po).value;
                var concat=dv1+sl1+po1;
                values.push(concat);                    
            }               
            JSON = JSON.stringify(values);
            $.ajax({
             url: "get_buildings.php",
                 type: 'POST',               
                 data:  JSON ,
                 success: function(){
                alert("Success!")
                }
            });

PHP Code:-

<?php
$json = $_POST['JSON'];
$p = json_decode(JSON);

$file = fopen('test.txt','w+');
fwrite($file, $p);
fclose($file);

echo 'success?';

?>

Upvotes: 0

Views: 730

Answers (1)

Marc B
Marc B

Reputation: 360672

Two flaws:

a) You're not sending your data correctly - it's lacking a field name:

data: {data: JSON}
       ^^^^---this will be the key in PHP's $_POSt

b) You're using invalid constants in PHP and not even decoding what MIGHT have been the passed in data. You should have:

$p = json_decode($_POST['data']);
                         ^^^^--matching what you have in the `data` field in Javascript.

Upvotes: 2

Related Questions