unable to fetch json data from ip url [duplicate] - javascript

This question already has answers here:
jQuery and CORS
(3 answers)
Closed 8 years ago.
hey guys i am unable to fetch cross domain json data here is my code below which doesn't work
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery.getJSON demo</title>
<style>
img {
height: 100px;
float: left;
}
</style>
<script src="js/jquery.min.js"></script>
</head>
<body>
<div id="images"></div>
<script>
(function() {
var furl= "http://192.168.2.36/gemadmin/display.php?callback=?";
$.getJSON( furl)
.done(function( data ) {
console.log(data);
});
})();
</script>
</body>
</html>
and this code works properly since its just localhost
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery.getJSON demo</title>
<style>
img {
height: 100px;
float: left;
}
</style>
<script src="js/jquery.min.js"></script>
</head>
<body>
<div id="images"></div>
<script>
(function() {
var furl= "http://localhost/gemadmin/display.php";
$.getJSON( furl)
.done(function( data ) {
console.log(data);
});
})();
</script>
</body>
</html>
why is the first version not working ? and what is the solution to make it work?
server code(display.php)
<?php
include 'config.php';
$sql = "select * from menu;";
$result= $mysqli->query($sql);
$data = $result->fetch_all( MYSQLI_ASSOC );
header('Content-Type: application/json');
echo json_encode( $data );
?>
The answer:
Found the answer instead of $.getJSON() use $.get and do a json parse
example
jQuery.getJSON demo
img {
height: 100px;
float: left;
}
<div id="images"></div>
<script>
(function() {
var furl= "http://localhost/gemadmin/display.php?callback=?";
$.get( furl)
.done(function( data ) {
var obj = JSON.parse(data);
console.log(obj);
});
})();
</script>
</body>
</html>
don't forget to add 'callback=?'to your url

Use Like This
$.ajax({
url: "URL",
type: "POST",
contentType: "application/json;charset=utf-8",
data: JSON.stringify("YOUR JSON"),
dataType: "json",
success: function (response) {
alert(response);
},
error: function (x, e) {
alert('Failed');
alert(x.responseText);
alert(x.status);
}
});

<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$.getJSON("demo_ajax_json.js",function(result){
$.each(result, function(i, field){
$("div").append(field + " ");
});
});
});
});
</script>
</head>
<body>
<button>Get JSON data</button>
<div></div>
</body>
</html>
demo_ajax_json.js
{
"firstName": "John",
"lastName": "Doe",
"age": 25
}
A simple example

Related

why Ajax code not trigger on click or load

Thanks for you all.
I am new in coding MVC, and I am trying to code a page that will create and as parent and child loop, using data from JSON (MenuHandler.ashx), the JSON data is tested and it's ok, but the Ajax was not working.
for your kind note: the Alert working before and after Ajax
this is my VIEW page:
<script type="text/javascript">
$(document).ready(function () {
$("#testaj1").click(function () {
alert ("test22")
$.ajax({
url: 'MenuHandler.ashx',
method: 'get',
dataType: 'json',
success: function (data) {
buildMenu($('#menu'), data)
$('#menu').menu();
}
});
alert("test33")
});
function buildMenu(parent, items) {
$.each(items, function () {
var li = $('<li>' + this.Name + '</li>');
li.appendTo(parent);
if (this.List && this.List.length > 0) {
var ul = $('<ul></ul>');
ul.appendTo(li);
buildMenu(ul, this.List);
}
})
}
})
</script>
<link href="~/Content/MyCSS/MyCSS.css" rel="stylesheet" />
#model IEnumerable<pedigree.Models.pedigree1>
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
<script src="~/Scripts/jquery-3.5.1.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
<title>Index</title>
</head>
<body>
<p>
#Html.ActionLink("Create New", "Create")
</p>
<form>
<button id="testaj1" type="button" >test</button>
<div class="tree">
<ul id="menu">
</ul>
</div>
</form>
Thanks for everyone as Alejandro Coronado said, the issue was in the handler.ashx file, I don’t now why wasn’t worked, but when I use instead json result action
The Ajax worked and the results came according to my expectations
Thanks everyone
The most common reason is the controller that you are pointing, maybe the controler uri is not correct, also be sure that your controller is returning a JSON.

Pie chart creating from JSON Data in Javascript

