read a div from an html file to a javascript var - javascript

I want to read the colTwo div from the file members.html (in the same folder) into a variable, then set innerHTML to that variable. The result is 'undefined'. How can I fix this?
var fredpagevar;
$.get("members.html", function(data){
fredpagevar = $(data).find('#colTwo').html();
});
function fredpage(){
document.getElementById('boldStuff').innerHTML = fredpagevar;}

based on your markup : <li><a href="#" onclick='fredpage()'>Fred</a></li>
Try this -
function fredpage(){
$.get("members.html", function(data){
$('#boldStuff').html($(data).find('#colTwo').html());
});
}

You can simply do this:
$.get("members.html", function (data) {
$('#boldStuff').html($(data).find('#colTwo').html());
});

This should work:
var fredpagevar;
$.get("members.html", function(data){
fredpagevar = $(data).find('#colTwo').html();
}).done(function (){
document.getElementById('boldStuff').innerHTML = fredpagevar;
});
Your function probably fired before get method receive data from file.
Or second usage (in case when you use your function in other place):
var fredpagevar;
$.get("members.html", function(data){
fredpagevar = $(data).find('#colTwo').html();
}).done(fredpage());
function fredpage(){
document.getElementById('boldStuff').innerHTML = fredpagevar;
}

Related

How to restore Jesson's value and put it into outside variable

I have a problem with this code
I manage to take the values from the json and put them into variables but I can not use them outside the function
what am i doing wrong ?
var sensor_name1;
var lat1;
var lng1;
var sensor_name2;
var lat2;
var lng2;
var sensor_name3;
var lat3;
var lng3;
$(function (){
var $sensors = $('#sensors');
$.ajax({
type:'GET',
url:'http://127.0.0.1:5000/',
success: function(sensors){
$.each(sensors, function(i, sensor) {
if (i==0){
$sensors.append(sensor_name1=sensor.name, lat1=sensor.lat, lng1=sensor.lng);
}
if(i==1){
$sensors.append(sensor_name2=sensor.name, lat2=sensor.lat, lng2=sensor.lng);
}
if (i==2){
$sensors.append(sensor_name3=sensor.name, lat3=sensor.lat, lng3=sensor.lng);
}
});
console.log('sensor one : ',sensor_name1, lat1, lng1);
console.log('sensor tow : ',sensor_name2, lat2, lng2);
console.log('sensor three : ',sensor_name3, lat3, lng3);
}
});
});
Hi and welcome on Stack Overflow :)
JavaScript Ajax is asynchronous and you execute console.log() before these variables receive a value.
But in your case you pass to append() which accepts a htmlString, Element, Text, Array or jQuery parameter a assignment of value expression. You don't append a child, but you declared it using append()
You must have to wait for response from server and after use that.
$(function () {
var $sensors = $('#sensors');
$.ajax({
type: 'GET',
url: 'http://127.0.0.1:5000/',
success: function (sensors) {
$.each(sensors, function (i, sensor) {
let sensorInfo = 'sensor #'+i+': '+sensor.name+' '+sensor.lat+' '+sensor.lng;
console.log(sensorInfo);
$sensors.append('<p>'+sensorInfo+'</p>')
});
}
});
});
Greetings, plum!
Sources:
Asynchronous on MDN: https://developer.mozilla.org/en-US/docs/Glossary/Asynchronous
jQuery Docs: https://api.jquery.com/jQuery.get/#jQuery-get-url-data-success-dataType

How get a variable from HTML in JavaScript/Ajax Call

