cross domain reading remote url using Jquery/Ajax/Json - json

I have an HTML page from which i want to read a remote webpage which is at http://xtremeinspection.com/new2you4kids/app/android/get_product_size.php?productID=113
The webpage returns a value depending on the Query string parameter passed that is the productID
My question is since its cross domain reading data which is the best method to use Jquery/Ajaz/Json or mix of all these ?
I have searched it on Google but i cant find example of reading and displaying the data in a DIV .
I am using this code but it doesnt display anything
<script type="text/javascript"src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
<script>
$(document).ready(function(){
$.getJSON('http://xtremeinspection.com/new2you4kids/app/android/get_product_size.php?productID=113', function(data){
$.each(data, function(i, tweet){
$('#tweets').append('<li>' + tweet.text + '</li>');
alert(tweet.text);
});
});
});
</script>
<ul id="tweets"></ul>

A basic example like this should help you get started:
$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?",
{
tags: "gulmarg",
tagmode: "any",
format: "json"
},
function(data) {
$.each(data.items, function(i,item){
$("<img/>").attr("src", item.media.m).appendTo("#images");
if ( i == 5 ) return false;
});
});
DEMO

Related

Can we send data from mongoDB to HTML?

I am working on a Mini Project where I have stored data coming from a form in my DataBase(MongoDB). Now I want to fetch data from MongoDB and want to add it to HTML(as a list) to display on the webpage.
I wanted to do this without using ejs or any other tool. Is this possible? If yes,then how?
(I have used Expressjs to create the server)
You would have to javascript in order to manipulate DOM elements on the page.
(see. https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Client-side_web_APIs/Manipulating_documents)
You can fetch the data in your html then add it to your page by manipulating the dom.
This is might help you:
<script type='text/javascript'>
$(function(){
$.ajax({
url: 'http://localhost:28017/local/students',
type: 'get',
dataType: 'jsonp',
jsonp: 'jsonp',
success: function (data) {
console.log('success', data);
}
}).done(function(){
let output = '<div>'
$.each(data, function(key, data){
output += '<p>' + data.score + '</p>';
});
output += '</div>'
$('#list').html(output);
});
});
</script>
Also this response might be helpful:
REST AJAX request to mongoDB
Since you have mentioned you are using Expressjs, I believe you are also using an ODM like mongoose. Hence, you should create an api in your backend that fetches the data from MongoDB (see your ODM's documentation for it) and send request to that api from your front end, whose response should trigger DOM manipulation.
Here are some resources that might help you:
https://medium.com/swlh/how-to-build-simple-restful-api-with-nodejs-expressjs-and-mongodb-e59595091640
https://medium.com/#ingridf/flow-of-fetch-and-dom-manipulation-454af047b6c
https://developer.mozilla.org/en-US/docs/Learn

What is the easiest way to make autocomplete using CSHTML

For like few days I have been trying to make autocomplete in ASP.NET for my project. wherever I look their project are in .ashx or .aspx file, while mine is in cshtml. This is a work project so I cant change the file format. You might see how I have already asked this question in the past with my attempts but it doesn't work. I have seen few videos online which they use controllers but for some reason my project doesn't have controller for that part (_search). If anyone could give me hints or tip how to make easiest autocomplete which connects to database it would mean the world to me. Thanks in advance :D <3
Well, you can try this Assuming you are searching country in controller.
public JsonResult SearchCountry(string query){
var dbResult=_context.Countries.Where(x=>x.Name.ToLower().StartWith(query.ToLower())).Take(20).ToList();
return Json(dbResult);
}
In CSHTML
<input type='text' id='autocomplete' >
Javascript:
$( "#autocomplete" ).autocomplete({
source: function( request, response ) {
// Fetch data
$.ajax({
url: "/demo/SearchCountry",
type: 'get',
data: {
query: request.term
},
success: function( data ) {
response( data );
}
});
},
select: function (event, ui) {
// Set selection
$('#autocomplete').val(ui.item.name); // In MVC5 change name to Name
return false;
}
});

Transmitting a JSON-Object to a new HTML side

Hello guys i have a big problem, which i somehow cant fix. I am having some JSON- Objects which i am giving out with a table, this part works perfectly fine. But than i would like to have a button or link that posts one of this JSON- Objects (the ID) to a new .html page. In this new .html page i would like to use the ID in Javascript code.
Does anybody know if there is a way how i can accomplish this and if yes how can i do it?
I tried to post it via the php _get methode but it just doesnt work it tells me that there is an " Uncaught TypeError: Cannot read property 'value' of null"
My JS-Code looks like this:
function dataRequest() {
var output = $('#output').text('Loading data...');
$.ajax({
url: 'http://test/html/getmeineFahrten.php',
dataType: 'jsonp',
jsonp: 'jsoncallback',
timeout: 5000,
success: function(data, status){
output.empty();
var ort ='<table border="dashed" width="30%">'
$.each(data, function(i,item){
var ServerDatum = item.abfahrt
var Datumonly = ServerDatum.substring(0,4) + ServerDatum.substring(5,7) + ServerDatum.substring(8,10);
var calcDatum = Datum - Datumonly
if(item.user_user_id == userID){
if(calcDatum < 0){
ort += '<tr>'+'<td>'+item.abfahrt+'</td>'
+ '<td>'+item.rueckfahrt+'</td>'
+ '<td>'+item.StartOrt+'</td>'
+ '<td>'+item.Zielort+'</td>'+'<td>'+'<form action="http://test/html/meineFahrten_Karte.html?FahrtenID= + item.fahrten_id" method="get"><input type="submit" value="Karte">'+'</form>'+'</td>'+'</tr>';
}}
});
ort +='</table>';
output.append(ort);
},
error: function(){
output.text('There was an error loading the data.');
navigator.notification.confirm(
'Something went wrong. Would you like to retry?',
yourCallback,
'Error',
'No,Yes'
);
}
});
}
You can't access URL parameters unless you create your own function to do so. Unfortunately, there is no native function for this yet, however, user Quentin answers this question in greater detail and provides a function for getting URL parameters.
How to get the value from the GET parameters?

Get request within page

I've been looking around, but I'm not quite sure what to search for...
I want to have a webpage send a Get request to a python script when you first open the page, maybe with the option to refresh it with a button. Is there a way to send a request ("script.py?var=test") and display the results within the page?
What I tried to use earlier: (didn't work..)
Am I doing something stupid? I don't know anything about JavaScript
<p>Highscores:</p>
<p id='scores'>text</p>
<input type='button' onclick='changeText()' value='Change Text'/>
<script type="text/javascript">
function changeText(){
var request = new XMLHttpRequest();
request.open("GET", "../../cgi-bin/highScore.py?scoreMethod=load&game=ulama", true)
request.onreadystatechange = function(){
var done = 4, ok = 200;
if (request.readyState == done && requeset.status == ok){
document.getElementById('scores').innerHTML = request.responseText;
}
};
request.send();
}
</script>
Also, should I have the python script return a full page with the header and all? or just the relevant section?
Use a Jquery call in this case to clean up your code a little bit.
Also in this case you should use a post because of the nature of your 'beast' :)
function changeText(){
$.ajax({
method : "POST",
URL : "../../cgi-bin/highScore.py",
data : {
"scoreMethod" : "load",
"game" : "ulama"
},
success : function(data) {
$("#scores").html(data);
}
});
}
I'd also look into JSON and jquery being returned as its probaly going to be easier in the long term (Though ive never played with python.
why not using jquery for doing this?
$('#scores').load('../../cgi-bin/highScore.py?scoreMethod=load&game=ulama', function(responseText, textStatus) {
alert(textStatus);//check here whether textStatus equals 'success' or something else (maybe an error)
});

trying to understand jsonp with the flickr example

I'm trying to get my head around how I can make json request to a json file stored on my server from jsfiddle.
html:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div id="images">
</div>
</body>
</html>
jquery:
$.getJSON("http://www.shopsheep.com/groupon/json/test.json?jsoncallback=?", function(data) {
$.each(data.items, function(i, item) {
$("<img/>").attr("src", item.media.m).appendTo("#images");
if (i == 0) {
return false;
}
});
});
$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?format=json&jsoncallback=?", function(data) {
$.each(data.items, function(i, item) {
$("<img/>").attr("src", item.media.m).appendTo("#images");
if (i == 0) return false;
});
});
I downloaded the flicker json file and uploaded it to my server as test.json. If I paste it in the browser it returns just as the flicker file.
However when I try to display the image only the original flicker example is working? Any idea why this is the case?
http://jsfiddle.net/stofke/DJQ5g
Ok I have found out how to do this. The getJSON function adds a random
named callback functionname to jsoncallback=? something like this
jQuery160188050875203142_1309437718540&_=1309437718551
In order to wrap your json file with this callbackfunction you need of course to know the name of this function, so if you convert your jsonfile into a php file than you can get the callbackfunctionname like this:
<?php echo $_GET["jsoncallback"];?>(
ADD JSON CONTENT HERE
)
This php file will get the name of the callbackfunction via a GET variable and wraps the json content with it. This way it works fine.
Your JSON file missed function name. It should start with function name.
If you see here http://api.flickr.com/services/feeds/photos_public.gne?format=json, it starts with jsonFlickrFeed.
Your JSON should be like this:
callback({
"title": "Uploads from everyone",
"link": "http://www.flickr.com/photos/",
"description": "",
"modified": "2011-06-29T21:43:16Z",
"generator": "http://www.flickr.com/",
"items": [
{....
Maybe you need to understand more about JSONP. http://en.wikipedia.org/wiki/JSONP