Decoding a JSON Array From Ajax Request - php

I finally succeeded in using Ajax to get SOMETHING sent from one page to another! What I'm trying to do is pass an array from a PHP file to a Javascript file, and the Javascript file is receiving this in this.responseText:
<html>
<head>
<script type="text/javascript">
var jsonArray = ["chickens","horses","cows","werewolves","zombies","vampires","phantoms","U.S. Congressmen","performance artists","pieces of fencepost","barnhouses","robots","cyborgs"]
</script>
</head>
</html>
I tried running eval() and alerting the result, but no result appears. How do I successfully extract the array from this.responseText?
Edit Here is my function thus far:
/*
* Function: selectVictim
* Called from function laserOn()
*
* Selects a random victim from a list of victims
*
* #return String: victim
*/
function selectVictim()
{
var params = "url=queenofsheep.com/Sheep/victims.php";
var request = new ajaxRequest();
request.open("POST", "victims.php", true);
request.setRequestHeader("Content-Type",
"application/x-www-form-urlencoded");
request.setRequestHeader("Content-Length", params.length);
request.setRequestHeader("Connection", "close");
request.onreadystatechange = function ()
{
if (this.readyState == 4)
{
if (this.status == 200)
{
if (this.responseText != null )
{
var vicArray = eval('('+this.responseText+')');
var numVic = Math.floor(Math.random() * (vicArray - 1));
alert(vicArray);
}
else alert("Ajax error: No data received");
}
else alert("Ajax Error: " + this.statusText);
}
}
request.send(params);
}
Second Edit The file containing the array (in PHP) is as follows:
<html>
<head>
<?php
$victims = array(
// Animals
"chickens",
"horses",
"cows",
// Supernatural
"werewolves",
"zombies",
"vampires",
"phantoms",
// Human
"U.S. Congressmen",
"performance artists",
// Inanimate, non-mechanical
"pieces of fencepost",
"barnhouses",
// Mechanical
"robots",
"cyborgs"
);
?>
<script type="text/javascript">
var jsonArray = <?php echo json_encode($victims); ?>
</script>
</head>
</html>

If your php page is returning all the text that you reported (with <html> etc...) then your output is not a JSON object, but an html page. Your response should contain only your serialized JSON object (and the proper http response headers)...
Once you have 'cleaned' your output you can use JSON2 library to parse your object:
http://www.json.org/js.html
var myObject = JSON.parse(myJSONtext);

That does not look like a proper JSON response from the server, because it contains HTML code and then a chunk of javascript. The response should contain only javascript code containing data, like
var data = ["chickens","horses","cows","werewolves","zombies"]";
You can then eval() the string and it will work.
As said above, eval() might be unsafe, so, if using jQuery, you can use the $.parseJSON function which is safe.
To return the JSON correctly, don't output HTML at all in the page, just do something like
<?php
$victims = ...; // fill array
echo json_encode($victims);
?>

You can use the library on json.org or use eval("(" + this.responseText + ")");
Generally you want to use a library to parse the JSON string instead of eval because eval is generally unsafe.

Related

Generate json with url built from form

