How get a variable from HTML in JavaScript/Ajax Call - javascript

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.

Related

Ajax success function to fire another ajax function whilst iterating through loop

I have the following js/jquery code:
var trigger = $('#loadTableData');
var wrapperClass = 'tableAccordionWrapper';
var url = 'data/tableData.json';
var template = 'includes/tableInput.html';
var parentWrapper = $('#selectedTables .sub-content .input-controls');
var href;
var intID;
var items;
var i;
// retrieve node data send from exteral source
addExternalTableInput = function(){
$('.tableAccordionWrapper').remove();
$.ajax({
type: 'GET',
url: url,
dataType: 'json',
success:function(data){
items = data.items
for(i in items){ // this loops 3 times
addExternalTemplate();
}
},
error:function(status){
console.log(status, "Something went wrong");
},
complete:function(){
}
});
}
// append table input to document
addExternalTemplate = function(){
var wrapper;
$.ajax({
type: 'GET',
url: template,
dataType: 'html',
success:function(data){
intID = i;
wrapper = $('<li/>');
wrapper.addClass(wrapperClass);
wrapper.attr('data-id','table-' +intID);
href = $('<a href="#"/>');
wrapper.append(href);
wrapper.append(data).insertBefore(parentWrapper);
var anchor = wrapper.find('> a');
anchor.html(items[intID].tableName); // this returns 'DB_SOURCE_3' for all 3 templates added to the DOM
},
error:function(status){
console.log(status, "Something went wrong");
},
complete:function(){
}
});
}
The concept is that I am using a small json file to run another ajax request. The length of the data in the json file determines how many times the consecutive function should be fired.
The json contains very basic data, but as I loop through it I want the second ajax function to append a template of html to the document (at which point I want to be able to run other functions). One part of data from the json file needs to be injected into the template as it is iterating through the loop.
It appears that the loop works in that in this example the html template gets appended to the dom 3 times, but it passes the last table name in the json to each template that is added to the dom. The second function appears to run after the loop has finished.
Example JSON:
{
"items":[
{
"tableName": "DB_SOURCE_1",
"tableID" : "14739",
"tableDescription" : "Main customer table"
},
{
"tableName": "DB_SOURCE_2",
"tableID" : "184889",
"tableDescription" : "Partitions table"
},
{
"tableName": "DB_SOURCE_3",
"tableID" : "9441093",
"tableDescription" : "Loans Table"
}
]
}
I have tried passing the function in the ajax complete function.
I have also tried to trigger the second ajax function inside the first ajax success function like so:
addExternalTableInput = function(){
$('.tableAccordionWrapper').remove();
$.ajax({
type: 'GET',
url: url,
dataType: 'json',
success:function(data){
items = data.items
for(i in items){
$.ajax({
type: 'GET',
url: template,
dataType: 'html',
success:function(data){
intID = i;
wrapper = $('<li/>');
wrapper.addClass(wrapperClass);
wrapper.attr('data-id','table-' +intID);
href = $('<a href="#"/>');
wrapper.append(href);
wrapper.append(data).insertBefore(parentWrapper);
var anchor = wrapper.find('> a');
anchor.html(items[intID].tableName);
},
error:function(status){
console.log(status, "Something went wrong");
},
complete:function(){
}
});
}
},
But everything I have tried seems to return the same results.
The code has been rewritten somewhat, but here is what I am doing.
var templateData;
addExternalTableInput = function(){
$('.tableAccordionWrapper').remove();
$.ajax({
type: 'GET',
url: url,
dataType: 'json',
success:function(data){
var items = data.items;
for(var i in items){
addExternalTemplate(items[i], i); // pass parameters to this function
}
},
error:function(status){
// etc.
}
});
}
addExternalTemplate = function(item, intID){ // add parameters to our function so we can access the same data
var wrapper;
// load template data once
if(!templateData){ // only run this function if !templateData (should only run once).
$.ajax({
type: 'GET',
url: template,
dataType: 'html',
async: false, // wait until we have a response before progressing
success:function(data){
templateData = data;
},
error:function(status){
console.log(status, "Something went wrong");
}
});
}
// append templateData to the dom
if(templateData){
var href = $('<a href="#"/>');
var tableNameInput = wrapper.find('[name="tables"]');
tableNameInput.val(item.tableName);
// etc
}
// update for, id and name attributes etc.
updateInputAttributes = function(){
// do other stuff to each instance of the template
}();
}
I have moved alot of the global variables out and instead I am using function parameters.
I am only calling the html template once, but for each iteration of the loop I can run functions to update certain atrributes in that instance of the template as well as match items in the json to items in the template.

Manipulate a dynamically generated html element in jquery

I have a little problem here. ¿How i can manipulate a dynamically generated html, in Jquery?
I have a function like:
generatesomething : function(DestinationID,data){
result = $.DoSomething(data)
$('#'+Destinationid).html(data);
}
The script, in other point, receive through ajax an array. Naturally, I will iterate the array like:
$.each(response, function(key, value){
ThisHtml = '<div id="div'+key'"></div>';
$('#MyPlaceHolderDiv').html(ThisHTML)
//In this point, i really need to call my first function
$.generatesomething('div'+key',data)
//But not works!!!!
}
How i can manipulated the generated div using my function?
Thanks in advance!
Edit: in a try to clarify my question, i will paste the exact functions.
I made this function. Please do not laugh at my code, I am newbie in jquery.
jQuery.fn.extend({
/funciones Generales/
piegraph : function(GraficoDestino,tipo,arrayDatos,dato1,dato2,tooltiptemplate,labeltemplate){
var dataPoints = [];
$.each(arrayDatos, function(key, value){
var temporal = {};
temporal.label = value[dato1];
temporal.y = parseInt(value[dato2]);
dataPoints.push(temporal);
});
var opciones = {
animationEnabled : true,
data : [{
type : tipo,
startAngle : 0,
toolTipContent : tooltiptemplate,
indexLabel : labeltemplate,
dataPoints : dataPoints,
}]
};
$('#' + GraficoDestino).CanvasJSChart(opciones);
}
This function works pretty well... if i can give it the destination div to it.
In other part of my script, i have a ajax call:
Generadisco: function(){
var datos = {
"accion":"generadisco"
};
$.ajax({
type: "POST",
url: "blahblah.php",
data: datos,
dataType: "json",
success:function(response){
$.each(response, function(key, value){
esteHTML = '<div id="divdisco'+key+'"></div>
$('#discosplace').append(estehtml);
//the div is generated... but when i do...:
$(this).piegraph('divdisco'+key,'pie', response[3],0,1, "{label} #percent%","{label} ");
//nothing happens
});
}
});
}
I found some error in your code:
$('#MyPlaceHolderDiv').html(ThisHTML)
$.generatesomething('div'+ key ,data)
must to be:
$('#MyPlaceHolderDiv').html(ThisHTML);
$.generatesomething('div'+key',data);
Also try to add console.log(DestinationID) in first line of your function to see passed argument (DestinationID)
If you are generating the dynamic elements after your ajax call, try using async:false.
$.ajax({
url: "abcd.html",
async:false
}).then(function())

Using document.currentScript to append data to divs

I want to append data into divs by passing their id as attributes in a script tag. In this example the first-div should get get 'test1' appended to it, and the second-div should get the 'test2' appended to it.
However, the result it that both 'test1' and 'test2' are appended to second-div. first-div is empty. I'm guessing it has to do with how document.currentScript is functioning. Is there any way to get the result I am looking for?
<div id="first-div"></div>
<div id="second-div"></div>
<script attr1="name1" attr2="name2" to-div="first-div" type="text/javascript">
var this_script = document.currentScript;
var attr1 = this_script.getAttribute('attr1');
var attr2 = this_script.getAttribute('attr2');
var append_div = this_script.getAttribute('to-div');
$.ajax({
url: "/dir?attr1=" + attr1,
type: 'GET',
success: function(data) {
$('#' + append_div).append("test1");
});
</script>
<script attr1="name3" attr2="name4" to-div="second-div" type="text/javascript">
var this_script = document.currentScript;
var attr1 = this_script.getAttribute('attr1');
var attr2 = this_script.getAttribute('attr2');
var append_div = this_script.getAttribute('to-div');
$.ajax({
url: "/dir?attr1=" + attr1,
type: 'GET',
success: function(data) {
$('#' + append_div).append("test2");
});
</script>
Also, in the solution, the scripts cannot have id attributes, which is why I am trying to use document.currentScript.
The reason for this is that the code will be hosted on my servers. The code will append information into the divs the user wants, given parameters passed through attributes on the script tag. In the end the user should be able to use:
<script attr1="var1" attr2="var2" to-div="custom-div" src="http://www.myurl.com/assets/script.js" type="text/javascript"></script>
To insert data into their custom-div based on code I run on my servers dependend on the parameters attr1 and attr2 they provide.
Your problem is that var append_div is a global variable and each time a new script tag is encountered it gets overwritten with the new value.
Since ajax is asynchronous , by the time the responses return the other script tags will have been evaluated so append_div will have the value of the last script tag.
You could fix this by creating a function that wraps the ajax
function doAjax(elementId, attr1) {
$.ajax({
url: "/dir?attr1=" + attr1,
type: 'GET',
success: function (data) {
$('#' + elementId).append("test2");
}
});
}
doAjax(append_div, attr1);
An even better solution as pointed out by #Rhumborl is to use an IIFE
(function( elementId, attr1){
$.ajax({
url: "/dir?attr1=" + attr1,
type: 'GET',
success: function (data) {
$('#' + elementId).append("test2");
}
});
}(elementId, attr1);
Or wrap all of your code in an IIFE and no arguments would need to be passed in.
(function(){
var this_script = document.currentScript;
var attr1 = this_script.getAttribute('attr1');
var attr2 = this_script.getAttribute('attr2');
var append_div = this_script.getAttribute('to-div');
$.ajax({
url: "/dir?attr1=" + attr1,
type: 'GET',
success: function(data) {
$('#' + append_div).append("test2");
}
});
}();

What's the error in following function code of jQuery?

I've written one jQuery function to get the city and state code based upon the zip code value but facing some issue with some errors. Can someone please help me in correcting the mistakes I'm making here.
Following is my code :
$(document).ready(function() {
$("#zip_code").keyup(function() {
var el = $(this);
var module_url = $('#module_url').val();
if (el.val().length === 5) {
$.ajax({
url : module_url,
cache: false,
dataType: "json",
type: "GET",
data: {'request_type':'ajax', 'op':'get_test_category_list','zip_code =' + el.val()},
success: function(result, success) {
$("#city").val(result.city);
$("#state_code").val(result.state);
}
});
}
});
});
Thanks in advance.
The issue is in your data object, you have invalid syntax. Change this:
'zip_code =' + el.val()
To this:
'zip_code': el.val()
The full object should look something like this:
data: {
'request_type': 'ajax',
'op': 'get_test_category_list',
'zip_code': el.val()
},
I think the problem is with data part of the ajax
Change it like this
data: {request_type:"ajax", op:"get_test_category_list",zip_code : el.val()},

.attr selector wont work in a each loop?

Here's the code:
$.ajax({
url: 'AEWService.asmx/previewAsset',
type: "GET",
contentType: "application/json; charset=utf-8",
data: json,
success: function (json) {
var prevObj = jQuery.parseJSON(json.d);
setInterval(function () {
var pId = $('#previewIframe').contents().find('[preview-id]');
$.each(prevObj, function (i, item) {
pId.each(function () {
var pElem = this.attr("preview-id");
if (pElem == item.Id) {
$(this).html(item.Value);
}
});
});
}, 3000);
}
});
this is a DOM node, not a jQuery object. Please read the .each() documentation and have a look at the examples.
Actually you already seem to know that, since you are calling $(this).html()...
Try to change this.attr("preview-id") to $(this).attr("preview-id")
like you use this in $(this).html(item.Value)
Hope this help you.

Categories

Resources