Frank
Frank

Reputation: 509

JSON doesnt post data

I have a question about json. First I made this jquery code±

    <script>
        $('#buy').click(function(){
        var items=[]; 
            var item={
                    firstname:'blabla'                  
                };
                items.push(item);           
                var sortorder={ items: items };
           $.post('post_form.php', 'data='+$.toJSON(sortorder)+'', function(response){      
              alert(response);          
           });                  
    });
   </script>

If you can see the data will be send to post_form.php but doesn't reach it I think, this the code:

 if(!$_POST["data"]){
    echo "Invalid data";
    exit;
}   
include('config.php');
$data=json_decode($_POST["data"]);

foreach($data->items as $item)   
{  
    $query = "insert into customer (id,firstname) VALUES ('','".mysql_escape_string($item->firstname)."')";
     mysql_query($query) or die (mysql_error());
     echo 'succes';
}
 echo 'fail';

Everytime I get the fail echo very strange, I used it for another script and worked very well. This script doesn't receive the data info, how to fix?

Regards and thanks,

Frank

Upvotes: 0

Views: 325

Answers (1)

Dim_K
Dim_K

Reputation: 571

Try to use

   $.post('post_form.php', { "data" : $.toJSON(sortorder) }, function(response){      
      alert(response);          
   }); 

post variables will be escaped in this way

Upvotes: 3

Related Questions