Passing JSON data from JavaScript using Ajax to PHP -
i have following js:
window.onload = function() { 'use strict'; var ajax = getxmlhttprequestobject(); ajax.onreadystatechange = function() { if ( ajax.readystate == 4 ) { if ( (ajax.status >= 200 && ajax.status < 300) || (ajax.status == 304) ) { var data = json.parse(ajax.responsetext); var file = ''; file += 'original: ' + data['org'].file + '<br>'; file += 'processed: ' + data['pre'].file + '<br>'; document.getelementbyid('output').innerhtml = file; } else { document.getelementbyid('output').innerhtml = 'error: ' + ajax.statustext; } } }; document.getelementbyid('btn').onclick = function() { ajax.open('post', 'resources/test.json', true); ajax.setrequestheader('content-type', 'application/json'); ajax.send(null); }; };
i pass data
data['org'].file
and
data['pre'].file
to php , have echo out value using post method. please no jquery solutions needs strictly javascript.
something this:
<?php $data = $_post['the_data']; echo $data; ?>
here json test.json:
{ "org": { "file": "css/original.css" }, "pre": { "file": "css/preprocessed.css" } }
if want php script echo json data, it's simple this:
<? $json = file_get_contents('php://input'); //... echo $json; ?>
to post javascript, reccomend reading this. there's reason many people use jquery...
Comments
Post a Comment