I am new in PHP and JavaScript, i need to create a pie chart using JSON data which will be get from the URL. The JSON data is :
[
{"Domain":"Artificial Intelligence","Count":"46"},
{"Domain":"Data Architecture","Count":"21"},
{"Domain":"Data Science","Count":"50"},
]
The code :
<!DOCTYPE html>
<html>
<head>
<title></title>
<link href="http://cdn-na.infragistics.com/igniteui/2018.1/latest/css/themes/infragistics/infragistics.theme.css" rel="stylesheet" />
<link href="http://cdn-na.infragistics.com/igniteui/2018.1/latest/css/structure/infragistics.css" rel="stylesheet" />
<script src="http://ajax.aspnetcdn.com/ajax/modernizr/modernizr-2.8.3.js">
</script>
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="http://code.jquery.com/ui/1.11.1/jquery-ui.min.js"></script>
<script src="http://cdn- na.infragistics.com/igniteui/2018.1/latest/js/infragistics.core.js"></script>
<script src="http://cdn-na.infragistics.com/igniteui/2018.1/latest/js/infragistics.dv.js"></script>
</head>
<body>
<?php
# Reading JSN Data from URLS
$jsn_data =
file_get_contents("http://localhost:9080/Badges/reporting/badge_json.php");
<div id="chart"></div>
<script type="text/javascript">
$("#chart").igPieChart({
width: "435px",
height: "435px",
dataSource: result,
dataValue: "count",
dataLabel: "Domain",
labelsPosition: "bestFit"
});
});
<script>
</body>
s</html>
But this code does not work. please tell me how do this ?
dataLabel: "Badge_SubDomain" doesn't exist in your data source.
Maybe try something like ...
$("#chart").igPieChart({
width: "435px",
height: "435px",
dataSource: result,
dataValue: "count",
dataLabel: "Domain",
labelsPosition: "bestFit"
});
});
Fix these:
JSON property Count is a string, not an integer
The code is broken, it needs to be fixed
The variable result is not defined anywhere in the <script> tag
The JavaScript snippet is inside <?php/> tag, move it outside
here's the fixed code:
index.php:
<!DOCTYPE html>
<html>
<head>
<title></title>
<link href="http://cdn-na.infragistics.com/igniteui/2018.1/latest/css/themes/infragistics/infragistics.theme.css" rel="stylesheet"></script>
<link href="http://cdn-na.infragistics.com/igniteui/2018.1/latest/css/structure/infragistics.css" rel="stylesheet"></script>
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="http://code.jquery.com/ui/1.11.1/jquery-ui.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/modernizr/modernizr-2.8.3.js"></script>
<script src="http://cdn-na.infragistics.com/igniteui/2018.1/latest/js/infragistics.core.js"></script>
<script src="http://cdn-na.infragistics.com/igniteui/2018.1/latest/js/infragistics.dv.js"></script>
</head>
<body>
<div id="chart"></div>
<script type="text/javascript">
$.ajax({type:"GET", url: "badge_json.php", success: function(data) {
$("#chart").igPieChart({
width: "435px",
height: "435px",
dataSource: data,
dataValue: "Count",
dataLabel: "Domain",
labelsPosition: "bestFit"
});
}});
</script>
</body>
</html>
and badge_json.php:
<?php
header('Content-type: application/json');
// your data goes here
$data = array(
['Domain' => 'Artificial Intelligence', 'Count' => 46],
['Domain' => 'Data Architecture', 'Count' => 21],
['Domain' => 'Data Science', 'Count' => 50]
);
echo json_encode($data);
?>

Ajax don't show me the selected data from PHP

<!DOCTYPE HTML>
<html>
<head>
<title>Scroll Pagination</title>
<link rel="stylesheet" type="text/css" href="style.css" />
<script src="jquery.js"> </script>
<script type="text/javascript">
$(document).ready(function(){
$.ajax({
type: "GET",
url: "ajax.php",
data:{
'offset':0,
'limit':5
},
succes:function(data)
{
$('body').append(data);
}
});
});
$(window).scroll(function(){
if($(window).scrollTop() >= $(document).height() - $(window).height()){
$.ajax({
type: "GET",
url: "ajax.php",
data: {
'offset':0,
'limit':3
},
succes:function(data)
{
$('body').append(data);
}
});
}
});
</script>
<style type="text/css">
.blog-post{border-bottom: solid 4px black; }
.blog-post h1{font-size:40px;}
.blog-post p{font-size:30px;}
</style>
</head>
<body>
</body>
</html>
Here is the html and ajax code.
And here is the PHP code
<?php
$con = mysqli_connect('localhost', 'root', '', 'table') or die();
print_r($_GET['limit']);
if(isset($_GET['offset']) && isset($_GET['limit'])){
$limit=$_GET['limit'];
$offset=$_GET['offset'];
$result = mysqli_query($con, "SET NAMES utf8");
$data = mysqli_query($con, "SELECT * FROM portf LIMIT {$limit} OFFSET {$offset}");
while ($portf = mysqli_fetch_array($data)){
echo '<div class="blog-post"><h1>'.$portf['title'].'</h1><p>'.$portf['category'].'</p></div>';
?>
<?php }}else{echo "fail";} ?>
I have no idea why in the index I can't see nothing what can I do to solve this problem? I saw this example on youtube and is working but..when I'm trying to do the same nothing appears.
Edit:
Statuts in network
There is syntax error in your code at time of ajax call due to which it does not enter in success.
Change
succes:function(data)
To
success:function(data)
It should be "success".

Sending value from jquery to php not working

I'm learning jquery and ajax. I have tried the following code, to post value to php from jquery. But it doesn't work. Can someone tell me what mistake am I doing here, and what is the solution.
I just want value1 to be printed by the PHP server side code, with that value being sent by the Jquery based client side code.
<html>
<head>
<title>Practice 1</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
</head>
<?php
if (isset($_POST['data'])) {
$data = $_POST['data'];
print( "data is: $data" );
return;
}
?>
<body onload='process()'>
<script type="text/javascript">
$.post(window.location, {'data': "value1"}, function (data) {
$('#response').text(data);
});
</script>
</body>
</html>
You're trying to output to an element that doesn't exist '#response', also the process function is missing.
Try something like this:
<html>
<head>
<title>Practice 1</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js">
</script>
</head>
<?php
if (isset($_POST['data'])) {
$data = $_POST['data'];
print( "data is: $data" );
return;
}
?>
<body>
<div id="response"></div>
<script type="text/javascript">
$.post(window.location, {'data': "value1"}, function (data) {
$('#response').text(data);
});
</script>
</body>
</html>

How to filter xml data according to the search?

<pages>
<link>
<title>HTML a tag</title>
<url>http://www.w3schools.com/tags/tag_a.asp</url>
</link>
<link>
<title>HTML br tag</title>
<url>http://www.w3schools.com/tags/tag_br.asp</url>
</link>
<link>
<title>CSS background Property</title>
<url>http://www.w3schools.com/cssref/css3_pr_background.asp</url>
</link>
<link>
<title>CSS border Property</title>
<url>http://www.w3schools.com/cssref/pr_border.asp</url>
</link>
<link>
<title>JavaScript Date Object</title>
<url>http://www.w3schools.com/jsref/jsref_obj_date.asp</url>
</link>
<link>
<title>JavaScript Array Object</title>
<url>http://www.w3schools.com/jsref/jsref_obj_array.asp</url>
</link>
</pages>
this is the sample xml data which i am parsing and getting the output from
SEARCH.HTML
<!DOCTYPE html>
<html>
<head>
<link
href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.js"></script>
<script>
$(document).ready(function () {
var myArr = [];
$.ajax({
type: "GET",
url: "http://localhost/category/links.xml",
dataType: "xml",
success: parseXml,
complete: setupAC,
failure: function (data) {
alert("XML File could not be found");
}
});
function parseXml(xml) {
//find every query value
$(xml).find("link").each(function () {
myArr.push($(this).find('title').text());
});
}
function setupAC() {
$("input#searchBox").autocomplete({
source: myArr,
minLength: 3,
select: function (event, ui) {
$("input#searchBox").val(ui.item.value);
$("#searchForm").submit();
}
});
}
});
</script>
</head>
<body style="font-size: 62.5%;">
<form name="search_form" id="searchForm" method="GET" action="http://localhost/search_result1.html">
<label for="searchBox">Keyword Search</label>
<input type="text" id="searchBox" name="searchString" />
<button name="searchKeyword" id="searchKeyword">Sumbit</button>
</form>
</body>
</html>
and this my search bar with auto complete feature. In it i first parse the above xml and then store the title in an array which i can use it for auto completeion feature. and on clicking the submit i redirect the page to another html page where i show all the results.
the code for the second html page is as given below..
RESULT.HTML
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script src="1.7.2.jquery.min.js" type="text/javascript"></script>
<script type="text/javascript" language="javascript">
$(document).ready(function () {
$("#dvContent").append("<div></div>");
$.ajax({
type: "GET",
url: "http://localhost/category/link.xml",
dataType: "xml",
success: function (xml) {
$(xml).find('link').each(function () {
var stitle = $(this).find('title').text();
var surl = $(this).find('url').text();
$("<li></li>").html(stitle + ", " + surl).appendTo("#dvContent div");
});
},
error: function () {
alert("An error occurred while processing XML file.");
}
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div id="dvContent">
</div>
</form>
</body>
</html>
but what i want is to show only the title and url of the searched term. In this i am getting the entire xml as output. So in there a way by which i can show only the title and url of the searched term.
that is i get the output in result.html as
. HTML a tag, http://www.w3schools.com/tags/tag_a.asp
. HTML br tag, http://www.w3schools.com/tags/tag_br.asp
on searching for the term HTML in the search in search.html
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script src="1.7.2.jquery.min.js" type="text/javascript"></script>
<script type="text/javascript" language="javascript">
$(document).ready(function () {
$("#dvContent").append("<div></div>");
var searchValue = $('#searchBox').val(); // Here you get the search text
$.ajax({
type: "GET",
url: "http://localhost/category/link.xml",
dataType: "xml",
success: function (xml) {
$(xml).find('link').each(function () {
var stitle = $(this).find('title').text();
var surl = $(this).find('url').text();
if (searchValue === stitle) { // Only append those if search text matches with title
$("<li></li>").html(stitle + ", " + surl).appendTo("#dvContent div");
}
});
},
error: function () {
alert("An error occurred while processing XML file.");
}
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div id="dvContent">
</div>
</form>
</body>
</html>

Categories

Resources