0

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?';

?>

4
  • 3
    Does this look right to you? $p = json_decode(JSON); Commented Dec 10, 2013 at 19:34
  • Also, no need to put capital letters on JSON. Declare the variable like this: var json = JSON.stringify(values); Commented Dec 10, 2013 at 19:37
  • Thanks.. but still an empty text file. any other error? Commented Dec 10, 2013 at 19:37
  • Why are you passing an object to fwrite? Why decode the JSON, if you want to write it to a file? What do you expect test.txt to contain? Commented Dec 10, 2013 at 19:39

1 Answer 1

2

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.