Hi i am having issues retrieving the json data from my web services using a Promise and AJAX requests fetch API, the code fails on
return response.json();
The console shows this error
ajaxPromisesTask2.html:47 GET ***/hits.php?artist=dav 401 (Authorization Required)
but i have many working scripts that connect to the same webservice and retrieve the Json data, but this is my first Promise version using the inbuilt API. what am i doing wrong ?
link to Json webservice:
Json file
FYI, I have tried Json.parse(response);
and JSON.stringify(response);
<script type='text/javascript'>
function ajaxrequest()
{
var a = document.getElementById("artist").value;
fetch('/hits.php?artist=' + a).then(ajaxresponse).
then(showJSONResults).catch(ajaxerror);
}
function ajaxresponse(response)
{
return response.json();
}
function ajaxerror(code)
{
alert('error; ' + code);
}
function showJSONResults(jsonData)
{
var output = "<table style='width:100%'> <tr> <th>Title</th> <th>Artist</th> <th>Chart position</th> </tr>";
for(var i=0; i < jsonData.length; i++)
{
output = output + ' <tr> <td>' + jsonData[i].title + '</td><td>' + jsonData[i].artist + '</td><td>' + jsonData[i].chart + '</td></tr>';
}
output = output + "</table>";
document.getElementById("response").innerHTML = output;
}
</script>
</head>
<body>
<div id="info">
<input id="artist" /> <br/>
<input type="button" value="Search" onclick="ajaxrequest()" />
<div/>
<div id="response"><div/>
By default, fetch won't send or receive any cookies from the
server, resulting in unauthenticated requests if the site relies on
maintaining a user session (to send cookies, the credentials init
option
must be set).
Source: Using Fetch - Web APIs | MDN
You have to supply an object with a credentials property whose value is set to same-origin to submit the authorization cookie.
function ajaxrequest()
{
var a = document.getElementById("artist").value;
fetch('/hits.php?artist=' + a, { credentials: 'same-origin' })
.then(ajaxresponse)
.then(showJSONResults)
.catch(ajaxerror);
}
Related
I am trying to send form data to another PHP file.
its working but once data is submitted the page is not redirecting to that specific page.
Like it work in php.
function codeverify() {
var code=document.getElementById('verificationCode').value;
coderesult.confirm(code).then(function (result) {
if (confirm("OTP Confirmed!")) {
var number=document.getElementById('number').value;
$.post("confirm-phone-reg.php", { status: number }); //send data to file
//document.location.href = "http://localhost/test/new/confirm-phone-reg.php";
} else {
window.location.href = "http://localhost/test/new/try-again.php";
};
var user=result.user;
console.log(user);
}).catch(function (error) {
alert(error.message);
});
}
How can I make sure when I send data to the confirm-phone-reg.php the post data and my page will be opened there.
I searched too much on internet but failed to search for answer.
I hope you guys will help me.
var number = document.getElementById('number').value;
var url = 'register.php';
var form = $('<form action="' + url + '" method="post">' + '<input type="text" name="phone" value="' + number + '" />' + '</form>');
$('body').append(form);
form.submit();
For those who are also stuck like this.
This is the easiest way to send data to another file and also redirect at the same time.
For some reason the script does not run, or return answer.
The console is nothing.
Trying to get an answer to yandex.transtale site (https://tech.yandex.com/translate/doc/dg/reference/translate-docpage/)
Code: http://jsbin.com/jolijep/edit?html,js,console,output
var app = angular.module('jsbin', []);
app.controller('DemoCtrl', function($scope, $http) {
var url = "https://translate.yandex.net/api/v1.5/tr.json/translate";
keyAPI = "trnsl.1.1.20130922T110455Z.4a9208e68c61a760.f819c1db302ba637c2bea1befa4db9f784e9fbb8";
var vm = this;
$scope.SendData = function() {
// тут данные
var textApi = 'Hello';
var langApi = 'en-ru';
var text1 = 'Hello';
var data = "key=" + keyAPI + "&text=" + textApi + "&lang=" + langApi;
$http.post(url, data)
.success(function(data, status, headers, config) {
vm.data = response.data;
$scope.PostDataResponse = data;
console.log(data);
})
.error(function(data, status, header, config) {
$scope.ResponseDetails = "Data: " + data +
"<hr />status: " + status +
"<hr />headers: " + header +
"<hr />config: " + config;
});
};
});
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Angular JS</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="weather.js"></script>
</head>
<body ng-app="jsbin">
<div ng-controller="DemoCtrl as vm">
<script src="weather.js"></script>
<button ng-click="SendData()">Send</button>
<br>Data: {{PostDataResponse}}
<br>{{vm.data}} {{vm.PostDataResponse}} Data: {{scope.PostDataResponse}} {{vm.data}}
</div>
</body>
</html>
If you look at the Yandex translate API reference, it has asked you to pass the information for the request you are making in the form of the params(parameter). These parameters are to be appended to the request URL.
Other ways of getting information from an API with a POST request is to pass information in the form of the body of that request.
But the Yandex translate API with the POST request is asking for the information attached to the url.
var data = "key="+keyAPI+"&text="+textApi+"&lang="+langApi
this data variable should be getting appended to the url variable when the POST request is made to the API. But,
$http.post(url, data)
Invoking $http method makes the data interpreted as the body of the post request instead of appending the data variable to url while making the call.
A much cleaner and proper implementation for $http API of the AngularJS would be to put all you parameters inside an object where the keys are the parameter type and values are the parameter values.
var params = {
key: keyAPI,
text:textApi,
lang:langApi
}
Now in the params object, you are hold all the information you wanted to pass while making the request.
Secondly, you need to the modify the $http request so that it knows what params are to be appended to the url. I am using more basic $http method instead of $http.post method,I will clearly mention what should be the base url, type of method for the HTTP request and lastly, the params that are to passed with the request to the API.
$http({
url: url,
method: 'POST',
params: params
})
.success(function(data,headers,status,config){
$scope.PostDataResponse = data;
vm.data = data;
console.log(data);
})
.error(function(data,headers,status,config){
$scope.ResponseDetails = "Data: " + data +
"<hr />status: " + status +
"<hr />headers: " + header +
"<hr />config: " + config;
});
Another thing which was wrong in your code was the initialization of $scope.PostDataResponse
$scope.PostDataResponse = response.data; //You are not getting any argument named response by the success function call
Correct way to do it will be
$scope.PostDataResponse = data;
Now if you run the code with the modification it should run pretty fine.
If everything is done correctly, then in the developer console you would find an object logged after the success of the request.
Object with the success of the call
In your webpage also, you would see the same object.
I create a server with node.js. Then I build an http form on the specific address. (I'm going do different forms on different addresses).
I want to receive data from the user in specific field. (I'll give them different ID's).
But I can't receive it with document.getElementById() because DOM is undefined in node.js.
Can you advise a specific module for solving this problem, or some useful method?
var server = new http.Server(function(req, res){
if (req.url=='/') {
res.statusCode=200;
auth(res);
res.end();
} else {
res.statusCode=404;
res.end("Page not found");
}
})
function auth(res) {
res.writeHead(200, {
'Content-Type': 'text/html',
});
var body = '';
body= '<form action="/" method="post">'+
'<thead>Connection details </thead>' +
'<br>'+
'<textarea id ="text" name="text" rows="1" cols="50"></textarea><br>'+
'<input value="localhost" id="host">Host</input><br>' +
'<input value="root" id="user">User </input><br>' +
'<input value="********" id="pass">Pasword </input><br>' +
'<input type="submit" value="Connect" id="scheme"></input><br></body></html>'
var toWrite = header + body;
res.write(toWrite);
}
Set up as your project is now, you will receive the parameters from the form in req.body. I recommend looking into express and body-parser, to parse incoming data.
i want to parse remote JSON file using JQuery, YQL(you know cross domain proble, so yql is best)
but i dont know what is misssing in this code ?
index.html
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>untitled</title>
<style type="text/css">
body { text-align: center; }
</style>
</head>
<body onLoad="gova();">
<div id="container">
</div>
<table id="userdata" border="1">
<thead>
<th>First Name</th>
<th>Last Name</th>
<th>Email Address</th>
<th>City</th>
</thead>
<tbody></tbody>
</table>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript" src="cross-domain-requests.js"></script>
<script type="text/javascript">
function gova() {
var path = $('http://mapleleafrealities.com/jsondata.php').val();
requestCrossDomain('http://mapleleafrealities.com/jsondata.php', function(results) {
$('#container').html(results);
});
return false;
}
</script>
</body>
</html>
cross-domain-requests.js
// Accepts a url and a callback function to run.
function requestCrossDomain( site, callback ) {
// If no url was passed, exit.
if ( !site ) {
alert('No site was passed.');
return false;
}
// Take the provided url, and add it to a YQL query. Make sure you encode it!
var yql = 'http://query.yahooapis.com/v1/public/yql?q=' + encodeURIComponent('select * from html where url="' + site + '"') + '&format=xml&callback=?';
// Request that YSQL string, and run a callback function.
// Pass a defined function to prevent cache-busting.
$.getJSON( yql, cbFunc );
function cbFunc(data) {
// If we have something to work with...
if ( data.results[0] ) {
// Strip out all script tags, for security reasons.
// BE VERY CAREFUL. This helps, but we should do more.
data = data.results[0].replace(/<script[^>]*>[\s\S]*?<\/script>/gi, '');
// If the user passed a callback, and it
// is a function, call it, and send through the data var.
if ( typeof callback === 'function') {
callback(data);
}
}
// Else, Maybe we requested a site that doesn't exist, and nothing returned.
else throw new Error('Nothing returned from getJSON.');
}
}
i want to display unformatted data in to table ? how ?
plese give solution where is the probleam or what is missing ?
thanks in advance !! :)
i want to parse remote JSON file using JQuery, YQL
You say that you want to parse some JSON, but your YQL query asks for HTML and the YQL URL asks for an XML response!
var yql = 'http://query.yahooapis.com/v1/public/yql?q=' + encodeURIComponent('select * from html where url="' + site + '"') + '&format=xml&callback=?';
If you really want to work with JSON, change that line to something like below. It a) uses the json table (since that is the nature of the content on the site) and b) tells YQL to return JSON because you're using the jQuery.getJSON() function!
var yql = 'http://query.yahooapis.com/v1/public/yql?'
+ 'q=' + encodeURIComponent('select * from json where url=#url')
+ '&url=' + encodeURIComponent(site)
+ '&format=json&callback=?';
Now that YQL returns JSON, you can get at the json object via data.query.results.json which then contains an array of userdata objects. See a fuller example, based on your code, which takes the JSON response from YQL and populates the table rows using jQuery.template()
http://jsbin.com/umuri5/edit
Two thins:
1)The json being returned in not well formed. For some reason the userdata element is prefixed with "\n , hence making the element userdata unavailable,
2)You should be using data.results[0].userdata to iterate over each user. i.e:
$.each(data.results[0].userdata, function(i,user){
var tblRow =
"<tr>"
+"<td>"+user.first+"</td>"
+"<td>"+user.last+"</td>"
+"<td>"+user.email+"</td>"
+"<td>"+user.city+"</td>"
+"</tr>"
$(tblRow).appendTo("#userdata tbody");
});
I have a database at zoho creator. They feed me a json of the database content. I have trouble to parse and display that data with jquery or php or in html
Question : So how do I capture json data, and save (convert) it to file as XML. With the xml file I can parse it with jquery xpath easily... the "file" will be a local database, as a backup (if saved)
anybod have clue on that ?
as request.. here is the link for the query -link-
getting a way to display data from var i need is the minimum i must have !
like prod_categorie or prod_nom
note :
i can get help with any tutorial on
how to get xml data from zoho
any json to xml converter (jquery)
out there ?????
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
</head>
<body>
<div id="Liste_output"></div>
<script type="text/javascript">
jQuery.ajax({
url: "http://creatorexport.zoho.com/marcandremenard/application-lemieux/json/Liste_produits_View1/7GWhjVxYeNDePjPZnExCKy58Aqr21JX2hJEE6fAfgfkapEQnRjRd5RUy8wdjKuhmFEhJR9QRsBCUBjACAdSgmJNQSvxMt6geaMNC/",
dataType: "json",
success: function(data) {
var Liste_div = jQuery("#Liste_output");
var Liste_data = data["Liste_des_produits1"];
for (var i=0; i<Liste_data.length; ++i) {
var prod_i = Liste_data[i];
Liste_div.append('<div>' +
'<div>Nom: <span>' + prod_i["prod_nom"] + '</span></div>' +
'<img src="/images/prod/'+ prod_i["prod_photo"] +'"/>' +
'<div>Description: <span>' + prod_i["prod_desc"] + '</span></div>' +
'<div>Ingredient: <span>' + prod_i["prod_ingredient"] + '</span></div>' +
'<div>Odeur: <div class="odeur_cls"></div></div>' +
'<div>Certification: <div class="cert_cls"></div></div>' +
'</div>');
var odeur_data = prod_i["prod_odeur"];
for (var j=0; j<odeur_data.length; ++j) {
jQuery('#Liste_output odeur_cls').eq(j).append('<span>' +
odeur_data[j] + '</span>' + (j<odeur_data.length-1 ? ', ' : ''));
}
var cert_data = prod_i["prod_certification"];
for (var k=0; k<cert_data.length; ++k) {
jQuery('#Liste_output cert_cls').eq(k).append('<div>' + cert_data[k] + '</div>');
}
}
}
});
</script>
</body>
</html>
This will not work from a local file. The HTML must be served from the same domain as the database query, that is, it must be served from http://creatorexport.zoho.com (you can put it in the app subfolder)
– OR –
You must read the zoho docs and find out how to do a "callback" (sometimes called "JSONP"). Usually this is done by adding something like ?callback=data to the end of the URL.
Firstly, Javascript has no file-output capability. The best it can do is send data back to a server for processing there -- so the "capture json data, and save it to file as XML" idea is out.
What problems in particular are you having with using JSON? As it gets converted to a native Javascript object, I find it quite easy to work with myself. Though, I can see that if you wanted to use XPath to query it, JSON is no help. You should still be able to get to whatever data you need, but it might be a bit more verbose.
In your example JSON:
{"Liste_des_produits1":[{"Added_Time":"28-Sep-2009 16:35:03",
"prod_ingredient":"sgsdgds","prod_danger":["sans danger pour xyz"],"prod_odeur"..
You could access the prod_danger property like this:
$.getJSON(url, function(data) {
var danger = data.List_des_produits1[0].prod_danger;
});
If you are having trouble getting the right path to a property, Firebug is a great help with this. Just call this:
$.getJSON(url, function(data) {
console.log(data);
});
...and then you can browse through its properties in a tree-structure.
There are jQuery pluggins for such convertion, for example json2xml.