I'm trying to create a form that is capable of generating multiple urls, depending on the input by the user. The created url has a json extension. A php file is used to get the contents of that url. This php file has to have the same contents as the inputted url has. This php file is used as input for a javascript/jquery file.
In this file I'm trying to convert the json code to an html table. This is done by an http_request. The table has to be outputted in a div on the html page. However my code doesn't work due to errors I can't find. I've already looked at simular questions at stackoverflow and google, but could find the fix that made my code working.
I'm applying this code to spotify lists. This is the code I already have:
html:
<script type="text/javascript" src="spotify.js"></script>
<form id="spotifyform" action="spotifylist.php" method="post">
<select id="country" name="country">
<option value="GB">UK</option>
<option value="US">USA</option>
</select>
<select id="interval" name="interval">
<option value="daily">Daglijst</option>
<option value="weekly">Weeklijst</option>
</select>
<select id="chart" name="chart">
<option value="most_streamed">Meest gestreamd</option>
<option value="most_viral">Meest gedeeld</option>
</select>
<input type="submit" name="formSubmit" value="Submit"/>
</form>
<div id="spotifylist"></div>
spotify.js:
function loadJSON()
{
var http_request = new XMLHttpRequest();
try{
// Opera 8.0+, Firefox, Chrome, Safari
http_request = new XMLHttpRequest();
}catch (e){
// Internet Explorer Browsers
try{
http_request = new ActiveXObject("Msxml2.XMLHTTP");
}catch (e) {
try{
http_request = new ActiveXObject("Microsoft.XMLHTTP");
}catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
http_request.open("GET", "spotifylist.php", true);
http_request.send();
http_request.onreadystatechange = function(){
if (http_request.readyState == 4 )
{
// Javascript function JSON.parse to parse JSON data
var jsonObj = JSON.parse(http_request.responseText);
// jsonObj variable now contains the data structure and can
// be accessed as jsonObj.artist_name and jsonObj.track_name.
HTML = "<table id='chart'> <thead><tr id='row2'><th id='dw'></th><th id='song'>Artiest</th><th id='song'>Titel</th></tr></thead><tbody>";
var x=jsonObj.tracks;
for (i=0;i<x.length;i++)
{
HTML += "<tr id='row1'><td id='dw'>";
HTML += i+1;
HTML += "</td><td id='song'>";
HTML += x[i].artist_name;
HTML += "</td><td id='song'>";
HTML += x[i].track_name;
HTML += "</td></tr>";
}
HTML += "</tbody></table>";
document.getElementById("spotifylist").innerHTML = HTML;
}
}
}
$("#spotifyform").submit(function(){
loadJSON();
return false;
});
spotifylist.php
<?php
if($_POST['formSubmit'] == "Submit")
{
$chart = $_POST['chart'];
$country = $_POST['country'];
$interval = $_POST['interval'];
}
$data_file="http://charts.spotify.com/api/tracks/".$chart."/".$country."/".$interval."/latest";
$url = file_get_contents ($data_file);
echo $url;
?>
What currently goes wrong is that the php file is loaded when I press the submit button. This file contains the right json information. However this json isn't converted to a html table.
I would really appreciate it, if anybody could help me fix this problem
If you want the spotifylist div to load in the data when you press submit, you have to prevent the page from redirecting.
Make the form action:
<form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF'])?>
And if possible, your input values (if you have any within the form tags):
"<?php echo $_POST['value']?>"
If you can, place your HTML code within a PHP file which executes everything from spotifylist.php.
There are a couple of problems in my guess.
You send your Form to the spotifylist.php which grabs an file and sends something back to the html. Probably JSON but where did you handle that data?
Maybe some Javascript which does something with that "string" that your php sends back?
And your loadJSON sends (whenever) a GET Request to the same php but without parameters or something.
So your php run into an error because there obviously no POST variables set, so your variables inside your if condition will never set ergo your data which comes back again?!? with errors
You should first get clear which technique you want to use.
It seems to me as you would take a little of both.
There are multiple ways to get information from an external server:
httprequest - not recommend, because of bad user experience.
file_get_contents - usually easy, but in this case it requires a lot of data handling. Php works server-side and javascript works client-side. It requires a lot more work to let these two work together.
$.ajax - in this case the best solution, because it doesn't require any php and $.ajax is able to directly parse the json data. Because the data is requested from an external site, you have to change the datatype to jsonp and perform a callback function.
It is very easy to transfer the data from the form to javascript:
// Automatically call this function when the page loads.
window.onload = function loadJSON()
{
// The HTML input of the form that is the input of this javascript document
var country2 = document.getElementById("country");
var chart2 = document.getElementById("chart");
var interval2 = document.getElementById("interval");
Build the url with the selected parameters on submit:
// Call the function when the form is submitted
$("#spotifyform").submit(function(e)
{
e.preventDefault(); // to prevent the page from reloading
// Save the choice of the <select> country in a variable named country2
var country = country2.options[country2.selectedIndex].value;
var chart = chart2.options[chart2.selectedIndex].value;
var interval = interval2.options[interval2.selectedIndex].value;
var url = "http://charts.spotify.com/api/tracks/" + chart + "/" + country + "/" + interval + "/latest"; // build url
Then get the right data and parse it directly with the json native parser.
// Get the data from the site and save this into the variable 'json'
$.ajax
({
'url': url + '?callback=?', // ?callback=? lets the server generate a function name, the call can be handled in the success parameter
'dataType': 'jsonp', // Cross site request via jsonp
'error': function(xhr, status, error){ alert(error.message); },
'success': jsonParser // call function
}); // $.ajax
}); // $("#spotifyform").submit(function(e)
} // window.onload = function loadJSON()
Then do with the data whatever you want. You don't need to do an httprequest and you don't have to parse the data anymore.
function jsonParser(json)
{
HTML = "<table id='chart'> <thead><tr id='row2'><th id='dw'></th><th id='song'>Artiest</th><th id='song'>Titel</th></tr></thead><tbody>";
var x=json.tracks;
for (i=0;i<x.length;i++)
{
HTML += "<tr id='row1'><td id='dw'>";
HTML += i+1;
HTML += "</td><td id='song'>";
HTML += x[i].artist_name;
HTML += "</td><td id='song'>";
HTML += x[i].track_name;
HTML += "</td></tr>";
}
HTML += "</tbody></table>";
document.getElementById("spotifylist").innerHTML = HTML;
} // function jsonParser(json)

JavaScript to Pass variable and retrieve output from PHP page

Trying to pass a variable to a PHP file then get the output of that file.
Page1.html:
<h2 id="test"></h2>
<script>
var data2;
$.post('textandemail.php',{ txt: "John", email: "test#gmail.com" },
function(data) {
data2 = data;});
document.getElementById("test").innerHTML = data2;
</script>
textandemail.php:
$variable = $_POST["txt"];
$variable2 = $_POST["email"];
echo $variable;
echo $variable2;
Hopefully this describes the desired idea. I will be doing much more in the PHP file but in the end echoing out a response that I want the JavaScript to read and implement into the html page.
The $.post() function is asynchronous. It finishes some time LATER. You need to put the assignment of the results from that function into the success handler, not after the function itself because as you have it now, the line document.getElementById("test").innerHTML = data2; is occurring BEFORE the ajax function has finished and thus it won't work.
This is how you can do it:
<h2 id="test"></h2>
<script>
$.post('textandemail.php',{ txt: "John", email: "test#gmail.com" },
function(data) {
// any code that uses the ajax results in data must be here
// in this function or called from within this function
document.getElementById("test").innerHTML = data;
}
);
</script>
Or, since you have jQuery, you can do it like this:
<h2 id="test"></h2>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
$.post('textandemail.php',{ txt: "John", email: "test#gmail.com" },
function(data) {
// any code that uses the ajax results in data must be here
// in this function or called from within this function
$("#test").html(data);
}
);
</script>
Your post call is asynchronous, you have access to the data2 variable only once the process is done, so you should do your ....innerHTML ... in the callback function, when the data is available, not before.
There are plenty of good examples of this on any js sites. On the jQuery doc you have a good example.
Since you are useing jQuery, you could replace your innerHTML call too.
you should use ajax function to make communication between php and javascript
function Ajax_Send(GP,URL,PARAMETERS,RESPONSEFUNCTION){
var xmlhttp
try{xmlhttp=new ActiveXObject("Msxml2.XMLHTTP")}
catch(e){
try{xmlhttp=new ActiveXObject("Microsoft.XMLHTTP")}
catch(e){
try{xmlhttp=new XMLHttpRequest()}
catch(e){
alert("Your Browser Does Not Support AJAX")}}}
err=""
if (GP==undefined) err="GP "
if (URL==undefined) err +="URL "
if (PARAMETERS==undefined) err+="PARAMETERS"
if (err!=""){alert("Missing Identifier(s)\n\n"+err);return false;}
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState == 4){
if (RESPONSEFUNCTION=="") return false;
eval(RESPONSEFUNCTION(xmlhttp.responseText))
}
}
if (GP=="GET"){
URL+="?"+PARAMETERS
xmlhttp.open("GET",URL,true)
xmlhttp.send(null)
}
if (GP="POST"){
PARAMETERS=encodeURI(PARAMETERS)
xmlhttp.open("POST",URL,true)
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
xmlhttp.setRequestHeader("Content-length",PARAMETERS.length)
xmlhttp.setRequestHeader("Connection", "close")
xmlhttp.send(PARAMETERS)
the call functions put it inside the javascript page
Ajax_Send("POST","users.php",data,e)
where data is the data you send to the php page and e is the function you pass the output of php page to it

Pass PHP value to javascript using Ajax

I have a php code that provides the database values. I need those values in the javascript variable.
Javascript Code
<script src="http://code.jquery.com/jquery-1.8.0.js"></script>
<script type="text/javascript">
function text() {
var textVal=$("#busqueda_de_producto").val();
$.ajax(
{
type:"POST",
url:"index.php", //here goes your php script file where you want to pass value
data: textVal,
success:function(response)
{
// JAVSCRIPT VARIABLE = varable from PHP file.
}
});
return false;
}
</script>
PHP FILE CODE:
<?php
$q11 = "select * from sp_documentocompra_detalle where dcd_codigo".$_GET['codigo'];
$res11 = mysql_query($q11);
$row11 = mysql_fetch_array($res11);
?>
Your returning data is in the response parameter. You have to echo your data in PHP to get the results
Using JSON format is convenient
because of its key-value nature.
Use json_encode to convert PHP array to JSON.
echo the json_encoded variable
you will be able to receive that JSON response data through $.ajax
JavaScipt/HTML:
<script src="http://code.jquery.com/jquery-1.8.0.js"></script>
<script type="text/javascript">
function text()
{
var textVal=$("#busqueda_de_producto").val();
$.post('index.php', { codigo:textVal }, function(response) {
$('#output').html(response.FIELDNAME);
}, 'json');
return false;
}
</script>
<span id="output"></span>
PHP:
$q11 = "select * from sp_documentocompra_detalle where dcd_codigo='".mysql_escape_string($_POST['codigo'])."'";
$res11 = mysql_query($q11);
$row11 = mysql_fetch_array($res11);
echo json_encode($row11);
You aren't echoing anything in your PHP script.
Try altering your PHP to this:
<?php
$q11 = "select * from sp_documentocompra_detalle where dcd_codigo".$_GET['codigo'];
$res11 = mysql_query($q11);
$row11 = mysql_fetch_array($res11);
echo $row11; //This sends the array to the Ajax call. Make sure to only send what you want.
?>
Then in your Ajax call you can alert this by writing alert(response) in your success handler.
Tips
Send your data to the server as a URL serialised string : request=foo&bar=4. You can also try JSON if you fancy it.
Don't use mysql_* PHP functions as they are being deprecated. Try a search for PHP Data Objects (PDO).
i see lots of things that needs to be corrected
the data in your ajax do it this way data: {'codigo':textVal}, since you are using $_GET['codigo'], which leads to the second correction, you used type:"POST" so you must also access the $_POST variable and not the $_GET variable and lastly the target of your ajax does not display / return anything you either echo it or echo json_encode() it
The best solution is to use
echo json_encode("YOUR ARRAY/VALUE TO BE USED");
and then parse JSON in the javascript code as
obj = JSON.parse(response);

Send JSON data from Javascript to PHP?

How can I send JSON data from Javascript in the browser, to a server and have PHP parse it there?
I've gotten lots of information here so I wanted to post a solution I discovered.
The problem: Getting JSON data from Javascript on the browser, to the server, and having PHP successfully parse it.
Environment: Javascript in a browser (Firefox) on Windows. LAMP server as remote server: PHP 5.3.2 on Ubuntu.
What works (version 1):
1) JSON is just text. Text in a certain format, but just a text string.
2) In Javascript, var str_json = JSON.stringify(myObject) gives me the JSON string.
3) I use the AJAX XMLHttpRequest object in Javascript to send data to the server:
request= new XMLHttpRequest()
request.open("POST", "JSON_Handler.php", true)
request.setRequestHeader("Content-type", "application/json")
request.send(str_json)
[... code to display response ...]
4) On the server, PHP code to read the JSON string:
$str_json = file_get_contents('php://input');
This reads the raw POST data. $str_json now contains the exact JSON string from the browser.
What works (version 2):
1) If I want to use the "application/x-www-form-urlencoded" request header, I need to create a standard POST string of "x=y&a=b[etc]" so that when PHP gets it, it can put it in the $_POST associative array. So, in Javascript in the browser:
var str_json = "json_string=" + (JSON.stringify(myObject))
PHP will now be able to populate the $_POST array when I send str_json via AJAX/XMLHttpRequest as in version 1 above. Displaying the contents of $_POST['json_string'] will display the JSON string. Using json_decode() on the $_POST array element with the json string will correctly decode that data and put it in an array/object.
The pitfall I ran into:
Initially, I tried to send the JSON string with the header of application/x-www-form-urlencoded and then tried to immediately read it out of the $_POST array in PHP. The $_POST array was always empty. That's because it is expecting data of the form yval=xval&[rinse_and_repeat]. It found no such data, only the JSON string, and it simply threw it away. I examined the request headers, and the POST data was being sent correctly.
Similarly, if I use the application/json header, I again cannot access the sent data via the $_POST array. If you want to use the application/json content-type header, then you must access the raw POST data in PHP, via php://input, not with $_POST.
References:
1) How to access POST data in PHP: How to access POST data in PHP?
2) Details on the application/json type, with some sample objects which can be converted to JSON strings and sent to the server: http://www.ietf.org/rfc/rfc4627.txt
Javascript file using jQuery (cleaner but library overhead):
$.ajax({
type: 'POST',
url: 'process.php',
data: {json: JSON.stringify(json_data)},
dataType: 'json'
});
PHP file (process.php):
directions = json_decode($_POST['json']);
var_dump(directions);
Note that if you use callback functions in your javascript:
$.ajax({
type: 'POST',
url: 'process.php',
data: {json: JSON.stringify(json_data)},
dataType: 'json'
})
.done( function( data ) {
console.log('done');
console.log(data);
})
.fail( function( data ) {
console.log('fail');
console.log(data);
});
You must, in your PHP file, return a JSON object (in javascript formatting), in order to get a 'done/success' outcome in your Javascript code. At a minimum return/print:
print('{}');
See Ajax request return 200 OK but error event is fired instead of success
Although for anything a bit more serious you should be sending back a proper header explicitly with the appropriate response code.
Simple example on JavaScript for HTML input-fields (sending to server JSON, parsing JSON in PHP and sending back to client) using AJAX:
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
</head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<body>
<div align="center">
<label for="LName">Last Name</label>
<input type="text" class="form-control" name="LName" id="LName" maxlength="15"
placeholder="Last name"/>
</div>
<br/>
<div align="center">
<label for="Age">Age</label>
<input type="text" class="form-control" name="Age" id="Age" maxlength="3"
placeholder="Age"/>
</div>
<br/>
<div align="center">
<button type="submit" name="submit_show" id="submit_show" value="show" onclick="actionSend()">Show
</button>
</div>
<div id="result">
</div>
<script>
var xmlhttp;
function actionSend() {
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else {// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
var values = $("input").map(function () {
return $(this).val();
}).get();
var myJsonString = JSON.stringify(values);
xmlhttp.onreadystatechange = respond;
xmlhttp.open("POST", "ajax-test.php", true);
xmlhttp.send(myJsonString);
}
function respond() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById('result').innerHTML = xmlhttp.responseText;
}
}
</script>
</body>
</html>
PHP file ajax-test.php :
<?php
$str_json = file_get_contents('php://input'); //($_POST doesn't work here)
$response = json_decode($str_json, true); // decoding received JSON to array
$lName = $response[0];
$age = $response[1];
echo '
<div align="center">
<h5> Received data: </h5>
<table border="1" style="border-collapse: collapse;">
<tr> <th> First Name</th> <th> Age</th> </tr>
<tr>
<td> <center> '.$lName.'<center></td>
<td> <center> '.$age.'</center></td>
</tr>
</table></div>
';
?>
PHP has a built in function called json_decode(). Just pass the JSON string into this function and it will convert it to the PHP equivalent string, array or object.
In order to pass it as a string from Javascript, you can convert it to JSON using
JSON.stringify(object);
or a library such as Prototype
This is a summary of the main solutions with easy-to-reproduce code:
Method 1 (application/json or text/plain + JSON.stringify)
var data = {foo: 'blah "!"', bar: 123};
var xhr = new XMLHttpRequest();
xhr.open("POST", "test.php");
xhr.onreadystatechange = function() { if (xhr.readyState === 4 && xhr.status === 200) { console.log(xhr.responseText); } }
xhr.setRequestHeader("Content-type", "application/json") // or "text/plain"
xhr.send(JSON.stringify(data));
PHP side, you can get the data with:
print_r(json_decode(file_get_contents('php://input'), true));
Method 2 (x-www-form-urlencoded + JSON.stringify)
var data = {foo: 'blah "!"', bar: 123};
var xhr = new XMLHttpRequest();
xhr.open("POST", "test.php");
xhr.onreadystatechange = function() { if (xhr.readyState === 4 && xhr.status === 200) { console.log(xhr.responseText); } }
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send("json=" + encodeURIComponent(JSON.stringify(data)));
Note: encodeURIComponent(...) is needed for example if the JSON contains & character.
PHP side, you can get the data with:
print_r(json_decode($_POST['json'], true));
Method 3 (x-www-form-urlencoded + URLSearchParams)
var data = {foo: 'blah "!"', bar: 123};
var xhr = new XMLHttpRequest();
xhr.open("POST", "test.php");
xhr.onreadystatechange = function() { if (xhr.readyState === 4 && xhr.status === 200) { console.log(xhr.responseText); } }
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send(new URLSearchParams(data).toString());
PHP side, you can get the data with:
print_r($_POST);
Note: https://caniuse.com/#search=URLSearchParams
There are 3 relevant ways to send Data from client Side (HTML, Javascript, Vbscript ..etc) to Server Side (PHP, ASP, JSP ...etc)
1. HTML form Posting Request (GET or POST).
2. AJAX (This also comes under GET and POST)
3. Cookie
HTML form Posting Request (GET or POST)
This is most commonly used method, and we can send more Data through this method
AJAX
This is Asynchronous method and this has to work with secure way, here also we can send more Data.
Cookie
This is nice way to use small amount of insensitive data. this is the best way to work with bit of data.
In your case You can prefer HTML form post or AJAX. But before sending to server validate your json by yourself or use link like http://jsonlint.com/
If you have Json Object convert it into String using JSON.stringify(object), If you have JSON string send it as it is.
using JSON.stringify(yourObj) or Object.toJSON(yourObj) last one is for using prototype.js, then send it using whatever you want, ajax or submit, and you use, as suggested, json_decode ( http://www.php.net/manual/en/function.json-decode.php ) to parse it in php. And then you can use it as an array.
I recommend the jquery.post() method.
<html>
<script type="text/javascript">
var myJSONObject = {"bindings": 11};
alert(myJSONObject);
var stringJson =JSON.stringify(myJSONObject);
alert(stringJson);
</script>
</html>
You can easily convert object into urlencoded string:
function objToUrlEncode(obj, keys) {
let str = "";
keys = keys || [];
for (let key in obj) {
keys.push(key);
if (typeof (obj[key]) === 'object') {
str += objToUrlEncode(obj[key], keys);
} else {
for (let i in keys) {
if (i == 0) str += keys[0];
else str += `[${keys[i]}]`
}
str += `=${obj[key]}&`;
keys.pop();
}
}
return str;
}
console.log(objToUrlEncode({ key: 'value', obj: { obj_key: 'obj_value' } }));
// key=value&obj[obj_key]=obj_value&
I found easy way to do but I know it not perfect
1.assign json to
if you JSON is
var data = [
{key:1,n: "Eve"}
,{key:2,n:"Mom"}
];
in ---main.php ----
<form action="second.php" method="get" >
<input name="data" type="text" id="data" style="display:none" >
<input id="submit" type="submit" style="display:none" >
</form>
<script>
var data = [
{key:1,n: "Eve"}
,{key:2,n:"Mom"} ];
function setInput(data){
var input = document.getElementById('data');
input.value = JSON.stringify(data);
var submit =document.getElementById('submit');
//to submit and goto second page
submit.click();
}
//call function
setInput(data);
</script>
in ------ second.php -----
<script>
printJson();
function printJson(){
var data = getUrlVars()["data"];
//decode uri to normal character
data = decodeURI(data);
//for special character , / ? : # & = + $ #
data = decodeURIComponent(data);
//remove " ' " at first and last in string before parse string to JSON
data = data.slice(1,-1);
data = JSON.parse(data);
alert(JSON.stringify(data));
}
//read get variable form url
//credit http://papermashup.com/read-url-get-variables-withjavascript/
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
vars[key] = value;
});
return vars;
}
</script>

