ERROR - unexpected token when getting bigger JSON file - javascript

I have a textbox that takes user input, sends it to WS, where it searches for anything matching said data and returns all that it finds as JSON. Then I take said json and fill a table. If the user input is quite specific I get the data and table is created with no problems, if the user input is not specific I get quite a lot of data in my JSON, BUT I also get ERROR - unexpected token, and the table stays empty.
My js
$('#btnFilter').click(function () {
var filter = $('#txtFilter').val();
var sqlCall = ""
callJsonWs("EXECUTE procedure", "loadPageFilter");
});
function loadPageFilter(dataJSON) {
var data
try {
data = JSON.parse(dataJSON)
}
catch (err) {
alert("ERROR - " + err.message)
}
document.getElementById("tableFilterPopup").innerHTML = ''
$.each(data.filter, function (index, value) {
document.getElementById("tableFilterPopup").innerHTML += '<tr onclick="newLocation(\'' + value.pageView + '\')">'
+ '<td>' + value.jobCode + '</td>'
+ '<td>' + value.jobCustomerName + '</td>'
+ '<td>' + value.jobPhoneNumber + '</td>'
+ '<td>' + value.jobModel + '</td>'
+ '</tr>';
})
}

As Gregg Duncan has mentioned, the problem was with invalid JSON format that broke off hence I was getting an incomplete JSON string.

Related

Updating table with jQuery, but browser not refreshing page

