I have a HTML code that extracts variables from JSON as :
<textarea id="{{textarea_id}}" class="comment-insert-text" style = "border: 1px solid #e1e1e1"></textarea>
</div>
<div id="{{btn_id}}" style = "margin: 2px 2px 0 0;width:26px;height: 25px;"class="comment-post-btn-wrapper">
C
</div>
The variables for id are also stored in a hidden temporary variable as:
I want to resolve these variables into a javascript file which executes an onclick function. The function takes in the id variable which is not always static. This dynamic variables are the one, passed to the temporary variable through JSON :
$(document).ready(function() {
$(document).on("click",<id-name to be resolved here> , function() {
alert("yes");
comment_post_btn_click();
});
$(document).on("click", "#comm_first_1", function() {
$('.comment-insert-text').css('border', '1px solid #e1e1e1 ');
});
});
function comment_post_btn_click()
{
var _tt = $('#textarea_id').val();
alert("in");
//Text within the textarea which the person has entered
var _comment = $('<id-name variable>').val();
var _Userid = 1;
// Hard coded the name, should be a session name like $('#Userid').val()
var _Username = "Username_sagar";
// Hard coded the name, should be a session name like $('#Username').val()
if (_comment.length > 0)
{
// proceed with ajax callback
$("#comm_first_1").css('border', '1px solid #e1e1e1');
$.post("comment_insert.php",
{
task: "comment_insert",
Userid: _Userid,
comment: _comment
}
)
.error(
function()
{
console.log("Error: ");
}
)
.success(
function(data)
{
//sucess
//insert html into the ul/li
comment_insert(jQuery.parseJSON(data)); // converts the text which we receive into a javascript object
console.log("ResponseText: " + data);
}
);
console.log(_comment + "Username: " + _Username + "Userid: " + _Userid);
}
else
{
// the textarea is empty, put a border on it
$('.comment-insert-text').css('border', '1px solid #ff0000');
console.log("The textarea is empty");
}
//remove the textarea and ready for another comment
$('#comm_first_1').val("");
}
function comment_insert(data) {
var t = '';
t += '<li class="comment-holder" id="_' + data.comment_id + '">';
t += '<div class="user-img">';
t += '<img src="' + data.profile_img + '" class="user-img-pic" />';
t += '</div>';
t += '<div class="comment-body">';
t += '<h3 class="username-field" >' + data.Username + '</h3>';
t += '<div class="comment-text">' + data.comment + '</div>';
t += '</div>';
t += '<div class="comment-buttons-holder">';
t += '<ul>';
t += '<li class="delete-btn">[x]</li>';
t += '</ul>';
t += '</div>';
t += '</li>';
$('.comments-holder-ul').prepend(t);
}
You can just add the click event to the class, not the id, then pass the this object to the function.
$(document).ready(function() {
$(".comment-insert-text").click(function() {
alert("yes");
comment_post_btn_click(this);
});
$(document).on("click", "#comm_first_1", function() {
$('.comment-insert-text').css('border', '1px solid #e1e1e1 ');
});
});
function comment_post_btn_click(textArea)
{
var _tt = $('#textarea_id').val();
alert("in");
//Text within the textarea which the person has entered
var _comment = $(textArea).val();
var _Userid = 1;
// Hard coded the name, should be a session name like $('#Userid').val()
var _Username = "Username_sagar";
// Hard coded the name, should be a session name like $('#Username').val()
if (_comment.length > 0)
{
// proceed with ajax callback
$("#comm_first_1").css('border', '1px solid #e1e1e1');
$.post("comment_insert.php",
{
task: "comment_insert",
Userid: _Userid,
comment: _comment
}
)
.error(
function()
{
console.log("Error: ");
}
)
.success(
function(data)
{
//sucess
//insert html into the ul/li
comment_insert(jQuery.parseJSON(data)); // converts the text which we receive into a javascript object
console.log("ResponseText: " + data);
}
);
console.log(_comment + "Username: " + _Username + "Userid: " + _Userid);
}
else
{
// the textarea is empty, put a border on it
$('.comment-insert-text').css('border', '1px solid #ff0000');
console.log("The textarea is empty");
}
//remove the textarea and ready for another comment
$('#comm_first_1').val("");
}
function comment_insert(data) {
var t = '';
t += '<li class="comment-holder" id="_' + data.comment_id + '">';
t += '<div class="user-img">';
t += '<img src="' + data.profile_img + '" class="user-img-pic" />';
t += '</div>';
t += '<div class="comment-body">';
t += '<h3 class="username-field" >' + data.Username + '</h3>';
t += '<div class="comment-text">' + data.comment + '</div>';
t += '</div>';
t += '<div class="comment-buttons-holder">';
t += '<ul>';
t += '<li class="delete-btn">[x]</li>';
t += '</ul>';
t += '</div>';
t += '</li>';
$('.comments-holder-ul').prepend(t);
}
Related
I have this function that add's to my cart html, and its working fine. But when i add two of the same Item i get an error(only changes color in the first of each same item).
The console.log(changeBackgroundColor); console.log(changeColorText); gets only the first div of each game.
const addToCart = function () {
getJSON('games.json', function (err, data) {
var cartBets = document.getElementById('cart-bets');
if (err === null) {
console.log('Ocorreu um erro' + err);
} else {
let html = '';
regexPrice = data.types[whichLoteriaIsVar].price;
totalPrice += regexPrice;
let newTotalPrice = data.types[whichLoteriaIsVar].price
.toFixed(2)
.replace('.', ',');
html += '<div class="bar-side-cart">';
html += '<div class="side-by-side">';
html +=
'<div class="menu-thrash-save"><i onclick="deleteItemCart(this)" value="' +
data.types[whichLoteriaIsVar].price +
'" class="far fa-trash-alt" src="img/thrash-can.jfif" width=15 alt="Thrash"></i>
</div>';
html +=
'<div data-style="cart-thrash-side-bar-' +
data.types[whichLoteriaIsVar].type +
'" class="bets-backgroundcolor-lotos-container"></div>';
html += '<div class="top-by-top">';
html += '<p class="cart-right-text">' + totalNumbers + '</p>';
html += '<div class="side-by-side">';
html +=
'<div data-style="cart-text-thrash-' +
data.types[whichLoteriaIsVar].type +
'" class="bets-color-lotos-container">' +
data.types[whichLoteriaIsVar].type +
'</div>';
html += '<div class="cart-money">R$ ' + newTotalPrice + '</div>';
html += '</div>';
cartBets.innerHTML += html;
var changeBackgroundColor = document.querySelector(
'[data-style="cart-thrash-side-bar-' +
data.types[whichLoteriaIsVar].type +
'"]'
);
changeBackgroundColor.style.backgroundColor =
data.types[whichLoteriaIsVar].color;
var changeColorText = document.querySelector(
'[data-style="cart-text-thrash-' +
data.types[whichLoteriaIsVar].type +
'"]'
);
changeColorText.style.color = data.types[whichLoteriaIsVar].color;
console.log(changeBackgroundColor);
console.log(changeColorText);
getCartTotal();
}
});
};
document.querySelector() only returns the first matched element. Try using document.querySelectorAll() with a loop:
var changeBackgroundColor = document.querySelectorAll(
'[data-style="cart-thrash-side-bar-' +
data.types[whichLoteriaIsVar].type +
'"]'
);
changeBackgroundColor.forEach(
element => element.style.backgroundColor =
data.types[whichLoteriaIsVar].color
);
I have the following javascript...
$.post(url, data, function (json) {
var patt = new RegExp('/^\[{"dID":/');
if (patt.test(json)) {
//output json results formatted
} else {
//error so output json string
$('#diaryTable').replaceWith(json);
}
}, 'json');
Basically my json should either be a valid json which begins with
[{"dID":
or it will be
[{ the ex.Message from try catch exception... }]
Unfotunately I get the error JavaScript runtime error: Expected ']' in regular expression
I have check my RegEx /^[{"dID":/ at RegEx101.com with some test data and my test worked as expected. Any ideas anyone?
Ok thanks to all who tried to help... I think my explanation of the problem was not too clear...
I've fixed my issue by checking if I have a valid object... a valid object will have a dID value so I have used...
if (typeof json[0].dID != 'undefined') {
// valid object
var out = "";
var i;
var a = "N"
for (i = 0; i < json.length; i++) {
out += '<div class="dOuter' + a + '">';
out += '<div class="dInner">' + json[i].dDate + '</div>';
out += '<div class="dInner">' + json[i].dRef + '</div>';
out += '<div class="dInner">' + json[i].dTeam + '</div>';
out += '<div class="dInner">' + json[i].dCreatedBy + '</div>';
out += '<div class="dType ' + json[i].dType + '">' + json[i].dType + '</div>';
out += '<div class="dServer">' + json[i].dServer + '</div>';
out += '<div class="dComment">' + htmlEncode(json[i].dComment) + '</div></div>';
if (a == "N") {
a = "A";
} else {
a = "N";
}
}
$('#diaryTable').replaceWith(out);
}
else {
//error so output json string
$('#diaryTable').replaceWith(json);
}
So I have this jquery function that is pulling data from another domain and i want to display that data with ajax when the user enters a value into the search box. As of now the app continuously gives me the error message I wrote from the error state no matter if I search by .productName or .itemCode. Any ideas what I'm doing wrong?
function foodQuery() {
var key = "123456789";
$("#searchinput").keyup(function() {
var value = $(this).val();
foodQuery(value);
});
function foodQuery(key) { // key is passed as a parameter
var foodURL = "http://api.example.com/items?key=" + key;
$.ajax({
url: foodURL,
type: 'GET',
contentType: "text/plain",
dataType: 'json',
success: function(json) {
$.each(json.products, function(index, product) {
// build product block
var htmlString = '<div class="product large-3 columns">';
//open imgwrap
htmlString += '<div class="imgwrap">';
//get img src
htmlString += ' <img class="item_img" src="http://api.example.com/assets/images/' + product.itemCode + '#2x.jpg" />';
// close imgwrap
htmlString += '</div>';
// open textwrap
htmlString += '<div class="textwrap">';
// get productName
htmlString += '<h1 class="product_headline">' + product.productName + '</h1>' ;
// get itemCode
htmlString += '<h4 class="item_id" >#' + product.itemCode + '</h4>';
// get description
htmlString += '<p class="product_desc">' + product.description + '</p>';
// open price
htmlString += '<div class="price">';
// get price & close div
htmlString += '<span class="dollar"><span class="usd">$</span>' + product.price + '</span> <span class="product_desc">per weight</span></div>'
// close divs
htmlString += '</div>';
//console.log(htmlString);
$('.listing').append( $(htmlString) );
}); //end each
}, // end success
error: function(e) {
console.log(e.message);
$('.listing').append( '<h1 class="errmsg" >Sorry, there was an unkown error.</h1>' );
} // end error
}); // end ajax request
$(".listing").html("");
}
}
Since its from a different domain, you can try using jsonp
Im making a site but i want to check the value of a session so i can show a button depending on what the users role is.
the problem im having is that i cant get the value of the session into SessionValue
i will also add that the file is a .js
what i have so far:
function getGroups() {
var SessionValue = <?php print($_SESSION['user_role']); ?>;
$.ajax({
url: 'services/functions.php',
data: {
action: 'getGroups'
},
type: 'post',
success: function (output) {
var result = JSON.parse(output);
result = result.results;
$(result).each(function (index, element) {
var out = "<div class='row'>";
out += "<div class='col-md-3'>";
out += "<img class='img-responsive image_" + index + "' src=" + element.group_image + ">";
out += "</div>";
out += "<div class='col-md-9'>";
out += "<h3>" + element.group_title + "</h3>";
if(SessionValue == "admin"){
out += "<button class='btn btn-primary pull-right' type='button' id='submitPost'>Delete</button>";
}
out += "<h4 class='hidden_" + index + "'>" + moment(element.group_playdate, 'HH:mm:ss').format('HH:mm') + "</h4>";
out += "<p class='hidden_" + index + "'>" + element.group_description + "</p>";
out += "</div>";
out += "</div>";
out += "<hr/>";
$(".groupContainer").append(out);
$(".hidden_" + index).hide();
$(".image_" + index).hover(
function () {
$('.hidden_' + index).fadeIn(200);
},
function () {
$('.hidden_' + index).fadeOut(100);
}
);
});
},
error: function (output) {
console.error("Something went wrong while loading the groups from the database.");
}
});
}
the session is started and the user_role is also defined #login.
I have created a JSON read function but I get error:
TypeError: a is undefined
Here is my code:
$(function() {
var json = $.getJSON("http://localhost/stratagic-json/project_json.php", function() {
console.log("success");
});
var mhtml = '';
$.each(json.slider, function(key, val) {
mhtml += '<li><div class="proj-details-wrap"> <img src="images/' + val.image + '" />';
mhtml += '<div class="proj-badge">' + val.status + '</div>';
mhtml += '<div class="proj-name">' + val.name + ' <span>' + val.location + '</span> </div>';
mhtml += '</div>';
mhtml += ' <div class="container proj-desc">' + val.description + '</div>';
mhtml += '</li>';
});
var $ul = $('<ul class="slides">').append($(mhtml)); // append DOM only one time.
$('.slider').append($ul);
})
The problem is that $.getJSON is an asynchronous method and you're treating it synchronously. json.slider is undefined because $.getJSON actually returns a promise, not the data. The data needs to be accessed via the callback or a promise. This should work:
$(function() {
$.getJSON("http://localhost/stratagic-json/project_json.php", function(json) {
var mhtml = '';
$.each(json.slider, function(key, val) {
mhtml += '<li><div class="proj-details-wrap"> <img src="images/' + val.image + '" />';
mhtml += '<div class="proj-badge">' + val.status + '</div>';
mhtml += '<div class="proj-name">' + val.name + ' <span>' + val.location + '</span> </div>';
mhtml += '</div>';
mhtml += ' <div class="container proj-desc">' + val.description + '</div>';
mhtml += '</li>';
});
var $ul = $('<ul class="slides">').append($(mhtml)); // append DOM only one time.
$('.slider').append($ul);
});
})
You could also do something like this:
$(function() {
var jqXhr = $.getJSON("http://localhost/stratagic-json/project_json.php");
jqXhr.done( function (data) {
// Do something
});
})