I've been trying some code from here to achieve my goal but I haven't found the solution yet.
Goal: I have to get a JSON objects array from a web (through the URL) using GET method. I have to do that in Javascript or HTML. I have been trying in javascript with jquery and with ajax. The idea is when the webpage I'm making loads I have to get the JSON objects array. I would want to save the JSON objets array fetched in a string to manipulate it.
Example of JSON array that I have to get from http://www.example.com/example
[
{
"type": "1",
"id": "50a92047a88d8",
"title": "Real Madrid"
},
{
"type": "1",
"id": "500cbb1a5ef23",
"title": "Fernando Alonso"
}
]
When I run my code in the browser I always get no response.
These are some pieces of code I've tried:
HTML Code
<html>
<head>
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script src="http://code.jquery.com/ui/1.8.23/jquery-ui.min.js"></script>
<script type="text/javascript" src="script.js"></script>
<link type = "text/css" rel = "stylesheet" href = "stylesheet.css"/>
</head>
<body onload = "httpGet('http://www.example.com/example')">
</body>
</html>
Javascript code
function httpGet(theUrl)
{
$.getJSON(theUrl, function(data)
{
$.each(data, function()
{
console.log(this['title']);
})
});
}
Other Javascript code
$.ajax(
{
url: theUrl,
type: 'GET',
dataType: 'json',
accept: 'application/json',
success: function(data)
{
console.log(data);
var objets= $.parseJSON(data);
$.each(objets, function(i, obj)
{
console.log(obj.title);
});
}
});
And I have prove a lot of code from here (stak overflow)...
Thank you very much and excuse me for my English.
Edit:
Some time ago I tried with stringify, but I don't really known how can it works.
I proved the following:
function httpGet(theUrl)
{
var xmlHttp = null;
xmlHttp = new XMLHttpRequest();
xmlHttp.open("GET", theUrl, true ); // I tried with true and with false
xmlHttp.send();
var answer= xmlHttp.responseText;
var str = JSON.stringify(answer);
console.log(str);
var jsonResponse = JSON.parse(str);
console.log(jsonResponse);
}
You can't fetch data cross domain with javascript, you have to put the data under your domain or using jsonp to get it, or just print it on the page.
I have found the solution to my problem with one line php code
<?php
echo file_get_contents("http://www.example.com/example");
?>
After that, I needed to reference the php file in the javascript file.
Finally I could access to the key-value pairs of the JSON objects array.
function httpGet()
{
$.getJSON('phpfile.php', function(data)
{
$.each(data, function(i, obj)
{
console.log("object: " + i + ", title: " + obj.title);
});
});
}
In the HTML file I modified the next line:
<body onload = "httpGet()">
Related
One php file with php and javascript inside. I have a multidimensional array defined in the javascript part. I can see the proper output of "key" and "value" in the console but I do no get the array into php after submitting my form.
What I am doing wrong?
<?php
echo "Postcmd: ".$_POST["postcmd"];
print_r($_POST["postcmd"]);
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script type="text/javascript">
var postcmd =[];
var key;
function formsubmitplus(ele) {
postcmd.push({"key": ele.id, "value": ele.value});
for (key in postcmd) {
if (postcmd.hasOwnProperty(key)) {
console.log(postcmd[key])
}
}
request = $.ajax({
url: "/index.php",
type: "post",
data: postcmd
});
}
</script>
Not even this simple and often found script example works for me - what else might be the issue? Are there other (basic) things to know about js->PHP?
<?php
// index.php
?>
<html>
<head>
<title>Pass JS array to PHP.</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
var arrayfromjs = "123";
$.ajax({
type: "POST",
url: "index.php",
data: { testArray : arrayfromjs},
success: function() {
alert("Success");
}
});
</script>
</head>
<body>
<?php
echo "<br>Pass JS array to PHP.<br>";
$myArray = $_POST['testArray'];
print_r($myArray);
?>
</body>
</html>
Per the jQuery documentation,
Data to be sent to the server. It is converted to a query string, if not already a string. It's appended to the url for GET-requests. See processData option to prevent this automatic processing. Object must be Key/Value pairs. If value is an Array, jQuery serializes multiple values with same key based on the value of the traditional setting (described below).
Thus, your data field must contain an object (such as {foo: bar, foo_again: bar_again}; in PHP, this would read as $_POST['foo'] == "bar"). However, your code submits an array with one element: the object specified. In addition, PHP does not magically turn your JS array/object into a PHP array. You have to parse the string passed into PHP and turn it into the array you need.
If you print $_POST, you can see what exactly is being passed into your PHP. That might help you see what is happening.
You are creating the following structure using the push method:
[
{
"key":"first_name",
"value": "Bob"
}
]
Using your code, all you need to do is index the postcmd variable to the object. You also had some indexing issues with your loop. The key variable would just be index 0. So you would need to set it to postcmd[key] to check for the key named "key".
function formsubmitplus(ele) {
postcmd.push({"key": ele.id, "value": ele.value});
for (key in postcmd) {
if (postcmd[key].hasOwnProperty("key")) {
console.log(postcmd[key].key)
}
}
request = $.ajax({
url: "/index.php",
type: "post",
data: postcmd[0]
});
}
Using the above snippet, jQuery will then parse the data into the correct key value pairs. Without specifying the index, the data would be posted as undefined=Bob
On the PHP side you should be able to grab those values as such:
<?php
echo $_POST['key'].PHP_EOL;
echo $_POST['value'];
?>
Alternative Method - JSON Submission
You could make the following modification to post the data as JSON:
function formsubmitplus(ele) {
for (key in postcmd) {
if (postcmd[key].hasOwnProperty("key")) {
console.log(postcmd[key].key)
}
}
request = $.ajax({
url: "/index.php",
type: "post",
contentType: 'application/json',
data: JSON.stringify(postcmd)
});
}
Then on the PHP side you can grab the POST body using the following:
<?php
echo "<pre>";
$json_data = json_decode(file_get_contents('php://input'), true);
print_r($json_data);
?>
If you would rather work with a PHP Object vs an Associative array. Just change true to false.
Ad the end I found a solution without jquery which works for me the best.
It is "playing" with HIDDEN form fields.
Maybe someone finds it helpful:
function submitform() {
Object.getOwnPropertyNames(postcmd).forEach(function(val, idx, array) {
var outarrayoutput = val + ' ==== ' + postcmd[val];
console.log(outarrayoutput);
var newHidInp = document.createElement('input');
newHidInp.type = 'hidden';
newHidInp.name = 'outArray[]';
newHidInp.value = outarrayoutput;
maintable.appendChild(newHidInp);
});
document.maintable.submit();
}
I am learning how to load json data into .js file. I have created a employee.json file. I saved my js and json file and on the desktop. What I trying to do is to put all the id in json files into an array in the js. I do not know what could be wrong. Hope someone could help me out. Thank you in advance.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>JSON with jQuery</title>
</head>
<body>
<p id="demo"></p>
<h1><h2>
<script src = "<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script>
var res = [];
$.ajax({
url: 'employee.json',
dataType: 'json',
type: 'get',
cache: false,
success: function(data) {
$(data.people).each(function(index, value) {
res.push(value.id);
});
}
});
document.getElementById("demo").innerHTML = res.toString();
</script>
</body>
</html>
{
"person": [
{
"id" : 1,
"firstName" : "Lokesh"
},
{
"id" : 2,
"firstName" : "bryant"
}
{
"id" : 3,
"firstName" : "kobe"
}
]
}
Error 1: Typing error. <script src = "<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>. You mistyped the src of the script, accidentally adding another another <script> start tag.
Error 2: Misplaced statement. document.getElementById("demo").innerHTML = res.toString(); should be placed in the success callback function, so it will be executed only after the server responds. If it executes prematurely, res will still be [].
Error 3: type: 'GET' should be method: 'GET', according to the docs (though 'GET' is default so you don't need to explicitly write this).
Use this:
<p id="demo"></p>
<h1><h2>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script>
var res = [];
$.ajax({
url: 'employee.json',
dataType: 'json',
method: 'get',
cache: false,
success: function(data) {
$(data.people).each(function(index, value) {
res.push(value.id);
});
document.getElementById("demo").innerHTML = res.toString();
}
});
</script>
You can't use the local json to read. it gives cross origin request failure. so deploy both the files (html and json) into a we server and execute. or place the json data onto some web url(http://somesite/myjson) and then request that url and see.
First of all, the JSON shouldn't be existed as in physical "file". It has to be generated by a backend language / web service etc. The JSON tags inside a manually created "file" have high chance of data invalidity upon parsing.
Solution
Use a Web Service to generate valid JSON output. And from Javascript end, use:
JSON.stringify( data );
The reading works.
However I got a syntax error in the firefox console (which is tiresome when I read 30 files).
The files are annotation files like (time \t value) with no headers like :
0.0 5.2
0.5 5.6
1.0 6.3
...
This is the ajax code :
function getdatafromfile(filename) {
// Read annotation file. Example : %timeinstant \t %value \n
// Return an array of string
var arraydata
$.ajax({
type: "GET",
url: filename,
dataType: "text",
async: false,
success: function(csv) {arraydata = $.csv.toArrays(csv,{separator:'\t'}); }
});
return arraydata}
And with d3:
d3.text(filename, function(text) {
var data = d3.tsv.parseRows(text).map(function(row) {
return row.map(function(value) {
return +value;
});
});
console.log(data);
});
}
It seems that I could use one of those code, but I got a syntax error in both cases (with firefox 33.1).
A file reader could work like the code below.
In the example I've added a flag to use the content of the variable instead of a file. That's just for the demo and can be removed. The same code is here as jsFiddle.
Maybe you could add some validation before or after the $.csv method. So you know that the file was a csv/tsv file.
If you need to open the file with-out user interaction, you have to look for something different because JS is not allowed to open a file with-out the user choosing the file (security concerns, see this SO question).
You could add your data to a database and read it from there. e.g. Firebase or MongoDB or use a JSON file. The code of my other answer should work for a JSON file that you host with your webpage.
var demoTxt = "0.0 5.2\
0.5 5.6\
1.0 6.3";
var flag_usedemofile = true; //if true var demoTxt will be used
function doOpen(evt) {
var files = evt.target.files,
reader = new FileReader();
reader.onload = function() {
if ( !flag_usedemofile) {
var arraydata = $.csv.toArrays(this.result,{separator:' '});
showout.value = arraydata; //this.result;
} else {
var arraydata = $.csv.toArrays(demoTxt,{separator:' '});
showout.value = arraydata;
console.log(arraydata);
}
};
reader.readAsText(files[0]);
}
var openbtn = document.getElementById("openselect"),
showout = document.getElementById("showresult");
openselect.addEventListener("change", doOpen, false);
#showresult {
width:98%;
height: 300px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery-csv/0.71/jquery.csv-0.71.min.js"></script>
<input type="file" id="openselect" />
<textarea id="showresult"></textarea>
I'm not exactly sure what syntax error you are getting. But I think the error have something to do with the mime type of your json request.
I think the best way is to wrap your data in json and then use JSONP. (I have also tried to get it working with text/plain, but with-out success.)
Please check the following example for details. You can also find the same example on
jsFiddle.
(function ($) {
var url = 'http://www.mocky.io/v2/547c5e31501c337b019a63b0'; // dummy url
var jsonCallback = function (csv) {
var arraydata;
console.log(data);
$('#data').html(JSON.stringify(csv, null, 2));
arraydata = $.csv.toArrays(csv.data,{separator:'\t'});
console.log(arraydata);
};
$.ajax({
type: 'GET',
url: url,
contentType: "application/json",
dataType: 'jsonp'
}).done(jsonCallback)
.fail(function (xhr) {
alert("error" + xhr.responseText);
});
})(jQuery);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<pre id='data'></pre>
I'm answering a certain request to my Django server with a JSON object:
return HttpResponse(json.dumps(geojson), mimetype="application/json")
But I don't know how to get it at the HTML/javascript. I have gone through lots of similar questions and tutorials, but they all start defining an string variable with an example of JSON to use it. But I haven't been able to find how to get the JSON the server is answering me.
Any help or tutorial link?
EDIT: I tried using jQuery.ajax as suggested, but the function is never being executed:
Content of map-config.js:
var jsondata;
var lon = 5;
var lat = 40;
var zoom = 5;
var map, layer;
function init(){
map = new OpenLayers.Map( 'map' );
layer = new OpenLayers.Layer.WMS( "OpenLayers WMS",
"http://vmap0.tiles.osgeo.org/wms/vmap0",
{layers: 'basic'} );
map.addLayer(layer);
map.setCenter(new OpenLayers.LonLat(lon, lat), zoom);
var geojson_format = new OpenLayers.Format.GeoJSON();
var vector_layer = new OpenLayers.Layer.Vector();
map.addLayer(vector_layer);
vector_layer.addFeatures(geojson_format.read(jsondata)); // Feeding with the json directly
}
$.ajax({
url: "localhost:8000/form/",
type: "POST",
dataType: "json"
}).done(function (data) {
$("#dialog").dialog('Hello POST!');
console.log(data);
jsondata = data; // Saving JSON at a variable so it can be used with the map
});
I also have another js file for a form, which works properly. And the HTML file is this one:
<html>
<head>
<script src="{{STATIC_URL}}js/jquery-1.9.1.js"></script>
<script src="{{STATIC_URL}}js/jquery-ui-1.10.3.custom.js"></script>
<script src="{{STATIC_URL}}js/OpenLayers.js"></script>
<script src="{{STATIC_URL}}js/form.js"></script>
<script src="{{STATIC_URL}}js/map-config.js"></script>
<link rel="stylesheet" href="{{STATIC_URL}}css/jquery-ui-1.10.3.custom.css">
<link rel="stylesheet" href="{{STATIC_URL}}css/style.css" type="text/css">
</head>
<body onload="init()">
<div id="form" class="form-style">
<p>Start Date: <input type="text" id="id_startDate"></p>
<p>
<label for="amount">Interval:</label>
<input type="text" id="amount" style="border: 0; color: #f6931f; font-weight: bold;" />
</p>
<p> <div id="id_interval"></div> </p>
<p>
<button id="id_okButton">OK</button>
</p>
</p>
</div>
<div id="map" class="smallmap">
</body>
So, when the POST request is received with the json coming from server, the jQuery.ajax method should execute, and the map should show some data (draw polygons over it to be exact). That POST is arraiving OK as stated at FireBug (the snapshot is not showing the whole json object, which is big):
Did you serialize your object to json format ?
$.ajax({
url: //your_url,
type: "POST",
success: function (data) {
// write your parsing code..
}
},
error: function (err) {
}
});
exp json from w3schools.com
{
"people": [
{ "firstName":"John" , "lastName":"Doe" },
{ "firstName":"Anna" , "lastName":"Smith" },
{ "firstName":"Peter" , "lastName":"Jones" }
]
}
parsing exp (in jquery ajax success function ):
$.each(data.people, function (i, person) {
console.log(person.firstName + " " + person.lastName)
});
You could use jQuery for the request on the browser side.
$.ajax({
url: "example.com/data",
dataType: "json"
}).done(function (data) {
// data is the javascript object from the json response
});
Edit: Linked to the wrong jQuery call.
See details
I already tried several methods getting my xml-script parsed in java, but i can't figure it out!
I have 2 files.
mysql_get.php is returning an XML script if it is called.
post_alert.html is fetching the XML script from mysql_get.php over jQuery $.post(..) as shown below:
function init2() {
var response;
$.post("mysql_get.php", function (data) {
response = data;
alert(response)
});
var xml;
xml = $.parseXML(response);
alert($(response).find("item").each(function () {
$(this).attr("id")
}));
}
After hit a button which call init2(), i get the response message in xml style as i can see by the alert popup.
<?xml version="1.0" encoding="uft-8"?>
<root>
<collection collection="locationPoint">
<item id="1">
<latitude>23.4442</latitude>
<longitude>51.2341</longitude>
</item>
<item id="2">
<latitude>2849.24</latitude>
<longitude>213.132</longitude>
</item>
</collection>
But the alert doesn't popup "1" in addition as I wished for correct parsing.
What am I doing wrong?
Here are a couple of things:
Line 1 of you xml file should read UTF-8 not UFT-8
Line 2 should be deleted, else make sure you have a closing tag, invalid xml
Then here is a little example that I hope helps:
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.js"></script>
</head>
<body>
<div id="dc"></div>
</body>
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
url: 'mysql_get.php',
type: 'post',
dataType: 'xml',
success: function(data) {
$(data).find('item').each(function () {
$('#dc').append($(this).attr('id') + '<br/>')
});
},
error: function(data) {
$('#dc').html('error');
}
});
});
</script>
</html>
The A in AJAX stands for asynchronous. The code after $.post(..) is executed right after $.post is called, regardless of the response state.
You have to move the var xml..-code inside the $.post call.
Also, .each() only loops through the elements, without returning the IDs. Use .map() to create an object consisting of the ids, and .toArray() to get an array representation of it.
function init2() {
$.post("mysql_get.php", function(data) {
var response = data;
var xml = $($.parseXML(response));
alert(response.find("item").map(function () {
return $(this).attr("id")
}).toArray() );
});
}
Take a look at XML manipulation with jQuery