Replace javascript variable without id or class - javascript

I have this javascript and once the AJAX process is executed I want to replace this variable to some other variable.
window.onload = function() {
oldvariable = [];
var chart = new Chart("Container2", {
data: [{
type: "column",
dataPoints: oldvariable
}]
});
}
When I process the AJAX request and fetch JSON data which is stored in oldvariable, it is not written so I have few options. I tried ads they are working in HTML but not under script tag.
If I can define oldvariable='<div class="second"></div>'; and replace this with processed JSON data then it is working and giving correct output in HTML but in javascript < tag is not allowed as variable so we cant define oldvariable like that.
$( "div.second" ).replaceWith( ''+newvariable +'' );
So is there anyway I can replace javascript variable as HTML tags are not allowed in variable and without tag javascript can't replace.
I have one more probable solution.regex. Search for oldvariable in entire HTML code and replace with newvariable but that process will be very slow so what is the best way to do this.
My vairables are globally defined and AJAX request is in external file and above codes are embeded in HTML.
========edit
how we can replace oldvariable with newvariable in above javascript
====== ajax code- variable name is different
$(document).ready(function() {
(function() {
$('#upload-form2').ajaxForm({
dataType: 'json',
success: function(data) {
var oldvariable = '',
downlo;
for (var i = 0; i < data.length; i++) {
downlo = data[i];
oldvariable += '' + downlo.ndchart + '';
}
$('#chek').html(oldvariable );
}
})
})();
});

you need to update chart datapoints and re-render the chart after ajax success like this
ajax :
...
success:function(response)
{
chart.options.data[0].dataPoints=response;
//response is (array) of dataSeries
chart.render();
}
.......
update 1 : As per your code data should be updated like this
.....
success:function(data) {
var new_data = [];
for (var i = 0; i < data.length; i++)
{
new_data.push({y:data[i].ndchart });
}
chart.options.data[0].dataPoints=new_data;
chart.render();
}
.....
update 2:
$(document).ready(function() {
(function() {
$('#upload-form2').ajaxForm({
dataType: 'json',
success: function(data) {
var new_data = [];
for (var i = 0; i < data.length; i++)
{
new_data.push({y:data[i].ndchart });
}
chart.options.data[0].dataPoints=new_data;
chart.render();
}
})
})();
});

Related

How to set json data into a html table

i want to display these json data into a html table. i am trying to do many things but i cant figure out how can i do it. So anyone can please help me to fix it.
the json data set will appear in the console. but i cant set it to a table.
this is my model
public function displayRecords()
{
$this->db->select('A.*');
$this->db->from('rahu AS A');
$this->db->where('A.status',1);
return $this->db->get()->result_array();
}
this is my controller
public function allrecodes()
{
/*script allow*/
if (!$this->input->is_ajax_request()) {
exit('No direct script access allowed here.');
}
$response= array();
$response['result'] = $this->RahuModel->displayRecords();
echo json_encode($response);
}
this is my js
var get_rec = function(){
//alert("WWW");
$.ajax({
//request ajax
url : "../dashbord/allrecodes",
type : "post",
contentType: "application/json",
dataType : "json",
success: function(dataset) {
//var myobject = JSON.stringify(result);
//alert(myobject[0]);
console.log(dataset);
console.log(dataset.result[0]['id']);
},
error: function() { alert("Invalide!"); }
});
};
the json dataset will appear in console.
And also this get_rec() in js file will called top of the page.
$(document).ready(function() {
//alert("Hello, world!");
get_rec();});
can anyone please help me to fix it.. thank you !!
There is no "simple" way to do it. You will have to loop through the resultset and render the html.
function renderTable(data) {
var result = ['<table>'];
var header = false;
for (var index in data) {
var row = data[index];
if (!header) {
// Create header row.
header = Object.keys(row);
var res = ['<tr>'];
for (var r in header) {
res.push("<th>" + header[r] + "</th>");
}
res.push('</tr>');
result.push(res.join("\n"));
}
// Add data row.
var res = ['<tr>'];
for (var r in header) {
res.push("<td>" + row[header[r]] + "</td>");
}
res.push('</tr>');
result.push(res.join("\n"));
}
result.push('</table>');
return result.join("\n");
}
document.getElementById('output').innerHTML = renderTable(data);
Have a div tag with id output on your HTML
<div id="output"></div>

