简体   繁体   中英

how to send json to php file to save on server

Im developing a javascript/php/ajax application and have stumbled across some problems.

Im confident at javascript and ajax but my php is a little rusty.

My aim is to get a json file from the server, modify it using javascript, and then save this modified json back to the server.

After some research it was obvious that the modified json file must be sent to a php file, this php file will then do the saving.

HOW do i send a json string from javascript to php? OR how do I get the php file to pick up the json variable from the javascript?

im assuming the php will be something like:

<?php 
    $json = $_POST["something"];
?>

but how do i send or "post" the javascript variable to the php file?

I was thinking about creating a hidden html form, setting a hidden textbox to the json string, then posting the html form

But surely there must be a way without including the html middle man?

Im looking for answer WITHOUT jQuery. Seeing as this is an application i would like a relieve the dependancy of jQuery.

The only, as far as I know, proper way to do this is sending data to a file through Ajax, then attaching some POST or GET data.

Example: You could send the data in the url as GET: http://example.com/foo.php?myvalue=cake

And then in the php you'd say:

<?php
$yourvalue = $_GET['myvalue'];
// Some code to save it to the database/server
?>

You would need to create a XMLHttp-Request like this:

xmlhttp.open( "POST", url, false );
xmlhttp.setRequestHeader(
    'Content-Type',
    'application/x-www-form-urlencoded; charset=UTF-8'
);
xmlhttp.send("data=yaystuff!")

So you can send it. In PHP just get the $_POST['data'] variable and do some json_decode() on it, if you send JSON :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM