why JavaScript is not displaying parsed json data? - javascript

This is format of JSON data: [{"options":"smart_exp"},{"options":"user_int"},{"options":"blahblah"}] that I receive through getjson from server. I need to append json with user input. I am trying to do it in this way: 1st convert it into javascript object, append it with user input, again convert to json object & send it back to server for database update. I have converted json to javaScript object using eval(). Now not able to manipulate javascript object. If I convert javascript object back to json object, it displays correctly all data that was sent from server.
<!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>
<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()
{// this script suffers from errors on eval/JSON.parse methods
alert (json.length);//outputs corrcet with eval
tring = JSON.stringify(json);//outputs corrcet with eval
alert(jsonString);//outputs corrcet with eval
alert(json.options[0]);//no output
}
</script>
<script src="http://code.jquery.com/jquery-latest.min.js">
</script>
<script src="http://www.json.org/json2.js"></script>
<script>
var json;
$(document).ready(function() {
jQuery .getJSON("http://127.0.0.1/conn_mysql.php", function (jsonData) {
json = eval(jsonData);
//json = JSON.parse(jsonData);/*error if uncomment:"IMPORTANT: Remove this line from
json2.js before deployment"*/
$.each(jsonData, function (i, j) {
document.index.user_spec.options[i] = new Option(j.options);
});});
});
</script>
</body>
</html>