Display only most recent row of data in Google Sheet from api call

I'm trying to print the most recent row from a Google Sheet, which updates daily. I'm making an API call to it and returning it in Json and whilst I can grab the most recent value, I can only seem to print the whole column of data:
I apologise the code is a bit slap and dash, I'm new to this.
Javascript
var sheetsuUrl = "https://sheetsu.com/apis/v1.0/3e242af0";
$.ajax({
url: sheetsuUrl,
dataType: 'json',
type: 'GET',
// place for handling successful response
success: function(data) {
console.log(data[data.length-1]['moved'])
addCharacters(data);
},
// handling error response
error: function(data) {
console.log(data);
}
});
addCharacters = function(characters) {
var list = $('#ponies');
for(var i=0; i<characters.length; i+=1) {
char = characters[i];
function lastNoZero(myRange) {
lastRow = myRange.length;
for (; myRange[lastRow - 1] == "" || myRange[lastRow - 1] == 0 && lastRow > 0 ; lastRow--) {
/*nothing to do*/
}
return myRange[lastRow - 1];
}
myRange = char.moved;
if (char.moved == 'entered') {
html = "<img src='https://media.firebox.com/pic/p5294_column_grid_12.jpg'/>";
} else {
html = "<img src='http://41.media.tumblr.com/30b1b0d0a42bca3759610242a1ff0348/tumblr_nnjxy1GQAA1tpo3v2o1_540.jpg'/>";
};
list.append(html);
}
}
HTML
<script src="https://code.jquery.com/jquery-3.0.0-alpha1.js"></script>
<div id="ponies"></div>
CSS
html img{
width:100px;
height:100px;
}
You needed to reference the last item in the array returned by your GET request.
characters[characters.length - 1]; will get the last character in the characters array. Then, to ensure that the html is not added on each run of the loop, you needed to move list.append(html); outside the loop, ensuring that it only appends the content to the page once.
Run the code snippet below to see in action.
var sheetsuUrl = "https://sheetsu.com/apis/v1.0/3e242af0";
$.ajax({
url: sheetsuUrl,
dataType: 'json',
type: 'GET',
// place for handling successful response
success: function(data) {
addCharacters(data);
},
// handling error response
error: function(data) {
console.log(data);
}
});
addCharacters = function(characters) {
var list = $('#ponies');
for(var i=0; i<characters.length; i+=1) {
char = characters[characters.length - 1];
myRange = char.moved;
if (char.moved == 'entered') {
html = "<img src='https://media.firebox.com/pic/p5294_column_grid_12.jpg'/>";
} else {
html = "<img src='http://41.media.tumblr.com/30b1b0d0a42bca3759610242a1ff0348/tumblr_nnjxy1GQAA1tpo3v2o1_540.jpg'/>";
};
}
//for illustration purposes
list.append(characters[characters.length - 1].time)
//the code to attach the image
list.append(html);
}
<script src="https://code.jquery.com/jquery-3.0.0-alpha1.js"></script>
<div id="ponies"></div>

Passing arrays js variable to php

