How to keep JavaScript from adding my text as numbers - javascript

I have text like this: 4.72% - 12.04% that I am putting in a JavaScript object property which I am trying to add to the page kind of like this:
$("#container").append("<div>" + rates.fixedrates + "</div>");
And JavaScript keeps trying to calculate the numbers even though that's not what I'm trying to do. It doesn't print the text, just NaN.
How can I tell JS to stop this? I've even tried replacing the "-" with — and it does the same thing. Is there something I don't know about that can stop this?
EDIT:
The data comes in from an ajax call:
$.ajax({
url: "/Search/Rates",
type: "POST",
dataType: "json",
data: { oe: ui.item.oe },
success: function (data) {
data.forEach(function (rates, index, arr) {
$("#container").append("<div>" + currentValue.fixedrates + "</div>");
});
}
});
Controller:
return Json(rates);
"FixedRates" is just a string property off of the c# object "rates". Nothing special.

Works fine in what I can only assume is the most standard way - You're probably doing something wrong with how the value is assigned, or concatenating
const rates = {
fixedRates: ''
};
// Joining ourselves
let a = '4.72%';
let b = '12.04%';
let c = a + ' - ' + b;
// Together already
let d = '4.72% - 12.04%';
rates.fixedRates = c;
$("#container").append("<div>" + rates.fixedRates + "</div>");
rates.fixedRates = d;
$("#container").append("<div>" + rates.fixedRates + "</div>");
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="container"></div>

Ok, for brevity/clarity I left out a lot of what was in the appended <div>. I found out that I had something like this going on:
"<div>" + <-- extra plus sign
+ rates.FixedRates + "</div>"
So basically it was like this:
"<div>" + + rates.FixedRates + "</div>"
I guess there is something to be said about posting everything.

This solution will take the input and convert it to a text node before inserting it into the div which is then inserted into the container. Let me know how this works out for you..
$.ajax({
url: "/Search/Rates",
type: "POST",
dataType: "json",
data: { oe: ui.item.oe },
success: function (data) {
data.forEach(function (rates, index, arr) {
var div = document.createElement('div');
var textContent = document.createTextNode(currentValue.fixedrates);
var container = document.getElementById('container');
div.appendChild(textContent);
container.appendChild('div');
});
}
});

Related

JQuery click 1 does nothing

I have a feeling there is something wrong with my for loop. When my websites event is activated the first time, I get no response. It works as intended every time after that. I have tried tuning the numbers in the for loop looking for mistakes but as far as what I've tried. It works best as is.
For the full app: https://codepen.io/xcidis/full/KvKVZb/
var reference = [];
function random() {
$.ajax({
url: "https://api.forismatic.com/api/1.0/?",
dataType: "jsonp",
data: "method=getQuote&format=jsonp&lang=en&jsonp=?",
success: function(quote) {
reference.push([quote.quoteText + "<br/><br/><br/><div align='right'>~" + quote.quoteAuthor + "</div>"]);
}
});
}
$("button").click(function(){
random();
for(i=0;i<4; i++){
if(reference[reference.length-1] == undefined){continue}else{
var boxes = $("<div id='boxes'></div>").html("<p>" + reference[reference.length-1] + "</p>");
$('body').append(boxes);
break;
};
};
});
Your rest of the code ran before your ajax push the value to reference variable.
https://www.w3schools.com/xml/ajax_intro.asp
You can either put your page rendering code within the ajax or use some tips to run the rederer synchronously
$("button").click(function(){
$.when( $.ajax({
url: "https://api.forismatic.com/api/1.0/?",
dataType: "jsonp",
data: "method=getQuote&format=jsonp&lang=en&jsonp=?",
success: function(quote) {
reference.push([quote.quoteText + "<br/><br/><br/><div class='tweet' align='left'></div><div align='right'>~" + quote.quoteAuthor + "</div>"]);
}
})).then(function() {
console.log(reference)
for(i=0;i<4; i++){
if(reference[reference.length-1] == undefined){continue}else{
var boxes = $("<div id='boxes'></div>").html("<p>" + reference[reference.length-1] + "</p>");
$('body').append(boxes);
break;
};
};
});
});