I'm using Zend Framework 2.
I would like to know how to get data defined in html in my javascript code.
html
<tr class="MyClass" data-MyData="<?php echo json_encode($array);?>">
javascript
$(document).on('click','.MyClass', function () {
var temp =document.getElementsByClassName("data-MyData");
$.ajax({
url: path_server + "pathDefinedInMyConfig",
type: 'post',
encode: true,
dataType: 'json',
data: {
'temp ': temp
},
success: function (data) {
//some code
},
error: function () {
alert("ERROR");
}
});
});
The problem is I don't have access to row in my Controller method. And i want to have access to My $array defined in html in my Controller.
Problem is that you are trying to find a class by the name data-MyData, but the object you "want" to look for is "MyClass"
Try something like var temp =document.getElementsByClassName("MyClass").attr("data-MyData");
Even better is that since you click on the object with MyClass you can use $(this).attr('data-MyData');
then result will look like: var temp = $(this).attr('data-MyData');
Simply replace temp var assignment line:
var temp =document.getElementsByClassName("data-MyData");
with this one:
var temp = this.getAttribute("data-MyData");
Since you use jQuery use the following:
$('.MyClass').data('MyData')
or
$('.MyClass').attr('data-MyData')
use like this-
$(document).on('click','.MyClass', function () {
var temp =$(this).attr('data-MyData');
$.ajax({
url: path_server + "pathDefinedInMyConfig",
type: 'post',
encode: true,
dataType: 'json',
data: {
'temp ': temp
},
success: function (data) {
//some code
},
error: function () {
alert("ERROR");
}
});});
You have a wrong selector. document.getElementsByClassNames() returns the collections so you have to loop through to get the target element:
var temp =document.getElementsByClassName('MyClass');
[].forEach.call(temp, function(el){
console.log(el.dataset['MyData']);
});
or as you are using jQuery then you can use .data():
var temp =$(this).data("MyData");
and with javascript:
var temp =this.dataset["MyData"];
// var temp =this.dataset.MyData; // <---this way too.

How to store loaded value in JS?

I've got this statement:
$('#queueCount').load("http://localhost:8081/smsc/userRole/getQueueCount/");
#queueCount is a <div> id. How can I store loaded value in variable? For example, like this:
var value=$('#queueCount').load("http://localhost:8081/smsc/userRole/getQueueCount/");
Three ways.. (1st and 2nd preffered)
var vardata;
$.get('http://localhost:8081/smsc/userRole/getQueueCount/', function(data) {
vardata = data;
});
or
var vardata;
$.ajax({
url: 'http://localhost:8081/smsc/userRole/getQueueCount/',
success: function(data) {
vardata = data;
}
});
or
var vardata;
$('#queueCount').load("http://localhost:8081/smsc/userRole/getQueueCount/");
vardata = $('#queueCount').html();
http://jsfiddle.net/hjggsqx2/2/
This is how I'd do it. I also like the syntax [website] [classname/id name]. It is more convenient.
var $div = $('<div>');
alert($div);
$div.load('http://www.aligajani.com .container', function(){
// now $(this) contains .container
});

returing data after the call success, ajax?

'function makeRequest()
{
var G_REL_URL="'||owa_util.get_cgi_env('SCRIPT_NAME')||'"
var v_data_sales ={ pvCurrCd:"'||CURRDEF||'"
};
$.ajax({
url:G_REL_URL+ "/contr_entry_pkg.SELECT_SALES_CENTERS",
data:v_data_sales,
async:false,
success: function(vRetVal){
//var jsonObj = eval("("+vRetVal+")");
function processresponse(v_data_sales,vRetVal)
}
});
} '||CHR(10)||
'function processresponse (v_data_sales,vRetVal){
retJson=eval("("+vRetVal+")");
} ';
i want to return a data to a dropdown after there is a onchange='makeRequest"
im not sure if im doing it the right way but is not giving me any errors
and is not working
maybe my logic is wrong but after its success if calls the function
processresponse so it will return pvcurrcd
but its not doing it.
any help or tips ,thanks
here below is where it make the onchange call which i dont think it matter here
HTP.P('<td class="reqlabel1">Sales Center:</td>');
HTP.P('<td class="tablelabel">');
HTP.P(Get_Sc_Dd(PVNAME=>'pnSalesCenterID', PVORAID=> VUSERNAME,
PVDEFVAL => NSALESCENTERID, PVEVENT=>'class="reqinput1" onChange="makeRequest();" style="width:260px"'));
it will change the currency dropdown here
HTP.P('<td class="reqlabel1">Currency:</td>');
HTP.P('<td class="tablelabel">');
HTP.P(Get_Currency_Dd(PVNAME=>'pvCurrCd', PVDEFVAL => NULL,
PVEVENT=>'class="reqinput1" id="pvCurrDd" onblur="makeRequest();" style="width:200px"'));
your code is missing some correct syntax... try this
'function makeRequest(){
var G_REL_URL="'||owa_util.get_cgi_env('SCRIPT_NAME')||'";
var v_data_sales ={ pvCurrCd:"'||CURRDEF||'" };
$.ajax({
url:G_REL_URL+ "/contr_entry_pkg.SELECT_SALES_CENTERS",
data:v_data_sales,
async:false,
success: function(vRetVal){
//var jsonObj = eval("("+vRetVal+")");
/*
fire up the Javascript console in
chrome/firefox/safari
and look at the result of:
*/
console.log(vRetVal);
// or better:
console.dir(vRetVal);
processresponse(v_data_sales,vRetVal);
}
});
function processresponse(v_data_sales,vRetVal){
retJson=eval("("+vRetVal+")");
}
}';

