Sending JSON (jQuery) to PHP and decoding it

I cannot understand for life what I am doing wrong. It seems like it should be simple, because I cannot find anyone else with this problem, but I cannot understand, send the main data via javascript (jQuery) to PHP and decode it. For simplicity, this is what I have:

JAVASCRIPT

var json_data = { "name" : "john doe" };

$.ajax({
    type: "POST",
    url: "../bin/process.php",
    dataType: "json",
    data: json_data
    });

and my php file

$arr = json_decode("json_data", true);

$fp = fopen('data.txt', "w");
fwrite($fp, $arr['name']);
fclose($fp);

The file I am writing contains nothing. If I do:

fwrite($fp, 'test');

I get a file with the word test in it, but no matter what I do, I do not receive the json data that I sent.

Can anyone share a detailed example of AZ. Thanks for any help.

+3
source share
2 answers

ajax, jQuery, "name" "john doe", . , :

data: { parameters: json_data }

PHP $_POST. , :

$name = $_POST['name'];

, , :

$params = $_POST['parameters'];

json_decode(), , $_POST, PHP-.

, json, PHP, , jQuery "" javascript .

, javascript JSON, , - :

// JS

var person = "{ name: 'John Doe' }"; // notice the double quotes here, this is a string, and not an object
$.ajax({
    type: "POST",
    url: "../bin/process.php",
    dataType: "json",
    data: { json: person }
    });

// PHP

$json = $_POST['json']; // $json is a string
$person = json_decode($json); // $person is an array with a key 'name'
+5

jQuery JSON, ( dataType ). json2.js .

+1

Source: https://habr.com/ru/post/1744704/


All Articles