Ajax call jsonp from PHP

Hi guys so i made a code that parses a CSV file into a JSON ARRAY with PHP. So when you go to this URL you get the PHP output:
http://www.jonar.com/portal/mynewpage.php
Now i used this code to append my JSON ARRAY to HTML but now things have changed since i am using PHP i am not sure how to use it and what to do differently.
Also my ajax call is always empty which is weird..
$.ajax({
type: 'GET',
url: 'http://www.jonar.com/portal/mynewpage.php',
dataType: 'jsonp',
success: function(response) {
alert(response);
}
});
I used this to append my JSON ARRAY but now if i can get the response do i use the same code or will it have to be altered?
$.each(results.data.slice(1), // skip first row of CSV headings
function(find, data) {
var title = data.title;
var link = data.link;
var date = data.date;
var type = data.type;
var where = data.where;
var priority = data.priority;
if (priority == '1') {
$('ul.nflist').prepend($('<li>', {
html: '' + title + ' ' + ' ' + '<span class="category">' + type + '</span>'
}));
} else if (where == 'pp', 'both') {
$('ul.nflist').append($('<li>', {
html: '' + title + ' ' + ' ' + '<span class="category">' + type + '</span>'
}));
}
});
the reason i used PHP is to avoid cross domain issue
Thanks for the help guys!

JQuery Adding elements to a list from parsed JSON

