Problem when reading from JSON file using javascript - javascript

<script type="text/javascript" src="js/jquery-1.3.2.js"></script>
<script type="text/javascript" src="js/jquery-1.3.2-vsdoc.js"></script>
<script type="text/javascript">
$(function() {
$("#Button1").click(function() {
$.getJSON("ticketPriceInArray.js",
function(json) {
var ticketPriceArray=[json.tickets[0].price, json.tickets[1].price,
json.tickets[2].price, json.tickets[3].price, json.tickets[4].price,
json.tickets[5].price];
alert(json.tickets[0].type);
var inputWord =$("#keyword").val();
if (inputWord=="A"){$("#result").text(ticketPriceArray[0]);}
if (inputWord=="B"){$("#result").text(ticketPriceArray[1]);}
if (inputWord=="C"){$("#result").text(ticketPriceArray[2]);}
if (inputWord=="D"){$("#result").text(ticketPriceArray[3]);}
if (inputWord=="E"){$("#result").text(ticketPriceArray[4]);}
if (inputWord=="F"){$("#result").text(ticketPriceArray[5]);}
});
});
});
</script>
Here is "ticketPriceInArray.js"
{
"tickets":[
{
"type":"A Ticket",
"price":220,
},
{
"type":"B Ticket",
"price":180,
},
{
"type":"C Ticket",
"price":120,
},
{
"type":"D Ticket",
"price":100,
},
{
"type":"E Ticket",
"price":80,
},
{
"type":"F Ticket",
"price":50,
}
]
}
This is a simple html where when the corresponding text inputed, the corresponding ticket price will show in the html after a button-click. All the ticket info is stored in a .json file named "ticketPriceInArray.js" and I have been trying to read it using $.getJSON(), but unfortunately I haven't been able to get any success. The weird thing is I didn't get any warning on anything so I couldn't fix it. Please see if you can give me any suggestions. Thank you.

By adding an AJAX error handler, I received this
"parsererror" SyntaxError: Unexpected token }
The problem is the trailing commas after each price property.

The following example is working fine in FF and Chrome with the exact JSON you provided. In IE you will have to remove the commas after the prices, as Phil already said.
In my test both the test.html and test.js were placed in my apache server root; viewing the files directly from my desktop into my browser didn't work apparently due to security restrictions.
<html>
<head></head>
<body>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js">
</script>
<script type="text/javascript">
$(function() {
$("#Button1").click(function() {
$.getJSON("test.js", function(json) {
for (var i in json.tickets) {
var type = json.tickets[i].type;
var price = json.tickets[i].price;
$('#result').append('<span>type: ' + type+ ', price: ' + price + '</span><br />');
}
});
});
});
</script>
<button id="Button1">click me</button>
<div id="result"></div>
</body>
</html>
I suggest you use http://jsonlint.com/ to validate your JSONs; or just rely on a good encoder instead of doing it by hand ;)

A little bit different approach to solving this problem. This is assuming that you aren't changing your ticket prices based on some data that you pass to the url.
ticketPriceInArray.js
{
"A" : 220,
"B" : 180,
"C" : 120,
"D" : 100,
"E" : 80,
"F" : 50
};
main file
<script type="text/javascript" src="js/jquery-1.3.2.js"></script>
<script type="text/javascript" src="js/jquery-1.3.2-vsdoc.js"></script>
<script type="text/javascript">
var ticket_prices = {};
$(function() {
$("#Button1").click(function() {
$.getJSON("ticketPriceInArray.js", function(returnedJSON) {
ticket_prices = returnedJSON;
$("#result").text( ticket_prices[ $("#keyword").val() ] );
});
});
});
</script>
If there are any considerations (or questions about my assumptions) let me know and I will update based on that.

Assuming the following facts:
you're using firefox
there is no traffic in the network-tab when you click on #Button1
there are no errors logged
... I would like to say:
the element you click on is not $("#Button1")
Are you sure that the element you click on has the ID "Button1" and that there is only one element using that ID ?
Are you running this from a webserver or from your local filesystem?

Related

the JSON works but print an error in console

I want to show Json data when the href text is clicked.it works but whenever I clicked the href text the console prints "Uncaught SyntaxError: Unexpected token :" in file data.json. why this is happening? I have validate the code in JSONLint.
file:index. html
<html>
<head>
<script src="data.json"></script>
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
</head>
<body>
<h1 id="title">Using jQuery to retrieve Json via Ajax</h1>
Get JSON data
</body>
<script>
$(function(){
$("#clickme").click(function(){
$.getJSON("data.json",function(data){
var items=[];;
$.each(data,function(key,val){
items.push('<li id="'+key+'">'+val+'</li>');
});
console.log(items);
$("<ul/>",{
"class":"interest-list",
html:items.join("")
}).appendTo("body");
});
});
});
</script>
</html>
file:data.json
{
"one":"pikachu is awesome",
"two":"squirtle is awesome"
}
The problem is in your data.json file:
you must change your json like this (using [ ] ):
[
{
"one":"pikachu is awesome",
"two":"squirtle is awesome"
}
]
then you must change your js code to use data[0] instead of data:
$.each(data[0],function(key,val){
items.push('<li id="'+key+'">'+val+'</li>');
});
this prevent the console error and all works fine.
p.s.: i suggest to remove the unnedded ; in line 14:
var items=[];;
to
var items=[];

How to load different html files in QUnit?

I'm using QUnit for unit testing js and jquery.
My HTML looks like this:
<!DOCTYPE html>
<html>
<head>
<title>QUnit Test Suite</title>
<script src="../lib/jquery.js"></script>
<link rel="stylesheet" href="http://code.jquery.com/qunit/qunit-1.16.0.css" type="text/css" media="screen">
<script type="text/javascript" src="http://code.jquery.com/qunit/qunit-1.16.0.js"></script>
<!--This is where I may have to add startPage.html--->
<script src="../login.js"></script>
<script src="../test/myTests.js"></script>
</head>
<body>
<div id="qunit"></div>
<div id="qunit-fixture"></div>
</body>
</html>
Currently, I'm adding login.js as shown and I'm getting references correctly to objects defined in login.js.
However, functions in login.js contains references to some dom elements defined in startPage.html which is located elsewhere.
So, if I say $('#login-btn'), it is throwing an error. Is there any way to fix this?
Can I
(a) refer to startPage.html to my qunit page given above?
(b) refer to or load startPage.html in the file where I'm running tests (myTests.js):
QUnit.test( "a test", function( assert ) {
assert.equal( 1, "1", "String '1' and number 1 have the same value" );//works
assert.equal( login.abc, "abc", "Abc" );//works with attributes
assert.equal(($("#userid").val()),'', 'Userid field is present');//fails
assert.equal( login.ValidUserId(), true, "ValidUserId" );//fails with functions
});
Does QUnit provide any method to load Html/php files so they'll be defined prior to testing. Like 'fixtures' in jasmine?
EDIT: Please also tell what to do in case I have startPage.php
There are a couple of ways you can do this. The simplest is just to use the built-in QUnit "fixtures" element. In your QUnit HTML file, simply add any HTML you want in the div with the id of qunit-fixture. Any HTML you put in there will be reset to what it was on load before each test (automatically).
<html>
...
<body>
<div id='qunit'></div>
<div id='qunit-fixture'>
<!-- everything in here is reset before each test -->
<form>
<input id='userid' type='text'>
<input id='login-btn' type='submit'>
</form>
</div>
</body>
</html>
Note that the HTML in the fixture doesn't really have to match what you have in production, but obviously you can do that. Really, you should just be adding the minimal necessary HTML so that you can minimize any side effects on your tests.
The second option is to actually pull in the HTML from that login page and delay the start of the QUnit tests until the HTML loading is complete:
<html>
<head>
...
<script type="text/javascript" src="http://code.jquery.com/qunit/qunit-1.16.0.js"></script>
<script>
// tell QUnit you're not ready to start right away...
QUnit.config.autostart = false;
$.ajax({
url: '/path/to/startPage.html',
dataType: 'html',
success: function(html) {
// find specific elements you want...
var elem = $(html).find(...);
$('#qunit-fixture').append(elem);
QUnit.start(); // ...tell QUnit you're ready to go
}
});
</script>
...
</head>
...
</html>
Another way to do this without using jquery is as follows
QUnit.config.autostart = false;
window.onload = function() {
var xhr = new XMLHttpRequest();
if (xhr) {
xhr.onloadend = function () {
if(xhr.status == 200) {
var txt = xhr.responseText;
var start = txt.indexOf('<body>')+6;
var end = txt.indexOf('</body>');;
var body_text = txt.substring(start, end);
var qunit_fixture_body = document.getElementById('qunit-fixture');
qunit_fixture_body.innerHTML = body_text;
}
QUnit.start();
}
xhr.open("GET", "index.html");
xhr.send();
} else {
QUnit.start(); //If getting the html file from server fails run tests and fail anyway
}
}

Go to URL if input val == something

So, I've found this JSFiddle example. In JSFiddle works well, the problem is that, even if I search any != from "advogados" (just testing), the browser goes to: http://www.site.com/index.html?procura=teste
No jQuery conflict, no html issue.
Here's JS
$("#procura").on("submit", function(event){
// prevent form from being truely submitted
event.preventDefault();
// get value of text box
name = $("#procura_texto").val();
// compare lower case, as you don't know what they will enter into the field.
if (name.toLowerCase() == "advogados")
{
//redirect the user..
window.location.href = "http://jornalexemplo.com.br/lista%20online/advogados.html";
}
else
{
alert("no redirect..(entered: " + name + ")");
}
});
If your javascript is somewhere in your HTML before your <form> your $("#procura") will be an empty set, so the submit-action won't be bound to anything. Try following code:
<html>
<head>
<script type="text/javascript" src="/path/to/your/jquery.js"></script>
<script type="text/javascript">
$(function() {
// This code will be run if your document is completely
// parsed by the browser, thus all below elements are
// accessible
$('#procura').on('submit', ....);
});
</script>
</head>
<body>
<form id="procura">...</form>
</body>
</html>
$(function() {}) is also known as $(document).ready(function() {}), (documentation)
You aren't defining the variable name. http://jsfiddle.net/zwbRa/59/
var name = $("#procura_texto").val();

Accessing JSON parsed object (works with trace but not without...)

I'm facing a weird problem after parsing a JSON file. I access the data and can use it only if I use "trace" at the right place ! When I comment the trace line I get "undefined"... Is it a problem of execution order of my code or maybe a problem passing the string argument ?
Thanks in advance for looking for a solution, this problem is very frustrating!!
Here is my code :
//index.js
var language={};
var resourceManager = {};
$(document).ready(function(){
loading();
});
function loading() {
$.ajaxSetup({'beforeSend': function(xhr){
if (xhr.overrideMimeType)
xhr.overrideMimeType("text/plain");
}
});
$.getJSON("json/lang_french.json", function(data) {
language = data;
});
setTitle();
}
function setTitle()
{
var title = resourceManager.getString("welcome");
var query = document.getElementById('title');
query.textContent = title;
}
resourceManager.getString = function(str)
{
//alert(str);//if I uncomment this line, the whole code works...
return language[str];//when the "alert" is commented, return undefined !!!
};
Here is the JSON file : lang_french.json
{
"welcome" : "Bienvenue",
"goodbye" : "Au revoir"
}
and the HTML file, index.html
<!DOCTYPE html>
<html>
<head>
<style>img{ height: 100px; float: left; }</style>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script src="index.js"></script>
</head>
<body>
<div id="title">
</div>
</body>
</html>
I'm not 100%, but I'd guess that what is happening is that the asynchronous $.getJSON call hasn't completed by the time it gets to "return language[str]" (AKA a race condition). Putting the "alert" in must give it enough time to complete the call.
Try putting "setTitle" in the callback for $.getJSON eg:
$.getJSON("json/lang_french.json", function(data) {
language = data;
setTitle();
});
That means it will wait to make that call until language is actually set, rather than being the empty object {}.

