Loading JSON into JavaScript variable locally without server-side script? - javascript

I have 41 JSON objects, each with the same scheme.
These objects are fairly large, and so I would like to load the object conditionally into a JavaScript script, when selecting an <option> from a <select> menu with an id of myPicker.
So far, I have set up jQuery to handle changes on the <select>:
$('#myPicker').change(function() {
alert('Value change to ' + $(this).attr('value'));
$('#container').empty();
init();
});
The function init() draws stuff in div called container.
When I change myPicker, I want init() to behave like init(value), which in turn tells init to load one of 41 JSON objects from a file (based on value).
Is loading a chunk of JSON from a file (located on the server-side) doable in this case, or do I need to use a server-side script handling Ajax form submissions and responses, etc.?
EDIT
I wrote the following code:
<script language="javascript" type="text/javascript">
$(document).ready(function(){
$('#cellTypePicker').change(function() {
alert('Value change to ' + $(this).attr('value'));
$('#container').empty();
initFromPicker($(this).attr('value'));
});
});
function initFromPicker(name) {
// pick default cell type from picker, if name is undefined
if (typeof name === "undefined")
name = 'AG10803-DS12374';
var jsonUrl = "file://foo/bar/results/json/" + name + ".json";
alert(jsonUrl);
$.ajax({
url: jsonUrl,
dataType: 'json',
success: function(response){
alert("Success!");
},
error: function(xhr, textStatus, errorThrown){
alert("Error: " + textStatus + " | " + errorThrown + " | " + xhr);
}
});
init(); // refills container...
}
</script>
<body onload="initFromPicker();">
...
The line alert("Success!"); never gets called.
Instead, I get the following error:
Error: error | Error: NETWORK_ERR: XMLHttpRequest Exception 101 | [object Object]
I am checking the value jsonUrl and it appears to be a proper URL. The file that it points to is present and I have permissions to access it (it is sitting in my home folder). Is there something I am still missing?

Let me make sure I understand your question. I think you want to:
have a handful of files out there that contain JSON objects
depending on which option is selected a particular file is loaded
the contents of the file is JSON and
you want to be able to use the JSON object later on in other javascript
If this is the case then you would just need to do something like:
$('#myPicker').change(function() {
$('#container').empty();
init($(this).val());
});
function init(jsonUrl){
$.ajax({
url: jsonUrl
dataType: 'json'
success: function(response){
// response should be automagically parsed into a JSON object
// now you can just access the properties using dot notation:
$('#container').html('<h1>' + response.property + '</h1>');
}
});
}
EDIT: Exception 101 means the requester has asked the server to switch protocols and the server is acknowledging that it will do so[1]. I think since you're using file://foo/bar/... you might need to toggle the isLocal flag for the $.ajax function [2], but honestly, I'm not sure.
[1] http://en.wikipedia.org/wiki/Http_status_codes#1xx_Informational
[2] http://api.jquery.com/jQuery.ajax/
Below is a complete working example that pulls a JSON object from Twitter, so you should be able to copy/paste the entire thing into a file and run it in a browser and have it work. If your server is configured correctly and your .json files are in the document_root and have the appropriate permissions, you should be able to swap them out for the Twitter URL and have it work the same way...
<!doctype html>
<html>
<head>
<title>My Super Rad Answer</title>
</head>
<body>
<form id="my-form">
<select id="cellTypePicker">
<option value=''>No Value</option>
<option value="AG10803-DS12374">AG10803-DS12374</option>
</select>
</form>
</body>
<!-- Grab the latest verson of jQuery -->
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript">
// Wait until the page is fully loaded
$(document).ready(function(){
$('#cellTypePicker').change(function() {
// Grab the value of the select field
var name = $(this).val();
if (!name) {
// Make sure it's not null...
// This is preferred over using === because if name is
// anything but null, it will return fale
name = 'AG10803-DS12374';
}
// Right now I'm overwriting this to a resource that I KNOW
// will always work, unless Twitter is down.
//
// Make sure your files are in the right places with the
// right permissions...
var jsonUrl = "http://api.twitter.com/help/test";
$.ajax({
url: jsonUrl,
dataType: 'json',
success: function(response){
// JSON.stringify takes a JSON object and
// turns it into a string
//
// This is super helpful for debugging
alert(JSON.stringify( response ));
},
error: function(xhr, textStatus, errorThrown){
alert("Error: " + textStatus + " | " + errorThrown + " | " + xhr);
}
});
});
});
</script>
</html>

You can use $.ajax() for this - or one of the shortcuts, e.g. $.getJSON():
$.getJSON('somefile', function(data) {
// here, data is javascript object represented by the json in somefile
});

Related

Ajax: obtain input text using get function from a web api

I have a problem using ajax,
I have a controller get who gives me a simple object (in my case is just one name) but I have this error ( SyntaxError: Unexpected end of JSON input ) and I don't know why.
This is the code:
$(function a() {
var $hello = $('#hello'); //Here #hello is a id which is inside a div
$.ajax({
url: uri_3,
type: 'GET',
dataType: 'json', // if i put text here also don't work, gives sucess but don't appear the
//name
success: function (data) { //have a problem get the name , also I try just $hello.append
//alone and using h2 rather than li but don't work
$.each(data, function c(i, name) {
$hello.append('<li>Name: ' + name + '</li>');
});
},
error: function (xhr, textStatus, errorThrown) { //it always gives me this error, it
//doesn't reach the top success
console.log('Error in Operation');
$hello.append('<h4> User Not Found: ' + errorThrown + '</h4>');
}
});
});
Since the backend function is working (I tested it using swagger and it gives me the right name), I assume the error must be in this ajax function. What more do I have to add?
Any answer is welcome

Appending external PHP file in jQuery

I'm referring a question answered here.
Trying to append an external PHP file in to jQuery and tried load.
$(".chatbox").load("./one.php");
This gives me the output;
Your success message!
However the concern is this removes all HTML in the body and does not really 'append' the success message.
I tried the following instead.
$(".chatbox").append("./one.php");
which merely prints this!
./one.php
Am I missing something here?
The .load() load data from the server and place the returned HTML into the matched element. But you need to use $.ajax() or $.get() that get data and return it into callback function.
$.get("./one.php", function(data) {
$(".chatbox").append(data);
});
in case if the page you're trying to load is failing due to some reason, you also need to handle the error block to inform you about the issue. Here is a more comprehensive way to do it. Here I have called a wiki page but you will know, all the php pages are in fact interpreted as valid html by PHP engine :)
$.ajaxPrefilter( function (options) {
if (options.crossDomain && jQuery.support.cors) {
var http = (window.location.protocol === 'http:' ? 'http:' : 'https:');
options.url = http + '//cors-anywhere.herokuapp.com/' + options.url;
}
});
$.ajax({
type: "GET",
url: "https://en.wikipedia.org/wiki/PHP",
data: { },
success: function(data){
$('#demo').html(data);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
$('#demo').html("Status: " + textStatus + "<br/>Error: " + errorThrown);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="demo"></div>

jQuery .html(someHTML) is not working

I have a script that makes an ajax request to the server. Then the server returns HTML code. After the request finish, I want to take the HTML code and put it on my site.
The problem that I am having is that the function .html() will display the html as text instead of making it an html.
Here is what I have done
var postData =
{
'campaign_id': 1,
'page_role': 'intro'
};
$.ajax({
type: 'POST',
url: 'url/to/get/html',
data: postData,
dataType: "text",
beforeSend: function(jqXHR, settings){
$('#MasterContentViewer').html('<div class="well innerwell">' +
'<h3>Please wait while loading the next page</h3>'+
'</div>');
},
error: function( jqXHR, textStatus, errorThrown ){
alert('Loading content failed! Error Code: ' + jqXHR.status);
},
success: function(page){
$('#MasterTable').removeClass('heightForIFrame');
$('#MasterContent').removeClass('heightForIFrame');
$('#MasterContentViewer').html(page);
}
}).done(function(page) {
var tags = $("meta[name^='is_system_'],meta[name^='is_attr_']" );
$.each(tags, function(index, tag){
var value = $(tag).attr('value');
var name = $(tag).attr('name').replace('is_attr_', '').replace('is_system_', '');
$('#attr_' + name + ':input').val( value );
$('#attr_' + name).not('input').text( value );
$('.attr_' + name + ':input').val( value );
$('.attr_' + name ).not('input').text( value );
});
I tried to change the following like
$('#MasterContentViewer').html(page);
to
$('#MasterContentViewer').empty().append(page);
which also did not work.
I also tried to change the dataType from "text" to "html" which also did not work.
How can I make the force the page to display html code instead of text?
UPDATED
Here is sample of what the user sees on the screen
<strong>Store Name: </strong><span class="attr_storename"></span> </div> <div class="scripter_header_label"> <strong>Store Number: </strong><span class="attr_alt_id_1"></span>
If .html(string) is appending elements as text, then that means that the elements are already HTML Encoded (e.g., <'s are in the string as >'s). jQuery will only encode html if you tell it to by using .text(string) instead of html(string).
Two possible solutions are:
Modify your server-side code to send non-encoded HTML
HTML Decode the string using Javascript (I would not recommend this method, however, because it caters to HTML Injection attacks).

getJSON in Javascript

I am new to html and javascript.As far as i know the following code should give an alert when i press "Get JSON Data" button.But the page is not giving me any response.Any help is greatly appreciated.
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$.getJSON("http://127.0.0.1:5000/2", function(result){
if (result.length == 0){
alert("nothing") ;
}
if (result.length){
alert("success") ;
}
// $("div").append(myObject);
});
});
});
</script>
</head>
<body>
<button>Get JSON data</button>
<div></div>
</body>
</html>
I suspected that should be the Cross-domain issue. That is why I asked for the console log. you have couple of choices:
config the cross-domain headers from your servlet/backend response.
(ex: if you're using a Servlet:)
response.setHeader('Access-Control-Allow-Origin','*');
use jsonp call back
$.getJSON("http://example.com/something.json?callback=?", function(result){
//response data are now in the result variable
alert(result);
});
The "?" on the end of the URL tells jQuery that it is a JSONP
request instead of JSON. jQuery registers and calls the callback
function automatically.
use $.ajax with CORS enabled or with jsonp
ex:
$.ajax({
url: surl,
data: {
id: id // data to be sent to server
},
dataType: "jsonp",
jsonp: "callback",
jsonpCallback: "jsonpcallback"
});
// Named callback function from the ajax call when event fired.
function jsonpcallback(rtndata) {
// Get the id from the returned JSON string and use it to reference the target jQuery object.
var myid = "#" + rtndata.id;
$(myid).feedback(rtndata.message, {
duration: 4000,
above: true
});
}
or else, download and configure "CORS.jar" in your server side which will allow the cross-domain requests.
HOW ?
Hope you can get some idea. follow which suits for you ..
Replace the JSON call with
$.getJSON("http://127.0.0.1:5000/2", function(result){
if (result.length == 0){
alert("nothing") ;
}
if (result.length){
alert("success") ;
}
// $("div").append(myObject);
}).fail(function( jqxhr, textStatus, error ) {
var err = textStatus + ", " + error;
console.log( "Request Failed: " + err )
});
That way you can see what goes wrong. The javascript looks OK, I suspect it's a server issue.
You could also try getting back JSON from some random source, like http://1882.no/API/business/get/results.php?q=skole&page=0

Symfony2: How to get the current route in javascript?

I'm using Ajax to change data in a page. So, I want to know that what is the current route in order to call to different functions. I have read many solutions used to retrieve the current url and also to get the current route in Controller and Twig. However, is there any possible way to achieve this in javascript or jQuery?
$(document).ready(function(){
$('#form_patient').change(function(){
var id = $(this).val();
// Get the current route
var route = ??; // <----------------Want to get the current route
if(route === 'route1'){
functionForRoute2(id,route)
}
else{
functionForRoute2(id,route);
}
});
});
** Function for the Route1 **
function functionForRoute1(id,route){
$.ajax({
type: "POST",
url: Routing.generate(route),
data: JSON.stringify({id:id}),
dataType: "json",
success: function(data){
// Execute some specific data for route1
},
error: function(XMLHttpRequest, textStatus, errorThrown)
{
alert('Error : ' + errorThrown);
}
});
}
** Function for the Route2 **
function functionForRoute2(id,route){
$.ajax({
type: "POST",
url: Routing.generate(route),
data: JSON.stringify({id:id}),
dataType: "json",
success: function(data){
// Execute some specific data for route2
},
error: function(XMLHttpRequest, textStatus, errorThrown)
{
alert('Error : ' + errorThrown);
}
});
}
What I would do is to output route (any route you want) in a html tag for example (twig version):
<div id="my-route" data-route"{{ path("my_route") }}"></div>
Then in your code I would retrive that route via jquery like this:
$(document).ready(function(){
$('#form_patient').change(function(){
var id = $(this).val();
var route = $('my-route').data('route');
});
});
You can also change path("my_route") to a string with a name of the route and then you are doing your if/else statement. However I dont think its a good idea as if your route name changes then your code will be affected as well
You will not get current route using just Javascript or JQuery. You can, however, get current URL with Javascript or current route using Twig.
Another possible solution is to issue one more AJAX call to server passing current URL, then match it to the correct route and send it back. However, if I were you, I would just get the current route from Twig.
var route = "{{ app.request.attributes.get('_route') }}";

Categories