I, too, was in a situation where I wanted to code using JSON, but only PHP v 5.1.6 was on the server. After several hours of trying, I found that all I had to do was just enable JSON.php from my PHP script and modify my AJAX Function a bit (originally obtained from the Internet - not my job).
Here are both files, I hope this will save someone from nerves.
java.js
var request; function runAjax (JSONString, phpScript, cfunc) { if (window.XMLHttpRequest) { request = new XMLHttpRequest(); } else if (window.ActiveXObject) { try { request = new ActiveXObject("Msxml2.XMLHTTP"); } catch(e) { try { request = new ActiveXObject("Microsoft.XMLHTTP"); } catch(e) { request = false; } } } request.onreadystatechange = cfunc; request.open("POST", phpScript); request.setRequestHeader("Content-type", "application/json", true); request.send(JSONString); } function smazVzor (id) { var JSONObject = new Object; JSONObject.id = id; JSONString = JSON.stringify(JSONObject); runAjax(JSONString, "./ajax/smaz_vzor.php", function () { if (request.readyState == 4) { var JSONObject = JSON.parse(request.responseText); alert(JSONObject.zprava); if (JSONObject.kod == 1) document.location.href = "./index.php"; } }); }
smaz_vzor.php
<?php require("../../include/dbconnect.php"); // just some commands for MySQL require('../../include/JSON/JSON.php'); // <-- THIS IS IMPORTANT $json = new Services_JSON(); // create a new instance of Services_JSON class $str_json = file_get_contents('php://input'); // read fiel send by POST method as text $decoded = $json->decode($str_json); // decode JSON string to PHP object $sql = "DELETE FROM Obory_vzory WHERE id = '$decoded->id'"; $response = array(); // create response array if (!mysql_query($sql, $pripojeni)) { $response['kod'] = 0; $response['zprava'] = "Something got wrong.\nError: ".mysql_error(); } else { $response['kod'] = 1; $response['zprava'] = "Operation successful."; } $encoded = $json->encode($response); // encode array $json to JSON string die($encoded); // send response back to java and end script execution ?>
source share