I just started to use ejs. Now, I want to pass data gotten from ajax result to two different div in ejs.
I can pass to a single div but for multiple divs, what change do I need in my code?
$.ajax({
type: "POST",
url: serviceurl + 'Get',
dataType: 'json',
crossDomain: true,
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ "imagesrc": imagesrc }),
success: function (data) {
var property = JSON.parse(data.GetResult);
$('.insideContent>').remove() ;
$('.insideContent').addClass("insidecontentcss") ;
var str = $("#insidecontenttooldata").html();
var data = { tooldata: property };
var content = new EJS({ text: str }).render(data);
$(".insideContent").html(content);
var str1 = $("#well").html();
var data1 = { tooldata: property };
var content1 = new EJS({ text: str1 }).render(data);
$(".well").html(content);
}
and in ejs page i use two script like
<script id="insidecontenttooldata" type="text/x-ejs-template">
//// loop////
</script>
<script id="well" type="text/x-ejs-template">
///loop///
</script>
I guess you have error while targeting second template. Modify code as follows:
var str1 = $("#well").html(); //id of template is 'well' and not the 'welldata'
var data1 = { tooldata: property };
var content1 = new EJS({ text: str1 }).render(data1);
$(".well").html(content1);
Note: as suggested by #kristjan reinhold modified the code to use relative variables.
Related
I'm getting this error ReferenceError: postCssID is not defined
My script is working if I add js code inside my php file but not working if I use separated js file
in php is working
<script type="text/javascript">
var offsets = offsets || new Array();
offsets["<?=$pst_cssid?>"] = 5;
$("#cmt-a-ii<?=$pst_cssid?>").click(function(){
$.ajax({
url: "<?=Url::to(['/comment/view-more'])?>",
type: 'POST',
data: ({st: '<?=$pst_id?>', cssid: '<?=$pst_cssid?>', offset: offsets["<?=$pst_cssid?>"]}),
success: function(result){
$("#cmt-d-ii<?=$pst_cssid?>").append(result);
}
});
offsets["<?=$pst_cssid?>"] += 5;
});
</script>
But if I use separated js file is not working , the error is in this : offsets[postCssID]; in my php file I only declare variables
<script type="text/javascript">
var postCssID = "<?=$pst_cssid?>";
var postID = "<?=$pst_id?>";
var urlLink = "<?=Url::to(['/comment/view-more'])?>";
</script>
I add path to my js file : <script src="/sxct/js/ly-extra-script.js"></script>
var offsets = offsets || new Array();
offsets[postCssID] = 5;
$("#cmt-a-ii"+postCssID).click(function(){
$.ajax({
url: urllink,
type: 'POST',
data: ({st: postID, cssid: postCssID, offset: offsets[postCssID]}),
success: function(result){
$("#cmt-d-ii"+postCssID).append(result);
}
});
offsets[postCssID] += 5;
});
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.
I have a question that I can't seem to answer about Jquery Ajax Response.
I use a for each to select some data from <p> tags in each info_div. This data I then use to do a ajax call to a service that replies with a XML. I want to place some elements from this XML under each div from where I took the two variables. Each div should have it's own reply.
$(document).ready(function () {
$('#action-button').click(function () {
$(".info_div").each(function () {
var var1 = $(this).find('p:nth-child(4)').text();
var1 = var1.slice(-10);
var var2 = $(this).find('p:nth-child(8)').text();
var2 = var2.slice(-1);
$.ajax({
type: "GET",
url: "http://www.mypage.com/mypage&value1=" + "va1" + "&value2=" + "var2",
cache: false,
dataType: "xml",
success: function (xml) {
$(xml).find('member').each(function () {
var name = $(this).find("title").text()
/* how do I get this variable under each $('.info_div') from where I selected the var1 and var2
Every attempt I made places all replies under all the divs in class .info_div */
});
}
});
});
});
});
I would not recommend you to send ajax requests in a loop. Better collect all your data, then send it to the server and handle the response.
Meanwhile, if you insist to do it in a loop, you should make a reference to the iterated element from $(".indo_div) collection, and use it in ajax callback.
$(".info_div").each(function() {
var _that = $(this);
var var1 = $(this).find('p:nth-child(4)').text();
var1 = var1.slice(-10);
var var2 = $(this).find('p:nth-child(8)').text();
var2 = var2.slice(-1);
$.ajax({
type: "GET",
url: "http://www.mypage.com/mypage&value1=" + "va1" + "&value2=" + "var2",
cache: false,
dataType: "xml",
success: function(xml) {
$(xml).find('member').each(function(){
var name = $(this).find("title").text()
that.append(name);
});
}
});
});
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");
}
});
}();
//path = the location of the external file
//scriptBlockId = the id of the external script block (<script id="add-form-tempate" type="text/html-template">)
//fillId = where you want to place the template when rendered
var App = Backbone.View.extend({
render: function (path, scriptBlockId, fillId) {
$.ajax({
async: false,
dataType: 'html',
method: 'GET',
url: path,
success: function (response) {
//Not sure why we have to do this first, before we can select the script block?
var section = $('#main').append(response);
var templateString = $(section).find('#' + scriptBlockId).html();
var compiledTemplate = _.template(templateString);
var temp = compiledTemplate();
$(fillId).html(temp);
}
});
}
});
var app = new App();
app.render(window.siteRoot + 'Scripts/_test1.tmpl.html', 'add-form-template', '#main');
This code works! Why we have to append first I do not know...
You may have had an issue w/ the aysnc $.ajax.
var App = Backbone.View.extend({
render: function(path, scriptBlockId, fillId) {
var self = this;
$.ajax({
async: false,
dataType: 'html',
method: 'GET',
url: path,
success: function(response) {
var templateString = $(response).find(scriptBlockId)[0].innerHTML,
compildeTemplate = _.template(templateString),
temp = compildeTemplate();
$(fillId).html(temp);
}
});
return this;
}
});
var app = new App();
app.render(window.siteRoot + 'Scripts/_test1.tmpl.html', 'add-form-tempate', '#main');
I also tried to do what I think you're trying to accomplish by searching your HTML result for an id and pulling the content out of that script block.