How to get Json Data via ajax in javascript? - javascript

i have trying to get json data via ajax in javascript . but i could not get the updated data from json while clicking the update button. Json data url also working correctly.
Mentioned below code:
<!DOCTYPE html>
<html>
<head>
<meta content="text/html; charset=ISO-8859-1" http-equiv="content-type">
<script type="application/javascript">
function loadJSON() {
var data_file = "http://www.tutorialspoint.com/json/data.json";
var http_request = new XMLHttpRequest();
try {
// Opera 8.0+, Firefox, Chrome, Safari
http_request = new XMLHttpRequest();
} catch (e) {
// Internet Explorer Browsers
try {
http_request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
http_request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
http_request.onreadystatechange = function () {
if (http_request.readyState == 4) {
var jsonObj = JSON.parse(http_request.responseText);
alert(jsonObj.name);
document.getElementById("Name").innerHTML = jsonObj.name;
document.getElementById("Country").innerHTML = jsonObj.country;
}
}
http_request.open("POST", data_file, true);
http_request.send();
}
</script>
<title>tutorialspoint.com JSON</title>
</head>
<body> <h1>Cricketer Details</h1>
<div id="Name">Sachin</div>
<div id="Country">India</div>
<button type="button" onclick="loadJSON()">Update Details </button>
</body>
</html>
in my above code, i have the url of json data. but while click on the update button, i could get the json data via ajax.
i could not find it out which is wrong in my code?
thanks in advance.

If you have the liberty to include the jQuery library, you can do it using $.ajax.
Use a regular web method that returns a json, and call it, like so:
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: serverpath + "/Service.asmx/GetJSON",
data: {},
dataType: "json",
success: function (data, textStatus) {
if (data.hasOwnProperty('d')) {
data = data.d;
}
var jsonObj = data; // or $.parseJSON(data); if required
},
error: function (msg) {
console.log(msg);
}
});

Related

How to get HTML source with JavaScript?

I am trying to get HTML source with JavaScript:
Why this does not work?:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
function MyGetHTML()
{
$.get("www.example.com/test1.html", function(data){
return data;
});
}
</script>
</head>
<body>
test 30.9.2015
<script>
alert(MyGetHTML());
</script>
</body>
</html>
(Below, i'm assuming that you need to get content from filen IN your source, from the same origin of your page.)
Your code doen't works because the the return of your MyGetHTML method is the get request itself, and the success callback of your request returns the data.
You could do:
function MyGetHTML(){
$.get("www.example.com/test1.html", function(data){
//alert(data);
//or use console.log() instead.
console.log(data);
});
}
And then
MyGetHTML(); //This will log your data after the succesfull request.
Further reading: https://api.jquery.com/jquery.get/
Hint on your use case:
A simple tutorial from Tuts+ on making simple ajax requests.
With pure JS:
load('test.html', function(xhr) {
document.getElementById('container').innerHTML = xhr.responseText;
});
function load(url, callback) {
var xhr;
if(typeof XMLHttpRequest !== 'undefined') xhr = new XMLHttpRequest();
else {
var versions = ["MSXML2.XmlHttp.5.0",
"MSXML2.XmlHttp.4.0",
"MSXML2.XmlHttp.3.0",
"MSXML2.XmlHttp.2.0",
"Microsoft.XmlHttp"]
for(var i = 0, len = versions.length; i < len; i++) {
try {
xhr = new ActiveXObject(versions[i]);
break;
}
catch(e){}
} // end for
}
xhr.onreadystatechange = ensureReadiness;
function ensureReadiness() {
if(xhr.readyState < 4) {
return;
}
if(xhr.status !== 200) {
return;
}
// all is well
if(xhr.readyState === 4) {
callback(xhr);
}
}
xhr.open('GET', url, true);
xhr.send('');
}
Or with jquery library
$('#container').load('test.html');
Because you're returning to the get not the function itself. Try like this:
function MyGetHTML()
{
var datum = '';
$.get("www.example.com/test1.html", function(data){
datum = data;
});
return datum;
}

Ajax won't Display on web page

I am currently trying to use a Ajax in netbeans using JavaScript and PHP file. The following code I should click the button and the contents of the php fill should appear but it doesn't. When I use firebug in firefox the response shows the full php file has returned but will not display on webpage. Why???
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<script>
function getXMLHttp() {
var xmlHttp
try {
//Firefox, Opera 8.0+, Safari
xmlHttp = new XMLHttpRequest();
}
catch (e) {
//Internet Explorer
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {
alert("Your browser does not support AJAX!")
return false;
}
}
}
return xmlHttp;
}
function MakeRequest() {
var xmlHttp = getXMLHttp();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4) {
HandleResponse(xmlHttp.responseText);
}
}
xmlHttp.open("GET", "ajax.php", true);
xmlHttp.send(null);
}
function HandleResponse(response) {
document.getElementById('ResponseDiv').innerHTML = response;
}
</script>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<input type='button' onclick='MakeRequest();' value='Use AJAX!!!!'/>
<div id='ResponseDiv'>
This is a div to hold the response.
</div>
</body>
</html>
My PHP file is
<?php
echo "This is a php response to your request!!!!!!";
?>
Apart from the fact that HTML code is barely decent, why not use jQuery?
<button id="get" onClick="return false;">jQuery get</button>
<div id="result"></div>
<script type="text/javascript">
$("#get").click(function() {
$.get( "ajax.php", function( data ) {
$( "#result" ).html( data );
});
});
</script>
PHP is server side and is not made to be run on the client side. Your response should come from a URL and not the contents of a file. Ensuring that your response contains on HTML and not PHP should lead you to your solution.
Try replacing your PHP file with
<p>This is a php response to your request!!!!!!</p>
If this enables you to show your content, you have your problem and solution.

reading .json file into javascript JSON object

I am testing whether i could read a item in a .json file into javascript JSON object and display the contents. I need to store the BIDs in the variable R1 array and display it
Code is as follows
<head>
<meta content="text/html; charset=ISO-8859-1" http-equiv="content-type">
<script type="application/javascript">
function loadJSON()
{
var data_file = "data1.json";
var http_request = new XMLHttpRequest();
try{
// Opera 8.0+, Firefox, Chrome, Safari
http_request = new XMLHttpRequest();
}catch (e){
// Internet Explorer Browsers
try{
http_request = new ActiveXObject("Msxml2.XMLHTTP");
}catch (e) {
try{
http_request = new ActiveXObject("Microsoft.XMLHTTP");
}catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
http_request.onreadystatechange = function(){
if (http_request.readyState == 4 )
{
// Javascript function JSON.parse to parse JSON data
var jsonObj = JSON.parse(http_request.responseText);
var R1 = new Array();
for(var i= 0 ; i< jsonObj.length; i++){
R1.push(jsonObj[i].BID);
document.write(R1);
}
}
}
http_request.open("GET", data_file, true);
http_request.send();
}
</script>
</body>
</html>
AND my data1.json is as follows
[ { "BID" : "4569749", }, { "BID" : "466759", }, { "BID" : "4561149", }, ]
Yes we can load Json objects, As I did in one of my JSP project. here is the code so that you can easily understand.It is calling a servlet which prepare JSON file from the DB.
$('document').ready(function(){
$.ajax({
type: 'POST',
url: 'getCities',
success: function(data) {
var response = JSON.parse(data);
var products = response['city'];
var product_html = '';
$(products).each(function(index, value){
product_html += ""+value['name']+"";
});
product_html += "";
$("#citylist").html(product_html);
}
});
});
here 'getCities' is a servlet which prepare JSON file from Data fetched from Database. It is actually populating the dropdownlist related to particular counties.
One more thing I believe the json file is incorrect. Please check the format with some json validator.

Ajax Javascript Scope Issues

I am having a javascript scope issue I want to take the responce text from the ajax call and place it into a global variable. Then process the JSON in another function here is my code.
var JSONDATA = "not gatherd";
var ajaxCalls = (function(){
var ajaxer = {
defaults:{
url:"test.php",
DirectHTML: true,
element:"#ajaxerizer"
},
setup:function(setup){
var defaulLengther = this.defaults
for (var key in defaulLengther)
{
if(setup.hasOwnProperty(key))
{
this.defaults[key] = setup[key];
}
}
if(this.defaults.DirectHTML === false)
{
if (window.XMLHttpRequest) {
this.ajaxRequester = new XMLHttpRequest();
}
if (window.ActiveXObject) {
this.ajaxRequester = new ActiveXObject("Microsoft.XMLHTTP");
}
this.ajaxRequester.open('POST', this.defaults.url, true);
this.ajaxRequester.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
this.ajaxRequester.send();
}
this.callIt();
},
callIt:function(){
if(this.defaults.DirectHTML === true)
{
$(this.defaults.element).load(this.defaults.url);
}
if(this.defaults.DirectHTML === false)
{
this.ajaxRequester.onreadystatechange = function(){
if (this.readyState == 4) {
//This is where I have trouble
alert(this.responseText);
JSONDATA = this.responseText;//This is the data I want to process and use
alert(JSONDATA);
}
}
}
}
}
return ajaxer
})();
Here is the Index
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js"></script>
<script src="simpleHtmlAjax.js"></script>
</head>
<body>
<div id="ajaxerizer">
<script>
ajaxCalls.setup({
url:"json.php",
DirectHTML: false,
});
alert(JSONDATA);
</script>
</div>
</body>
</html>
and the JSON data
<?php
$json = array("one" => 1,"two" => 2,"three" => 3,"four" => 4);
echo json_encode($json);
?>
Thank you for any help.
You're already including jQuery in your HTML, so why not just use jQuery's AJAX helper functions to automatically process the JSON data?
$.post("json.php", function (data) {
// do something with data, which should be a plain JS object:
// {"one":1, "two":2, "three":3, "four":4}
}, "json");

JavaScript + Querystring + div

How to load content in to a html page. please note IM not allowed to use php or C. Only javascript and html.
for example
load Page B in to Page A
http:myweb.com/index.html?load=pageb
thank you.
Issue an AJAX request to Page B
Get the contents using responseText
Display the contents inside a div using innerHTML property.
If you can use a js framework then I would suggest jQuery and #marcgg's answer will do it.
Just plain JavaScript:
<html>
<head>
<script>
function getUrlVars() {
var map = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
map[key] = value;
});
return map;
}
function createRequestObject() {
var ro;
// Mozilla, Safari,...
if (window.XMLHttpRequest) {
ro = new XMLHttpRequest();
if (ro.overrideMimeType) {
ro.overrideMimeType('text/xml');
// See note below about this line
}
// IE
} else if (window.ActiveXObject) {
try {
ro = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
ro = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
}
if (!ro) {
alert('Giving up :( Cannot create an XMLHTTP instance');
return false;
}
return ro;
}
function sndReq(param,server,handler) {
//location.href = server+"?"+action; //uncomment if you need for debugging
http = createRequestObject();
http.open('GET', server, true);
http.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
http.onreadystatechange = handler;
http.send(param);
}
handler_function = function()
{
if(http.readyState == 4)
{
if (http.status == 200)
{
document.getElementById("your_div_element").innerHTML = http.responseText;
}
else
{
alert('There was a problem with the request.');
}
}
}
</script>
</head>
<body>
<div id="your_div_element"></div>
<script>
var getvars= getUrlVars();
sndReq(null, getvars['action'], handler_function);</script>
</body>
</html>
html:
//Page A
<html>
<head><title>Page A</title></head>
<body>
<div id="pageB"></div>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#pageB').load('pageb.html')
});
</script>
</body>
</html>
Using jQuery:
$.ajax({
type: "POST",
url: "http://some.com/page.html",
success: function(msg){
alert( "here's your data: " + msg );
jQuery("#yourDivID").html(msg);
}
});
http://docs.jquery.com/Ajax/jQuery.ajax
edit: added how to put it into a div

Categories