How do you use $('document').ready(function()) in jQuery?

I have a piece of code that is working fine in IE, but it doesn’t run in Firefox. I think the problem is that I have not been able to implement $('document').ready(function). The structure of my json is like [{"options":"smart_exp"},{"options":"user_intf"},{"options":"blahblah"}].
I will be very thankful if someone can see my code & help me in correctly implementing it. Here is my code:
<html><head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2
/jquery.min.js"></script>
<script type="text/javascript" language="javascript">
$(document).ready(function() {
$.getJSON("http://127.0.0.1/conn_mysql.php", function (jsonData) {
$.each(jsonData, function (i, j) {
document.form1.fruits.options[i] = new Option(j.options);
});});
});
</script></head>
<body><form name="form1">
My favourite fruit is :
<select name="fruits" id="fruits" /></form></body>
</html>
Short version (suggested by meeger): don't use single quotes around document.
document is a variable that comes with JavaScript (at least in the browser context). Instead, try the following for the relevant line.
$(document).ready(function() {
You'll also want to take the onLoad attribute off of the body tag, else it will run twice.
Just run $(document).ready(function() {doStuff}). This will automatically run when the document is ready.
It's best practice, at least in my opinion, that you don't put any events in the html itself. This way you separate the structure of an html document from it's behavior. Instead attach events in the $(document).ready function.
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$.getJSON("http://localhost/conn_mysql.php", function (jsonData) {
var selectElem = $('#fruits');
for(var i = 0; i < jsonData.length; i++) {
selectElem.append($('<option>').html(jsonData[i].options));
}
});
});
</script>
</head>
<body>
<form name="form1">
My favourite fruit is :
<select name="fruits" id="fruits" />
</form>
</body>
</html>
EDIT:
I tested with the following and mocked the json object since I can't make that call myself.
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var jsonData = JSON.parse('[{"options":"smart_exp"},{"options":"user_intf"},{"options":"blahblah"}]');
var selectElem = $('#fruits');
for(var i = 0; i < jsonData.length; i++) {
selectElem.append($('<option>').html(jsonData[i].options));
}
});
</script>
</head>
<body>
<form name="form1">
My favourite fruit is :
<select name="fruits" id="fruits" />
</form>
</body>
</html>
Here it is in all its glory. The shorthand, awesome version:
UPDATED
<script type="text/javascript" language="javascript">
$(function() {
$.getJSON("http://localhost/conn_mysql.php", function (jsonData) {
var cacheFruits = $('#fruits'),
cacheOption = $(document.createElement('option'));
$.each(jsonData, function (i, j) {
cacheFruits.append(
cacheOption.clone().attr('value', j.options).html(j.options)
);
});
});
});
</script>
Of course, I don't know what your JSON structure is, so you may need to play around with the append section of the code.
There should be no reason why the above would not work.
You do not need quotes around document. Once the page has completely loaded, it will start executing whatever you have defined in ready()
$(document).ready(function() {
$(this).getJSON("http://localhost/conn_mysql.php", function (jsonData) {
$(this).each(jsonData, function (i, j) {
document.form1.fruits.options[i] = new Option(j.options);
});
});
});
Try this, your json data should be in this format:
[{'text':'sometext','value':'somevalue'},{'text':'sometext','value':'somevalue'}];
$(document).ready(function() {
$(this).getJSON("http://localhost/conn_mysql.php", function (jsonData) {
var options = [];
$.each(jsonData, function (i, j) {
options.push('<option value="' + j.value + '">' + j.text + '</option>');
});
$('#fruits').html( options.join(''));
});
});
Please note that there may be an encoding/escaping issues here.
Make sure that you escape the text properly from the server side.
htmlentities, htmlspecialchars can help you with that.
This should work in most browsers

Categories