I've got a node.js and sockets app that I'm using to build a SPA. A user fills out a form to create a new lobby. When they submit it, a socket event it sent to the server, the server adds the lobby, then the server emits an event to everyone with the updated list of lobbies. When this occurs, my client side JS receives the lobby list and updates a table. While viewing the browser console, this seems to work fine. I see that the the lobby info is logged in my update_lobbies function. I see that it loops through the lobbies, and I even see the html update with the new information. However, the browser doesn't seem to update the view. If I refresh the page, which requests the same lobby information, the page will update. Also, at that point, after the refresh, future lobby updates will be visually updated for that user.
socket.on('lobby list', function(data){
if(data.lobbies.length > 0){
update_lobbies(data.lobbies);
}
}
Which then calls update_lobbies():
const update_lobbies = (lobbies) => {
var lobbies_table = document.getElementById('lobbies_table');
lobbies_table.innerHTML = "";
console.dir(lobbies);
$("#lobbies_table").append("<tr>" +
"<th>" + "Name" + "</th>" +
"<th>" + "Participants" + "</th>" +
"<th>" + "Current State " + "</th>" +
"<th>" + "Actions" + "</th>" +
"</tr>");
for (var i = 0; i < lobbies.length; i++){
console.log("looping");
$("#lobbies_table").append("<tr>" +
"<td>" + lobbies[i].name + "</td>" +
"<td>" + lobbies[i].participants.length + "/" + lobbies[i].capacity + "</td>" +
"<td>" + lobbies[i].state + "</td>" +
"<td>" + "<button id=\"join_lobby\" value=\"" + lobbies[i].name + "\">Join</button>" + " | " + "<button id=\"spectate_lobby\" value=\"" + lobbies[i].name + "\">Spectate</button>" + "</td>" +
"</tr>");
}
}
One thing that may be related is that I have a e.preventDefault(); in the form to prevent the page from reloading when I submit the form. Removing this obviously 'fixes' the problem because I'm doing a reload, but I don't want to have to reload the page to get the browser to update the view. I'm not exactly storing state information yet, so reloading isn't yet an option anyway.
I was making a stupid mistake. If the page loaded and there were no lobbies, I was hiding the table. I was just forgetting to show it when lobbies were added.

Coffeescript variable concatenation causes "Uncaught TypeError value is not a function"

I'm creating an app in Rails that uses ActionCable/Websockets and I'm using coffeescript to update a users browser with data received from the current channel in ActionCable. When I run this code I get the error "Uncaught TypeError: data.user.name is not a function", however when I swap data.user.id and data.user.name the error is then for data.user.id. I think my syntax is wrong but I can't find any answers. Any help would be appreciated. Thanks
received: (data) ->
$('#players-table').show()
$('#players-table-body').append '<tr>' +
'<td>' + data.user.id + '</td>' +
'<td>' + data.user.name +'</td>'
It'll sound strange, but you need an space after the last +:
received: (data) ->
$('#players-table').show()
$('#players-table-body').append '<tr>' +
'<td>' + data.user.id + '</td>' +
'<td>' + data.user.name + '</td>'
Without it, it'd make the data.user.name to open parenthesis and to put inside the +'</td>', like:
return $('#players-table-body').append('<tr>' + '<td>' + data.user.id + '</td>' + '<td>' + data.user.name(+'</td>'));

Can´t get the output using jQuery with rest

I am using jQuery with REST in my application and I want to get the ouput mentioned below using the jQuery within my webpage .
I used the code below to search by get a company by id (each company has id, name other info supplier and buyers) but the result does not show up for me with my code, any suggestion on what have I missed?
REST is a concept for HTTP request exchange, so you're making RESTful request calls (e.g. 'get') against the REST-API you implemented on server side.
<input name="find" type="text" maxlength="300" id="find"/>
<button onclick="findId()"> Find By ID </button>
<div id="info"></div>
<script>
function findId()
{
var id = document.getElementById("find").value;
$("#info").html("");
$.getJSON("http://localhost:8080/company/" + id, function(data)
{
for (var i in data) {
$('#info').append("<p>ID: " + data[i].id + "</p>")
$('#info').append("<p>Name: " + data[i].name + "</p>")
$('#info').append("<p>Other Info: " + data[i].otherInfo + "</p><br>")
$('#info').append("<p>Supplier: " + data[i].suppliers + "</p><br>")
$('#info').append("<p>Buyers: " + data[i].buyers + "</p><br>")
}
});
}
When I type http://localhost:8080/company/ into my browser I get the following output:
[{"id":1,"name":"Test 1","otherInfo":"Test 1","suppliers":[{"id":1,"name":"Test 1","address":"Test 1","buyers":[{"id":1,"name":"Test 1","address":"Test 1"}]},{"id":2,"name":"Test 2","address":"Test 2","buyers":[{"id":3,"name":"Test 3","address":"Test 3"},{"id":2,"name":"Test 2","address":"Test 2"}]}]},{"id":2,"name":"Test 2","address":"Test 2","suppliers":[{"id":3,"name":"Test 3","address":"Test 3","buyers":[{"id":4,"name":"Test 4","address":"Test 4"}]}]}]
If i type http://localhost:8080/company/1 into my browser i get
{"id":1,"name":"Test 1","otherInfo":"Test 1","suppliers":[{"id":1,"name":"Test 1","address":"Test 1","buyers":[{"id":1,"name":"Test 1","address":"Test 1"}]},{"id":2,"name":"Test 2","address":"Test 2","buyers":[{"id":3,"name":"Test 3","address":"Test 3"},{"id":2,"name":"Test 2","address":"Test 2"}]}]}
Is it a cross domain request? If so you can get around it by using jsonp instead of json.
function findId()
{
var id = document.getElementById("find").value;
$("#info").html("");
$.getJSON("http://localhost:8080/company/?callback=?" + id, function(data)
{
for (var i in data) {
$('#info').append("<p>ID: " + data[i].id + "</p>")
$('#info').append("<p>Name: " + data[i].name + "</p>")
$('#info').append("<p>Other Info: " + data[i].otherInfo + "</p><br>")
$('#info').append("<p>Supplier: " + data[i].suppliers + "</p><br>")
$('#info').append("<p>Buyers: " + data[i].buyers + "</p><br>")
}
});
}

Why is my json get request not working?

I am working on building a movie search app. It is my first time using json. I cannot figure out why my code is not working. I have it running on localhost using xampp.
On submit
$('.search-form').submit(function (evt) {
// body...
evt.preventDefault();
var $searchBar = $('#search');
var omdbApi = 'http://www.omdbapi.com/?';
var movieSearchTerm = $searchBar.val();
var searchData = {
s:movieSearchTerm,
r:json
}
Here is the callback function
function displayMovies(data) {
// for each search result
$.each(data.items,function(i,movie) {
movieHTML += '<li class="desc">';
//movie title
movieHTML += '<a href="' + movie.Title + '" class="movie-title">';
//release year
movieHTML += '<a href="' + movie.Year + '" class="movie-year">';
//poster
movieHTML += '<img src="' + movie.Poster + '" class="movie-poster"></li>';
$('#movies').html(movieHTML);
}); // end each
// movieHTML += '</li>';
}
$.getJSON(omdbApi, searchData, displayMovies);
});//end submit
r:json
You made a typo.
You haven't created a variable called json and the service expects the value of r to be json.
String literals need to be surrounded with a pair of " or '.
data.items
And the JSON returned doesn't have items, it has Search.

jquery: making button.click & json call work together but keeping them separated

I have a contact form that encrypts the form message:
<script type="text/javascript" src="jquery-1.10.2.min.js"></script>
<form name="form_contact" method="post" action="/cgi/formmail.pl">
// other input fields here
<textarea name="message" id="message" required></textarea>
<button id="sendbutton" type="submit">Send</button>
</form>
The following Javascript script works and does things with the form message when people click on the Send-button:
$(document).ready(function() {
$("button[id$='sendbutton']").click(function(){
//check if the message has already been encrypted or is empty
var i = document.form_contact.message.value.indexOf('-----BEGIN PGP MESSAGE-----');
if((i >= 0) || (document.form_contact.message.value === ''))
{
document.form_contact.submit(); return;
}
else
{
document.form_contact.message.value='\n\n'+ document.form_contact.message.value + "\n\n\n\n\n\n\n\n" + "--------------------------" + "\n"
if (typeof(navigator.language) != undefined && typeof(navigator.language) != null) {
document.form_contact.message.value=document.form_contact.message.value + '\n'+ "Language: " + (navigator.language);}
else if (typeof(navigator.browserLanguage) != undefined && typeof(navigator.browserLanguage) != null) {
document.form_contact.message.value=document.form_contact.message.value + '\n'+ "Language: " + (navigator.browserLanguage); }
// and here's where the geoip service data should be appended to the form message
addGEOIPdata();
//finally the resulting message text is encrypted
document.form_contact.message.value='\n\n'+doEncrypt(keyid, keytyp, pubkey, document.form_contact.message.value);
}
});
});
function addGEOIPdata(){
$.get('http://ipinfo.io', function(response)
{
$("#message").val( $("#message").val() + "\n\n" + "IP: "+ response.ip + "\n" + "Location: " + response.city + ", " + response.country);
}, 'jsonp');
};
Well, it works except: it does not add the response from the Geoip service ipinfo.io to the form message before encrypting it.
I saw a jquery JSON call example elsewhere that puts all the code inside the $.get('http://ipinfo.io', function(response){...})
but that's not what I want.
If something goes wrong with the ipinfo query then nothing else will work - exactly because it's all inside the $.get('http://ipinfo.io', function(response){...}).
In other words: how can I make my button.click and my $.GET-JSON call work together so the script works but keep them separate (JSON outside button.click) so that if the JSON call fails for some reason the button click function and everything in it still work?
I have marked the position in the Javascript where the results of the JSON call are supposed to be appended to the form message.
Thank you for your help.
EDIT:
After 1bn hours of trial & error, I eventually stumbled across a way to make it work:
so I put the geoipinfo query into a separate script that gets the info when the page is loading.
$.getJSON("https://freegeoip.net/json/", function (location) {
var results = "\n\n" + "IP: "+ location.ip + "\n" + "Location: " + location.city + ", " + location.region_name + ", " + location.country_name;
window.$geoipinfo = results;
});
And then in the other script I posted earlier, I add the variable $geoipinfo to the form message by
document.form_contact.message.value=document.form_contact.message.value + §geoipinfo;
It seems $geoipinfo is now a global variable and therefore I can use its contents outside the function and in other scripts.
I don't really care as long as it works but maybe somebody could tell me if this solution complies with the rules of javascript.
The jQuery API: http://api.jquery.com/jQuery.get/
specifies that you can put a handler in .always() and it will be called whether the get succeeds or fails.
$.get('http://ipinfo.io', , function(response)
{
$("#message").val( $("#message").val() + "\n\n" + "IP: "+ response.ip + "\n" + "Location: " + response.city + ", " + response.country);
}, 'jsonp').always(function(){
document.form_contact.message.value='\n\n'+doEncrypt(keyid, keytyp, pubkey, document.form_contact.message.value);
});

Categories

Resources