getting variables into ajax function JQuery

I have an AJAX function triggerd by a click which basically copies one table row into another table.
The problem I am having is that I get the required variables from the original table row before the AJAX request however these variables don't seem to be passed to the success function and they come out as undefined.
Is there anyway to pass the variables to the function ?
$('.addfile_popup').on('click', '.add2_fl', function(){
var file_id1=$(this).data('file');
var id=$('.useri').val();
var file_name1=$(this).closest('tr').children('td:first').text();
var upload_date1=$(this).closest('tr').children('td').eq(1).text();
var upload_desc=$(this).closest('tr').children('td').eq(2).text();
var job_idx=$(this).data('jid');
//write to appointment database
var data="job_id="+job_idx+"&file_id="+file_id1+"&user_id="+id;
$.ajax({
type:"POST",
url:"admin_includes/prepend_files.php",
data:data,
success:function(html){
var ups='';
ups+='<tr data-file='+file_id1+'><td width="40%">'+file_name1+'</td><td>'+upload_date1+'</td><td>'+upload_desc+'</td><td>VIEW FILE | DELETE</td></tr>';
$(ups).prependTo('.app_table');
}
});
});
$('.addfile_popup').on('click', '.add2_fl', function(){
var file_id1=$(this).data('file');
var id=$('.useri').val();
var file_name1=$(this).closest('tr').children('td:first').text();
var upload_date1=$(this).closest('tr').children('td').eq(1).text();
var upload_desc=$(this).closest('tr').children('td').eq(2).text();
var job_idx=$(this).data('jid');
//write to appointment database
var data="job_id="+job_idx+"&file_id="+file_id1+"&user_id="+id;
// closure function that wrap your variables
function success(file_id1, file_name1, upload_date1 ... ) {
return function(html) {
var ups='';
ups+='<tr data-file='+file_id1+'><td width="40%">'+file_name1+'</td><td>'+upload_date1+'</td><td>'+upload_desc+'</td><td>VIEW FILE | DELETE</td></tr>';
$(ups).prependTo('.app_table');
}
$.ajax({
type:"POST",
url:"admin_includes/prepend_files.php",
data:data,
success: success(file_id1, file_name1, upload_date1 ...)
});
});
You need to use a closure. You can read about them here: How do JavaScript closures work?
This should work:
$('.addfile_popup').on('click', '.add2_fl', function(){
var me = this;
(function() {
var file_id1=$(me).data('file');
var id=$('.useri').val();
var file_name1=$(me).closest('tr').children('td:first').text();
var upload_date1=$(me).closest('tr').children('td').eq(1).text();
var upload_desc=$(me).closest('tr').children('td').eq(2).text();
var job_idx=$(me).data('jid');
//write to appointment database
var data="job_id="+job_idx+"&file_id="+file_id1+"&user_id="+id;
$.ajax({
type:"POST",
url:"admin_includes/prepend_files.php",
data: {
job_id: job_idx,
file_id: file_id1,
user_id: id
},
success:function(html){
var ups='';
ups+='<tr data-file='+file_id1+'><td width="40%">'+file_name1+'</td><td>'+upload_date1+'</td><td>'+upload_desc+'</td><td>VIEW FILE | DELETE</td></tr>';
$(ups).prependTo('.app_table');
}
});//end ajax
})();
});
Note also I've changed how you pass data to the AJAX call.

Categories

Resources