I am trying to parse some JSON and take the elements "startTime" and "endTime" and add them to a list. I am able to receive the JSON successfully, however I am having trouble properly parsing and then looping through to add each instance to the list. Inside of the UL, i would like to create lists for each, like i demo below:
$.ajax({
url: 'localhost:8080/sample?',
dataType: 'json',
success: function (data){
var json = $.parseJSON(data);
var $calAppts = $('#appts');
$('<li data-role="list-divider">' + this.startTime
+ ' - ' + this.endTime + '<span class="ui-li-count"></span></li>').appendTo($appts);
The HTML where I am trying to insert the LI inside of the UL:
<div data-role="main" class="ui-content" id="headerDate">
<ul data-role="listview" data-inset="true" id="appts">
</ul>
</div>
So basically for each appointment i get back in the JSON, I want to add a new LI with the startTime and endTime.
I am using JQM 1.3.2, and JQUERY 1.8.0.
Thank you
Change this:
$.ajax({
url: 'localhost:8080/sample?',
dataType: 'json',
success: function (data){
var json = $.parseJSON(data);
var $calAppts = $('#appts');
$('<li data-role="list-divider">' + this.startTime
+ ' - ' + this.endTime + '<span class="ui-li-count"></span></li>').appendTo($appts);
Into this:
$.ajax({
url: 'localhost:8080/sample?',
dataType: 'json',
success: function (data){
var json = $.parseJSON(data);
$.each( json, function( key, value ) {
var agrega = "<li data-role='list-divider'>";
if(key=='startTime')
{
agrega = agrega + value
}
if(key=='endTime')
{
agrega = agrega + ' - ' + value;
}
agrega = agrega + '<span class="ui-li-count"></span></li>';
$('#appts').append(agrega);
});
From your code sample, it seems your problem is that you're trying to look for the startTime property in the wrong place (on this). In your sample, the startTime property should be present on your parsed JSON, so accessing the key there should do the trick:
$('<li data-role="list-divider">' + json.startTime
+ ' - ' + json.endTime + '<span class="ui-li-count"></span></li>').appendTo($appts);
If the returned JSON is a series of times, then you'll also want to loop through the JSON object as well:
$.each(json, function(key, value) {
if (key === 'startTime') {
// append to the list
}
});
Additional note:
If JSON is what is being returned from the AJAX call, then you shouldn't need to use $.parseJSON on it. JSON objects are JavaScript objects, so you can simply use the returned value and access they keys on it (meaning you can use data.startTime directly instead of parsing it first).
Please find the response below
var ulObject = $("#appts");
var ajaxObject = $.ajax({
type:"POST",
dataType:"json",
url:"" //Provide the URL in the field to be processed.
});
ajaxObject.done(function(msg){
var jsonResponse = $.parseJSON(msg);
var listObjectStart = '<li data-role="list-divider">'
var listObjectEnd = '</li>';
$.each(jsonResponse,function(key,value){
if(key === "startTime")
{
listObjectStart += value;
}
else if(key === "endTime")
{
listObjectStart += '-'+value+'<span class="ui-li-count"></span>';
}
});
listObjectStart += listObjectEnd;
ulObject.append(listObjectStart);
});
Try the following if server send the data back to client in json format.
$.ajax({
url: 'localhost:8080/sample?',
dataType : 'json',
success: function(data){
$("#appts").append('<li data-role="list-divider">' + data.startTime
+ ' - ' + data.endTime + '<span class="ui-li-count"></span></li>');
},
error: function(){
alert('There was an error in communication.');
}
});

Array and while loop: make unique clickable

I have an array (via ajax) that looks like this:
data[i].id: gives the id of user i
data[i].name: gives the name of user i
I want to output the array like this:
X Leonardo Da Vinci
X Albert Einstein
X William Shakespeare
...
The X is an image (x.gif) that must be clickable. On click, it must go to functiontwo(), passing the parameter data[i].id. Functiontwo will open a jquery dialog with the question "Delete id data[i].id"?
I know this can't be too hard to do, but I can't seem to figure it out...
This is what I have so far:
function functionone() {
$.ajax({
type : 'POST',
url : 'post.php',
dataType : 'json',
success : function(data){
var message = "";
var i = 0;
while (i < (data.length - 1))
{
var myvar = data[i].id;
message = message + "<div class=" + data[i].id + "><img src=x.gif></div>" + data[i].name + "<br />";
$('#somediv').html(message).fadeIn('fast');
$("." + data[i].id + "").click(function () {
functiontwo(myvar);
});
i++;
}
}
});
}
function functiontwo(id) {
...}
I know why this isn't working. Var i gets populated again and again in the while loop. When the while loop stops, i is just a number (in this case the array length), and the jquery becomes (for example):
$("." + data[4].id + "").click(function () {
functiontwo(myvar);
});
, making only the last X clickable.
How can I fix this?
Thanks a lot!!!
EDIT:
This is my 2nd function:
function functiontwo(id) {
$("#dialogdelete").dialog("open");
$('#submitbutton').click(function () {
$('#submitbutton').hide();
$('.loading').show();
$.ajax({
type : 'POST',
url : 'delete.php',
dataType : 'json',
data: {
id : id
},
success : function(data){
var mess = data;
$('.loading').hide();
$('#message').html(mess).fadeIn('fast');
}
});
//cancel the submit button default behaviours
return false;
});
}
In delete.php there's nothing special, I used $_POST['id'].
As I pointed out in my comment. The problem is the .click part. Either use bind, or use a class for all the elements, and a click-event like this $('.classnamehere').live('click',function () { // stuff });
function functionone() {
$.ajax({
type : 'POST',
url : 'post.php',
dataType : 'json',
success : function(data){
var message = "";
var i = 0;
while (i < (data.length - 1))
{
var myvar = data[i].id;
message = message + "<div class=\"clickable\" id=" + data[i].id + "><img src=x.gif></div>" + data[i].name + "<br />";
$('#somediv').html(message).fadeIn('fast');
i++;
}
}
});
}
$('.clickable').live('click',function () {
alert($(this).attr('id') + ' this is your ID');
});
The usual trick is create a separate function to create the event handler. The separate function will receive i as a parameter and the generated event will be able to keep this variable for itself
make_event_handler(name){
return function(){
functiontwo(name);
};
}
...
$("." + data[i].id + "").click( make_event_handler(myvar) );

Using Ajax callback variable values in JQuery dynamic click handlers

I'm doing a simple ajax query which retrieves a variable-length list of values as JSON data. I'm trying to make a list based on this data which has click-functions based on the values I got from the JSON query. I can make this work just fine by writing the onClick-methods into the HTML like this:
function loadFooList() {
var list_area = $("#sidebar");
list_area.html("<ul>")
$.ajax({
type: 'GET',
url:'/data/foo/list',
dataType: 'json',
success: function (json) {
$.each(json, function(i, item) {
var link_id = "choosesfoo" + item.id;
list_area.html(list_area.html()
+ "<li> <a href='#' onClick='alert(\"" +
link_id + "\");'>" +
item.name + "</a></li>");
});
list_area.html(list_area.html() + "</ul>");
}
});
}
I don't like writing the onClick-function into the HTML and I also want to learn how to create this same functionality via JQuery click-function.
So the problem is obviously variable-scoping. My naive attempt here obviously won't work because the variables are no longer there when the click happens:
function loadFooList2() {
var list_area = $("#sidebar");
var link_ids = Array();
list_area.html("<ul>")
$.ajax({
type: 'GET',
url:'/data/foo/list',
dataType: 'json',
success: function (json) {
$.each(json, function(i, item) {
var link_id = "choosefoo" + item.id;
list_area.html(list_area.html()
+ "<li> <a href='#' id='" + link_id + "'>"+item.name+"</a></li>");
link_ids.push(link_id);
});
list_area.html(list_area.html() + "</ul>");
for (link_index=0; link_index<link_ids.length; link_index++) {
$("#" + link_ids[link_index]).click(function() {
alert(link_ids[i]);
});
}
}
});
}
Obviously I'd like to do something else than just alert the value, but the alert-call is there as long as I can get that working and move forward.
I understand that I'll have to make some kind of handler-function to which I pass a state-variable. This works for a single value (I can store the whole link_ids array just fine, but then I don't know which of them is the right value for this link), but how would I do this for arbitrary-length lists?
Here is an example from JQuery docs which I'm trying to copy:
// get some data
var foobar = ...;
// specify handler, it needs data as a paramter
function handler(data) {
//...
}
// add click handler and pass foobar!
$('a').click(function(){
handler(foobar);
});
// if you need the context of the original handler, use apply:
$('a').click(function(){
handler.apply(this, [foobar]);
});
And I quess the last example here, "if you need the context of the original handler..." would probably be what I want but I don't know exactly how to get there. I tried to store the current link_id value into this, use it from this in the applied function (using apply()) but I didn't succeed. The necessary values were still undefined according to FireFox. I'm using JQuery 1.3.2.
So what's the right solution for this relatively basic problem?
Use append instead of html():
function loadFooList() {
var ul = $('<ul>');
$.ajax({
type: 'GET',
url:'/data/foo/list',
dataType: 'json',
success: function (json) {
$.each(json, function(i, item) {
var link_id = "choosesfoo" + item.id;
var a = $('<a>').attr('href','#').bind('click', function(e) {
alert(link_id,item_name);
e.preventDefault();
});
$('<li>').append(a).appendTo(ul);
});
ul.appendTo('#sidebar'); // this is where the DOM injection happens
}
});
}
So the problem appears to be getting the link id associated with the link so that your click handler has access to it. Note that if it's alphanumeric it will qualify for the id attribute and you can extract it from there. If it is purely numeric, it will be an illegal id attribute. In that case, you can either use an attribute, like rel, or the jQuery.data() method to store the link id with the link. You can also simplify by using append. I'll show both examples.
var link = $("<li><a href='#' id='" + link_id + "'>" + item.name + "</a></li>";
link.click( function() {
alert( $(this).attr('id') );
});
list_area.append(link);
or (if numeric)
var link = $("<li><a href='#'>" + item.name + "</a></li>";
link.data('identifier', link_id )
.click( function() {
alert( $(this).data('identifier') );
});
list_area.append(link);
Try this:
function loadFooList() {
var list_area = $("#sidebar");
$.ajax({
type: 'GET',
url:'/data/foo/list',
dataType: 'json',
success: function (json) {
var out = '<ul>';
$.each(json, function(i, item) {
var link_id = "choosefoo" + item.id;
out +="<li><a href='#' id='" + link_id + "'>"+item.name+"</a></li>";
});
out +="</ul>"
var $out = $(out);
$out.find('a').click(function(){
var link_id = this.id;
var item_name = $(this).text();
alert(link_id);
alert(link_name);
})
list_area.html($out);
}
});
}
Using multiple appends causing the browser to redraw multiple times in a row. You only want to modify the dom once.

Categories

Resources