I have this code that works for me:
$('#demo').live('pagecreate', function(event) {
var data, template, html;
data = {
"sver": [{"title":"Buffet Stagaljxxs" , "url_titler":"buffet-stagalj" },{"title":"Restoran Vrske" , "url_titler":"restoran-vrske" }]
};
template = '<ul data-role="listview" data-divider-theme="b" data-inset="false">{{#sver}}<li data-theme="b"><h3>{{title}}</h3><p>Opis: {{title}}</p></li>{{/sver}}</ul>';
html = Mustache.to_html(template, data);
$('#content').html(html);
});
Now i need to use remote json using getJSON, instead raw json like in my example.
I can't get it to work. Access-Control-Allow-Origin is not the issue.
This is the remote json address
Thanks
Call the data by using Ajax (like the function below)
<script>
function getJSONData(url)
{
var data = null;
var request = window.XMLHttpRequest ? new XMLHttpRequest() : (window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : null);
if (null != request)
{
request.open('GET', url, false);
request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
request.send(data);
//Parse returned JSON string.
data = JSON.parse(request.responseText);
}
return data;
}
$('#demo').live('pagecreate', function(event) {
var data, template, html;
data = getJSONData('http://wmd.hr/mobile-rss/jason/');
template = '<ul data-role="listview" data-divider-theme="b" data-inset="false">{{#sver}}<li data-theme="b"><h3>{{title}}</h3><p>Opis: {{title}}</p></li>{{/sver}}</ul>';
html = Mustache.to_html(template, data);
$('#content').html(html);
});
</script>
Related
i am trying to send json stringfy array from ajax to Codeigniter 4 controller. but i am not able to receive array in CodeIgniter controller. I am getting error
500 (Internal Server Error)
here is my ajax code
let adbtn = document.getElementById("aDDbtn");
adbtn.addEventListener("click", function () {
const xhtp = new XMLHttpRequest();
xhtp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
console.log(this.responseText);
}
};
var test1 = [1, 2, 3, 4];
xhtp.open("POST", window.location.origin + "/crud/test", false);
xhtp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
let my_json = JSON.stringify(test1);
xhtp.send(my_json);
});
and here is my codeigneter function
public function test()
{
$n= $this->request->getPost("my_json");
$array=json_decode($n);
var_dump($array);
exit;
}
i had javascript array , i converted this to jason stringyfy then tried to decode that but am failed. can anyone please help me ? correct me where am wrong ? i tried to solve bymyself but not succeed.
do it like me for json request
public
function sendActivateCodeViaSms()
{$res['data']='soem data';
return $this->response->setJSON($res)
->setStatusCode(ResponseInterface::HTTP_OK, 'get data')
->setContentType('application/json');
}
I want to bind some data to a variable on command (by the press of a button) from a server. On the server I have a function that will return a JSON object (this has been tested, if I open the API link directly, I do get the proper JSON format). However, the variable stays undefined, no matter what I do. I have a button and a table (px-data-table is part of a framework and should be able to display JSON formatted data):
<button id="runPredictionButton">
<i>Button text</i>
</button>
<px-data-table
table-data$="{{data}}"
</px-data-table>
<div class="output"></div>
And I'm handling the button press and define the variables as follows:
<script>
Polymer({
is: 'custom-view',
properties: {
data: {
type: Object,
notify: true
}
},
ready: function() {
var self = this;
this.$.runPredictionButton.addEventListener('click', function() {
filerootdiv.querySelector('.output').innerHTML = 'Is here';
var xhr = new XMLHttpRequest();
this.data = xhr.open("GET", "API/predict") //as mentioned, API/predict returns a valid JSON
console.log("This data is:" + this.data);
this.data = xhr1.send("API/predict","_self")
console.log("This data is_:" + this.data);
});
}
});
</script>
For some reason, on the console this.data shows up as undefined both times I'm trying to print it. What am I missing? How to pass the JSON from the API call to the this.data variable?
xhr.send() doesn't return what you want.
You need to learn XmlHttpRequest first. Here is documentation. And some easy examples
Simply, you need to listen to onreadystatechange on your xml variable. There you will be able to get data from server.
Additionaly, why are you using addEventListener. You can simply set on-click.
<button id="runPredictionButton" on-click="getDataFromServer">
<i>Button text</i>
</button>
and then you can define javascript function which is called everytime user clicks on button.
getDataFromServer: function() {
var xhr = new XMLHttpRequest();
xhr.open("GET", "API/predict");
xhr.send("API/predict","_self");
xhr.onreadystatechange = function() {
// 4 = data returned
if(xhr.readyState == 4) {
// 200 = OK
if (this.xhttp.status == 200) {
// get data
this.data = xhr.responseText;
}
}
}.bind(this);
}
I am creating a website that reads externally hosted json files and then uses node.js to populate the sites content.
Just to demonstrate what I'm after, this is a really simplified version of what I'm trying to do in node.js
var ids = [111, 222, 333];
ids.forEach(function(id){
var json = getJSONsomehow('http://www.website.com/'+id+'.json');
buildPageContent(json);
});
Is what I want to do possible?
(Marked as a duplicate of "How do I return the response from an asynchronous call?" see my comment below for my rebuttal)
You are trying to get it synchronously. What you should aim for instead, is not a function used like this:
var json = getJSONsomehow('http://www.website.com/'+id+'.json');
but more like this:
getJSONsomehow('http://www.website.com/'+id+'.json', function (err, json) {
if (err) {
// error
} else {
// your json can be used here
}
});
or like this:
getJSONsomehow('http://www.website.com/'+id+'.json')
.then(function (json) {
// you can use your json here
})
.catch(function (err) {
// error
});
You can use the request module to get your data with something like this:
var request = require('request');
var url = 'http://www.website.com/'+id+'.json';
request.get({url: url, json: true}, (err, res, data) => {
if (err) {
// handle error
} else if (res.statusCode === 200) {
// you can use data here - already parsed as json
} else {
// response other than 200 OK
}
});
For a working example see this answer.
For more info see: https://www.npmjs.com/package/request
I think problem is in async request. Function will return result before request finished.
AJAX_req.open( "GET", url, true );
Third parameter specified async request.
You should add handler and do all you want after request finished.
For example:
function AJAX_JSON_Req( url ) {
var AJAX_req = new XMLHttpRequest.XMLHttpRequest();
AJAX_req.open( "GET", url, true );
AJAX_req.setRequestHeader("Content-type", "application/json");
AJAX_req.onreadystatechange = function() {
if (AJAX_req.readyState == 4 && AJAX_req.status == 200) {
console.log(AJAX_req.responseText);
}
};
}
I am trying to create a simple web application which fires a http.request call, get the data and display it over to the html(ejs here). I am able to fire the request, get the data, massage it etc.. but unable to pass it to the view. Sample code is as below:
var searchData = [];
router.post('/',requesthandler);
function requesthandler(req,res){
var options = {
host: url,
port: 9999,
path: qstring,
method: 'GET'
};
var reqget = http.request(options,responsehandler);
reqget.end();
console.log('Rendering now:............................ ');
res.render('result',{title: 'Results Returned',searchdata : searchData});
}
function responsehandler(ress) {
console.log('STATUS: ' + ress.statusCode);
ress.on('data', function (chunk) {
output += chunk;
console.log('BODY: ' );
});
/* reqget.write(output); */
ress.on('end',parseresponse);
}
function parseresponse(){
var data = JSON.parse(output);
console.log(data.responseHeader);
// populate searchData here from data object
searchData.push({//some data});
}
function errorhandler(e) {
console.error(e);
}
module.exports = router;
Problem is I a unable to pass the objeect searchData to the view via res.render();
'Rendering now: ...........' gets executed before execution starts in parseresponse() and so the page is displayed without the data which seems to be in conjuction with using callbacks, So how can I pass the data object to the view once the searchData is loaded in parseresponse().
PS: I am able to print all console statements
define res variable globally:
var res;
function requesthandler(req,resObj){
res = resObj;//set it to the resObj
}
wrap res.render inside a function like this:
function renderPage(){
res.render('result',{title: 'Results Returned',searchdata : searchData});
}
then in parseresponse function do this:
function parseresponse(){
var data = JSON.parse(output);
searchData.push({some data});
renderPage();
}
Hope this solves your problem.
How do i read HttpRequest data sent by POST method from client, on the server, in Dart?
I send a message from the client like this:
HttpRequest request = new HttpRequest();
var url = "http://127.0.0.1:8081";
request.open("POST", url, async: false);
String data = 'hello from client';
request.send(data);
On server i am catching the request like this:
HttpServer.bind('127.0.0.1', 8081).then((server) {
server.listen((HttpRequest request) {
//DATA SHOULD BE READ HERE
});
});
But i cant figure out how to actually read the data... There is not data property in HttpRequest nor anything else...
EDIT This is how i get the answer now:
HttpServer.bind('127.0.0.1', 8081).then((server) {
server.listen((HttpRequest request) {
//DATA SHOULD BE READ HERE
print("got it");
print(request.method);
if(request.method == "POST") {
print("got it 2");
List<int> dataBody = new List<int>();
request.listen(dataBody.addAll, onDone: () {
var postData = new String.fromCharCodes(dataBody);
print(postData);
});
}
});
});
But for some reason the request.method is not "POST" but "OPTIONS", and if i change to if(request.method == "OPTIONS") , then print(postData) will still return nothing...
You can use the StringDecoder to tranform from "List of Int" to "String" from the HttpRequest. Since no matter if you send json, plain text, or png, Dart always send data in form of
"List of Int" to the server.Another means is to use the Streams (http://www.dartlang.org/articles/feet-wet-streams/) tested on Heroku Steam v0.6.2 Dart Editor 0.4.3_r20602 Dat SDK 0.4.3.5_r26062
For example,
the client:
import 'dart:html';
import 'dart:json' as Json;
import 'dart:async';
import 'dart:uri';
final String data = 'Hello World!';
void _sendPNG(String pngData) {
HttpRequest request = new HttpRequest(); // create a new XHR
// add an event handler that is called when the request finishes
request.onReadyStateChange.listen((_)
{
if (request.readyState == HttpRequest.DONE &&
(request.status == 200 || request.status == 0)) {
// data saved OK.
print(request.responseText); // output the response from the server
}
}
);
// POST the data to the server Async
print('Sending Photos to the server...');
var url = "/png";
request.open("POST", url);
request.setRequestHeader("Content-Type", "text/plain");
request.send(data);
}
the server:
import 'dart:io';
import 'dart:async';
import 'dart:json' as Json;
import "package:stream/stream.dart";
import 'package:xml/xml.dart' as xml;
import 'package:unittest/unittest.dart';
import 'package:rikulo_commons/mirrors.dart';
void receivePNG(HttpConnect connect){
var request = connect.request;
var response = connect.response;
if(request.uri.path == '/png' && request.method == 'POST')
{
String png='';
response.write('The server received png request!');
//read incoming List<int> data from request and use StringDecoder to transform incoming data to string
var stream = request.transform(new StringDecoder());
stream.listen((value){
print(value);
//Hello World!
}
else
{
response.write('error');
response.statusCode = HttpStatus.NOT_FOUND;
connect.close();
}
}
configure.dart
var _mapping = {
"/": home,
"/png": receivePNG,
};
Right now, the handling of POST data is a little difficult. But essentially the HttpRequest itself has to be 'listened' to. HttpRequest is a stream itself. In particular it's a Stream<List<int>>. So basically your data may be passed to your HttpRequest as multiple List<int>'s. So we need to reconstruct the data then convert it into a string (assuming you're expecting a string, not binary data, etc). Here's more or less what I do:
HttpServer.bind('127.0.0.1', 8081).then((server) {
server.listen((HttpRequest request) {
if(request.method == "POST") {
List<int> dataBody = new List<int>();
request.listen(dataBody.addAll, onDone: () {
var postData = new String.fromCharCodes(dataBody);
// Do something with the data now.
});
}
request.response.close();
});
Note that the request.listen(dataBody.AddAll, ...) basically calls List.addAll() each time data is to the server (in cases of larger data or multi-part forms it may not come all at once). This ensures we buffer it all until the stream indicates it is 'done' In which case we can now do something with the data we received, like convert it to a string.
I have found this useful example with client/side code
GitHub json send to server Example
// XXX: Dart Editor thinks this is OK, but I haven't run it.
import 'dart:html';
String encodeMap(Map data) {
return data.keys.map((k) {
return '${Uri.encodeComponent(k)}=${Uri.encodeComponent(data[k])}';
}).join('&');
}
loadEnd(HttpRequest request) {
if (request.status != 200) {
print('Uh oh, there was an error of ${request.status}');
return;
} else {
print('Data has been posted');
}
}
main() {
var dataUrl = '/registrations/create';
var data = {'dart': 'fun', 'editor': 'productive'};
var encodedData = encodeMap(data);
var httpRequest = new HttpRequest();
httpRequest.open('POST', dataUrl);
httpRequest.setRequestHeader('Content-type',
'application/x-www-form-urlencoded');
httpRequest.onLoadEnd.listen((e) => loadEnd(httpRequest));
httpRequest.send(encodedData);
}