is my code victim of same origin policy?

Here is my code. You have to kindly look does it suffer from 'same origin policy' in this shape. The domain for HTML is (http://127.0.0.1/jqload.html) & php file (http://127.0.0.1/conn_sql.php). This is json format : [{"options":"smart_exp"},{"options":"user_int"},{"options":"blahblah"}]
I actually want to append json data that I receive in HTYML with user input & I am suffering in that. If I use eval for parsing, it works fine to point its put here. But if I use JSON.parse to parse, the whole code stops working & this error message is issued '"IMPORTANT: Remove this line from json2.js before deployment". I put my code for some other question on stackoverflow forum & I was told that my code suffer from 'same origin policy' that causes the problems in appending JSON data. So can you kindly see does my code suffer from this policy? Though I have doubts it suffers from that policy as I learn that it restricts if files reside on different domains, here both files reside next to each other.
Code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html><head></head>
<body>
<form name="index">
<p><input type = "text" id = "txt" name = "txt"></input>
<p><input type = "button" id = "send" name = "send" value = "send" onClick=
"ADDLISTITEM"></input>
<p><select name="user_spec" id="user_spec" />
</form>
<script>
function ADDLISTITEM()
{
alert (json.length); // working
alert json.options[1]; // do not show any value, message just for testing
json.options[json.length+1] = 'newOption'; //not working; HELP HERE
jsonString = JSON.stringify(json);//working fine for current data
alert(jsonString);
//here I have to implement send this stringify(json) back to server,HELP
//HERE
}
</script>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
var json;
$(document).ready(function() {
jQuery .getJSON("http://127.0.0.1/conn_mysql.php", function (jsonData) {
json = jsonData;
$.each(jsonData, function (i, j) {
document.index.user_spec.options[i] = new Option(j.options);
});
});
});
</script>
</body>
</html>
You're on the right track, but here: $.each(jsonData, function (i, j) { ... } you are actually looping through each character of the jsonData string, and not the json object. Just change jsonData to json inside the $.each(), and it should work fine (regardless of whether you're using eval or JSON.parse, but I recommend the latter).
Edited: Since you are using jQuery.getJSON(), you don't need to use eval or JSON.parse - jQuery does it for you. So inside your callback function, just set json = jsonData .
<script>
var json;
$(document).ready(function() {
jQuery .getJSON("http://127.0.0.1/conn_mysql.php", function (jsonData) {
json = jsonData;
$.each(json, function (i, j) {
document.index.user_spec.options[i] = new Option(j.options);
});
});
});
</script>

Categories