In jQuery, $.getJSON()'s callback gets called with parsed JSON data; just use it.
$.getJSON("*.php", function(data) {
$.each(data, function() { alert(this.options); });
);
should give you an alert for every {"options": "xyzzy"} object in the array.
EDIT after OP edited their post:
Your edit clarifies things a little: You won't get any data back -- and it will be completely silent, too, as I found out -- if you violate the same origin policy.
Basically (with exceptions (preflight checks, etc)), you can only access URLs on the exact same domain via AJAX. If your HTML file is a static file served locally, it can not access http://127.0.0.1/; if your file is http://foo.baz.quux.org/, you can't simply AJAX into http://mordor.baz.quux.org .

I don't think the problem here has anything to do with eval/parse etc or the same origin policy. Your json is an array of objects each containing a member named options. Therefore you cannot do json.options[0], you have to do json[0].options.

var json = [{"options":"smart_exp"}, {"options":"user_int"}, {"options":"blahblah"}]
for (var i = 0; i < json.length; i++){
alert(json[i].options)
}

Related

How to display the values coming from springboot controller in javascript

I have a controller which is passing the json object wrapped inside a model.
#RequestMapping("/template")
public String showTemplate(Model model) {
JSONObject obj = new JSONObject();
obj.put("equipmentID", "30584D277D6D4568B17EBB8917D0CB15");
model.addAttribute("template",obj);
return "templates";
}
I would like to use these values in my javascript. I am not able to do that. However, I can see display these values in HTML.
<head>
<script>
function test()
{
var temp = "${template}";
alert(temp); // The values are not displayed here
}
</script>
<body onload="test()">
<span th:text="${template}"> </span> //I can display the values here
<body>
I have also looked into this question How to get spring mvc controller model key value inside javascript? and tried both the options with or without quotes with no success.
I have also tried defining in HTML:
<input type="hidden" id="templates" value='${template}'/>
and using getElementById in my javascript with no success:
var template = document.getElementById("templates");
Using thymeleaf inlining you can use the below:
<script th:inline="javascript">
var message = [[${template}]];
alert(template);
</script>
There are additional ways to access server side variables depending on your use case refer to http://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#javascript-inlining for more information.

How to extract json objects into an external file?

I have this small code example:
<script type="text/javascript">
var texts = [{key:'key_1', value:'value_1'},
{key:'key_2', value:'value_2'},
{key:'key_3', value:'value_3'}];
</script>
I use a json array directly in my xhtml page by using the script tag. The json array "texts" is used by an another java script function in my xhtml page, but that is not important at the moment.
How can a extract this json array into an external file? Which library it must be used?
EDIT:
I use a java maven project and that should be include my external json file!
I tried this code but it doesn´t work:
<script type="text/javascript">
var placeholderTexts = himjQuery(document).getJSON('placeholder.json');
</script>
You can use each loop in jQuery
Just try this
$.each(texts, function(key, value) { }
please try the below.
var arraysel;
var json = { };
for(var i = 0, l = arraysel.length; i < l; i++) {
json[arraysel= [i].id] = arraysel= [i].value;
}
After reading many times your question, I think what you want is this:
Create a .js file, for example data.js, with your data... which is not a JSON-serialized object, but a real literal. Use pure JSON notation if you want.
var DATA = {"a":1, "b":2};
Import that "script" wherever you want to use your data.
<script type="text/javascript" src="./data.js></script>
Use this data from any place in your JS code, for instance:
console.log(DATA.a);
Please get JSON data from AJAX and evaluate response and store in variable
<script>
var placeholderTexts = new Object();
$(function(){
$.get('placeholder.json', function(data){
try{
placeholderTexts = jQuery.parseJSON(data);
console.log(placeholderTexts)
}catch(e){
alert(e.toString());
}
});
});
</script>

In PHP how to use $_REQUEST to retrieve an array of inputs to enter into a database

I am using AJAX to send inputs from a webpage to a PHP file to then be entered into a database. Here is my JavaScript file:
var pageLoaded = function () {
var submitButton = document.getElementById("submit");
if (submitButton) {
submitButton.addEventListener("click", submit, true);
}
};
var submit = function () {
var xhr, changeListener;
var form = document.getElementById('item_form');
var inputs = form.getElementsByTagName('input');
// create a request object
xhr = new XMLHttpRequest();
// initialise a request, specifying the HTTP method
// to be used and the URL to be connected to.
xhr.open("POST", "../php/add_item.php", true);
console.log(inputs[0].value); // debugging
// Sends the inputs to the add_item.php file
xhr.send(inputs);
};
window.onload = pageLoaded;
Here I am trying to send inputs from a form to a PHP file called add_item.php located "../php/add_item.php" in my file system.
I am pretty sure this code works and sends the inputs to the PHP file in an array.
My question is, how do I then use $_REQUEST within that file to be able to use the inputs within the array to send to a database? Or, what is the best way of doing this?
The xhr.send() method only accepts a string. If you want to send an array you have to flatten it into a string before posting. You can do this easily using the JSON.stringify() method in javascript, then use json_decode() function in PHP on receiving it.
Also for PHP to receive the data properly in the $_POST[] variable (or $_REQUEST if you must, but not recommended) you need to set a name for the POST variable and URL-encode your JSON text like this:
var json_array = JSON.stringify(inputs);
xhr.send('myJSONData=' + encodeURIComponent(json_array));
On the PHP side you shouldn't need to use urldecode() because the server stack expects to receive POSTed name-value pairs url-encoded. But you will need to use json_decode on the posted variable to get the array back, e.g.:
php_array = json_decode($_POST["myJSONData"]);
You will see other methods to do this, including setting the xhr POST content-type header to JSON, but in my experience this is the path of least resistance.
Also note whilst it is possible to send an "array" of objects in an HTML form like this:
<input type="text" name="myArray[]" value="val1">
<input type="text" name="myArray[]" value="val2">
<input type="text" name="myArray[]" value="val3">
<input type="text" name="myArray[]" value="val4">
which will result in an array being available within PHP in the variable $_POST["myArray"], there is no easy equivalent of this using the XHR object (AJAX method). JSON.stringify() is IMO the easiest way to go.
The variables inside the $_REQUEST are stored as an array. To access them you would do something similar to this:
echo $_REQUEST['input_1'];
To view all the variables (in a nice format) sent by the JS you could use this code:
echo "<pre>";
print_r($_REQUEST);
echo "</pre>";
You can't do it in the way you are doing it. You send "input" array which is incorrect. You should prepare array of input values. Morover, I'd recommend you to use JQuery.
$(function (){
$("#submit").click(function (){
//the way to get input values and names
var arr = [];
$("input").each(function (index,value){});
arr.push([$(value).attr('name'), $(value).val()];
});
// it can be replaced also via serialize() funciton
//ajax
$.post( "../php/add_item.php", arr)
.done(function( data ) {
//data has been send response is in data object
});
});
});
In PHP you can get these values via $_POST. $_REQUEST is not needed here because you use POST method. For example if you have input
<input name="xxx" value="test">
to print value of this input in PHP you need use this code
echo $_POST['xxx'];
If you don't want to use JQuery then you still need loop through inputs and prepare proper array to send it via XHR.

Reading contents from a JSON url and writing out those contents

I have a url [https://www.inquicker.com/facility/americas-family-doctors.json] that is a JSON data url. How can I access the contents of this url, and write out the values.
The format contains schedules as an array that inside it contains schedule_id, name, and available_times. I have tried various ways of getting the JSON file, but none have worked.
UPDATE:
Well I have got it this far with this code, and it's laying out what looks like objects from the array. So I believe I got the cross site issue under control. I just need to figure out how to access the data now.
<!DOCTYPE html>
<html>
<head>
<title>JQuery (cross-domain) JSONP</title>
<script type="text/javascript"src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"> </script>
<script>
$(document).ready(function(){
$.getJSON('https://www.inquicker.com/facility/americas-family-doctors.json',
function(data){
alert(data.facility);
$.each(data.schedules, function(i, name){
$('#names').append('<li>' + name.available_times[0] + '</li>');
});
});
});
</script>
</head>
<body>
<ul id="names"></ul>
</body>
</html>
Any help, or suggestions will be greatly appreciated, Thanks.
You cannot generally pass an Ajax request across domains. Normally a server will refuse any Ajax calls that don't come from the same source unless it is explicitly configured otherwise. I am guessing that you aren't calling from the same domain, given that you are using a fully-qualified URL. If you own the server, you will have to configure it to accept such calls from your other domain.
If this is not the case, launch the script in Firefox with Firebug running and look at the console output and tell me what error you get if any.
Once you manage to pass the JSON from your server back to the page, you will retrieve it in your JavaScript as a string. You then need to execute this function:
var jsonObject = JSON.parse(jsonString);
where jsonString is the string that you received from your server. jsonObject becomes an object representation of the JSON passed back to the answer that you can access using dot notation.
Try something like :
alert(json.facility);
There is no title json object in the url you have mentioned.
The JSON is already parsed when it comes to your function.
$.get('https://www.inquicker.com/facility/americas-family-doctors.json', function(result){
alert(result.facility); //Do whatever you want here
// result.schedules array is also ready
});

Reaching a data in json using getJSON

I want to get the username's profile image. So i prefer to use twitter api version 1 for this.(The regular version of api is here). But my code doesn't return any data. How can i fix this?
<html>
<head>
<script src="http://code.jquery.com/jquery-1.8.2.min.js"></script>
<script>
$(document).ready( function() {
var userPage = "https//twitter.com/jack";
var arr = userPage.split("/");
var username = "";
for(i=3;i<4;i++)
username += arr[i];
var page = 'https://api.twitter.com/1/users/show.json?screen_name='+username;
$.getJSON(page, function(data) {
alert(data.profile_image_url);
});
})
</script>
</head>
<body>
</body>
</html>
Add "&callback=?" to the URL to force jsonp format to get around the Access-Control-Allow-Origin issue.
var page = 'https://api.twitter.com/1/users/show.json?screen_name='+username + "&callback=?";
EXAMPLE
JSONP:
The way JSONP works is simple, but requires a little bit of
server-side cooperation. Basically, the idea is that you let the
client decide on a small chunk of arbitrary text to prepend to the
JSON document, and you wrap it in parentheses to create a valid
JavaScript document (and possibly a valid function call).
The client decides on the arbitrary prepended text by using a query
argument named jsonp with the text to prepend. Simple! With an empty
jsonp argument, the result document is simply JSON wrapped in
parentheses.

Categories

Resources