Currently I have stored variables in a Javascript array. The goal here is to turn them into PHP variables so that I can use these variables and insert them into my database.
The problem with this code is that the AJAX part doesn't work. Please get me in the right direction as I am extremely new to AJAX. I did try to read about them but still do not understand much. Doing it without refreshing the page is not necessary. Methods other than AJAX are welcomed.
Here is my current code:
<button onclick="Bookings()">Book</button>
<script>
function Bookings() {
var t2Cells = document.getElementsByClassName("t2");
for (var i = 0; i < t2Cells.length; i++) {
var t2CellsIndex [i] = t2Cells[i].cellIndex
var t2CellsRow [i] = t2Cells[i].parentNode.rowIndex
//alert('Coordinates are: '+t2Cells [i].cellIndex+'x'+t2Cells [i].parentNode.rowIndex);
var tbl = document.getElementById("tblMain");
//alert (tbl.rows[0].cells[t2CellsIndex].innerHTML);
var studioSelected = tbl.rows[0].cells[t2CellsIndex].innerHTML
var Timeselected = tbl.rows[t2CellsRow].cells[0].innerHTML
$.ajax({
type: "POST",
url: 'bookingconfirm.php',
data: "studioSelected=" + studioSelect,
success: function(data) {
alert("success!");
}
});
}
}
</script>
<?php
//bookingconfirmed.php
if (isset($_POST['studioSelect'])) {
$uid = $_POST['studioSelect'];
//steps to insert into database.
First, you should move ajax call outside of foreach
var usefulData = [];
var t2Cells = document.getElementsByClassName("t2");
for (var i = 0; i < t2Cells.length; i++) {
var t2CellsIndex [i] = t2Cells[i].cellIndex
var t2CellsRow [i] = t2Cells[i].parentNode.rowIndex
//alert('Coordinates are: '+t2Cells [i].cellIndex+'x'+t2Cells [i].parentNode.rowIndex);
var tbl = document.getElementById("tblMain");
//alert (tbl.rows[0].cells[t2CellsIndex].innerHTML);
var studioSelected = tbl.rows[0].cells[t2CellsIndex].innerHTML
// add data to array
usefulData.push(studioSelected);
var Timeselected = tbl.rows[t2CellsRow].cells[0].innerHTML
}
$.ajax({
type: "POST",
url: 'bookingconfirm.php',
data: {'usefuldata': usefulData},
success: function(data) {
alert("success!");
}
});
Then in your php file:
if (isset($_POST['usefuldata'])) {
var_dump($_POST['usefuldata']);
}

Accessing specific data from csv file and show on html

Having some problems accessing specific data from a csv file. Currently I can see all data in the console but when I try to show a specific data getting undefined. For example in my console I get all data and I want to extract the subtitles and show it on the html in a class score-text.
My console looks like this:
subtitle 1,
name1,65%
name2,65%
name3,65%
name4,65%
total,70%
,
subtitle 2,
name1,65%
name2,65%
name3,65%
name4,65%
total,30%
,
subtitle 3,
name1,65%
name2,65%
name3,65%
name4,65%
total,60%
,
subtitle 4,
name1,65%
name2,65%
name3,65%
name4,65%
total,50%
$.ajax({
url: 'test.csv',
type: "GET",
dataType: "text",
success: function (data) {
var rows = data.split(/\n/);
for (var rowIndex in rows)
{
var columns = rows[rowIndex].split(/,/);
for (var colIndex in columns)
{
var colValue = columns[colIndex].trim();
console.log(colValue);
}
}
$(".score-text").each(function( index, value ) {
value.innerHTML = result[columns[2]] = rows[2];
});
}
});
Why don't you try putting the insertion part into the loop?
var columns = rows[rowIndex].split(/,/);
for (var colIndex in columns)
{
var colValue = columns[colIndex].trim();
console.log(colValue);
$(".score-text").append(colValue);
}

is there a way to set a var = to content of external file in javascript?

I have to pass some result string to the view after sucessful ajax post. At the moment my js is placed in the view and the callback function creates a resultstring and then posts it to the results div. Since I have some blade syntax in the string that is being generated by the callback function it works until I leave the js in the blade.php view file, if I put the javascript in public/js/some.js blade doesn't parse that syntax and the result is the view is rendered with the syntax instead of data. So I was thinking: Can I put the sting in a separate view/js/result.blade.php and in the jquery function do somtehing like:
var resultStr = (content of view/js/result.blade.php)
for(var i=0; i<obj.length; i++){
resultStr
};
$("#results").html(resultStr);
If so, how do I load the external file into partialstring?
My guess is that as it's a blade file it will be parsed.
#c-smile tried this code but is not working, the file is opened but then the view doesn't get the data
jQuery(function ($) {
$(document).ready(function () {
var form = $('form');
form.submit(function (e) {
e.preventDefault();
$.get("js/blade/filler.blade.php", function (data) {
var resultStr = data;
$.ajax({
url: form.prop('action'),
type: 'post',
dataType: 'json',
data: form.serialize(),
success: function (data) {
var obj = (data);
for (var i = 0; i < obj.length; i++) {
resultStr;
}
$("#results").html(resultStr);
}
});
});
});
});
});
That's subject of AJAX functionality.
With jQuery you would do it as:
$.get( "view/js/result.blade.php", function( data ) {
var resultStr = data;
...
});

Categories

Resources