I have a functionality.js file which is linked to the front-end, within here I want to click on a div(item1wrapper) and call a function from my index.js file.
Within this functionality.js file I append the div:
socket.on('response', function (data) {
if (msg.includes('totalPrice')) {
if (parsed.itemPrice.length === 1) {
$('#messages').append($('<li id="messageclient">').append($(`
<div id="message-cont" class="message-cont">
<div class="orderDetailsWrapper">
<div class="detailsHeaderWrapper">
<div class="orderNum"></div>
<div class="customerName"></div>
</div>
<div class="textToCustomer">
<p> Please click on the item you want to return</p>
</div>
<div class="itemBoxWrapper">
<div id ="item1Wrapper" class="item1Wrapper" onclick="">
<div class="item1Title"></div>
<div class="item1Price"></div>
</div>`
)).append($('<div id="client-imgorder">')));
$("#messages").animate({ scrollTop: $("#messages")[0].scrollHeight }, 1000);
$('.customerName').text('Customer name: ' + customerName);
$('.orderNum').text('Order number: ' + orderNum);
$('.item1Title').text('Item: ' + item1Title);
$('.item1Price').text('Price: ' + item1Price);
}
Module exports isnt working because it's linked to the front-end?
Here is my function within my index.js file:
function oneCall() {
itemId = itemIdArray[0];
// matching API get
// getRefundCalc API post.
console.log('ngrokurl' + ngrokUrl)
console.log('domain' + domain)
console.log('orderId' + orderId)
console.log('itemId' + itemId)
/*
The Purchase date must be in the future
*/
rp(optionsPOST1)
.then(function (parsedBody) {
Match = parsedBody.Match;
if (Match) {
console.log('Match is true');
httpRequest.post(
`${ngrokUrl}/${domain}/${orderId}`,
{
json:
{
"line_items": [
{
"line_item_id": itemId, "quantity": 1
}
]
}
},
function (error, resp, body) {
if (!error && resp.statusCode == 200) {
console.log(body)
response = responseToFrontEnd
data = [details.chatuser, response]
io.of('/main').to(socket.id).emit('response', data);
}
else {
console.log('error' + error)
}
}
)
// include getRefundCalc within here
} else {
console.log('Match is false');
response = `I'm sorry but your item fell out of the refund policy. Please check the purchase date of your item or if it falls under the minimum price.`
}
});
}
Currently the "onclick" is empty because it wasnt working, when I click on that div in this functionality.js file I want to call that function! and it has to be outside of the functionality file as it requires node modules and needs to be within the socket function!
Related
I'm working in a net core app, i made a HttpPost function to know if an user marked like.
This is the function code:
var likesCancion = (from likesCanc in _context.table
where likesCanc.SongId == idCancion && likesCanc.UserId == idUser
select likesCanc.Likes).FirstOrDefault();
if (likesCancion == 1)
{
return 1;
}
else
{
return 0;
}
I have this:
<div class="col-3 col-sm-2 col-md-2">
<i class="far fa-heart" id="heart" data-idAudio = #song.Id>
<span class="badge" >#song.Likes</span>
</i>
</div>
This is the <div> that I want to change at the start of the page if the user liked it or not.
The #song.Likes its data filled from the database.
I made an ajax request inside a for loop and get the respond of my HttpPost function:
const iconosCorazon = document.querySelectorAll('#heart');
setTimeout(function () {
let idUser = $('#inputidUsuario').val();
function makeRequest(i)
{
$.ajax({
type: "POST",
url: "checkHeart",
data: { idCancion: i, idUser: idUser },
dataType: "text",
success: function (msg) {
console.log(msg);
**if (msg == 1) {
$('.fa-heart').removeClass("far text-dark");
$('.fa-heart').addClass("fa text-danger");
}
else
{
$('.fa-heart').removeClass("fa text-danger");
$('.fa-heart').addClass("far fa-heart");
}**
},
error: function (req, status, error) {
console.log(msg);
}
});
}
for (var i=0;i<iconosCorazon.length;i++) {
let idCancion = iconosCorazon[i].getAttribute('data-idAudio');
makeRequest(idCancion);
}
I want to assign the css class to the correct element coming from the function result.
The issue here its that ajax execute all the elements at once and change the classes only with the last lopped element. So the question is how can i assign the rigth class to each div element. eg: If result == 1 paint red, if result == 0 paint other color.
Sorry for my bad english
Im trying to make this code works
You should use $(".fa-heart:eq(index)") to locate the each element with same class name. Sample code below:
$(".div_test:eq(0)").css("border","2px solid yellow");
Test Result:
Using Meteor framework version 1.2.1
I have a form which adds data to Mongo collection. However I find that the javascript code executes without errors (and all the debug console.log messages appear as i expect) but still the collection doesn't have the data which i just inserted. The issue is that this happens kind of randomly. So sometimes the insertion is working and at other times the insertion doesn't work. Similar issue with the upsert command. my html and js code is pasted below (Note i haven't removed autopublish and insecure packages). Unable to figure what the issue in my code is and need help in this matter
JS Code
ProjectList = new Mongo.Collection("projectList");
ListItem = new Mongo.Collection("listItem");
if (Meteor.isClient) {
Template.create.events({
'submit .add_chapter': function (event) {
var addtoWhat;
var chapName = event.target.chapName.value;
if (event.target.addToWhat.value) {
if (event.target.addToWhat.value.length > 0) {
addtoWhat = event.target.addToWhat.value;
} else {
}
} else {
}
if (addtoWhat) {
var addToWhatItem = ListItem.findOne({name:addtoWhat});
var item = {
name : chapName,
list : [],
}
var id = ListItem.insert(item);
if (id) {
addToWhatItem.list.push(id);
if (!ListItem.upsert({_id:addToWhatItem._id}, addToWhatItem)) {
alert("Unable to upsert");
}
} else {
alert("Unable to insert");
}
} else {
var projList;
if (!ProjectList.findOne({projectId:"123"})) {
projList = {
projectId : "123",
list : [],
};
var topid = ProjectList.insert(projList);
if (topid) {
console.log ("Top Insert succesful with id " + topid);
} else {
console.log ("Error Top Insert unsuccesful with id ");
}
}
projList = ProjectList.findOne({projectId:"123"});
var item = {
name : chapName,
list : [],
}
var id = ListItem.insert(item);
projList.list.push(id);
if(!ProjectList.upsert({_id:projList._id}, projList)) {
console.log("Upsert failed");
} else {
console.log("Upsert successful");
}
}
},
'submit .gen_tree' : function(event) {
getElements();
}
});
function getElements() {
}
if (Meteor.isServer) {
Meteor.startup(function () {
// code to run on server at startup
});
}
HTML Code
<head>
<title>test_hierarchy2</title>
</head>
<body>
<h1>Welcome to Meteor!</h1>
{{> create}}
</body>
<template name="create">
<form class="add_chapter" method="post">
<label>addToWhat</label>
<input type="text" name="addToWhat">
<label>chapName</label>
<input type="text" name="chapName">
<button type="submit">Add</button>
</form>
<form class="gen_tree" method="post">
<button type="submit">generate</button>
</form>
</template>
Try this
ProjectList.update({_id:projList._id}, projList, {upsert:true}, function(error,doc){
if(error){
console.log(error);
}
else{
console.log(doc);
}
})
I want to populate the results div with the already loaded variable, data1, when the back button is clicked. With this code, when the back button is clicked, the results div gets set to "". How do I access the newer version of data1?
Javascript:
function finddata(def,id){
$("#doctitle").html($("#exp").val() + " - Writer's Dictionary");
$("#results").html('<span class="glyphicon glyphicon-cog glyphicon-spin" title="loading..."></span>').fadeIn();
if (def == 1) {
var word = id.innerHTML;
$.get( "processor.php?query=" + word + "&def=" + def, function(data2) {
$("#results").html(data2);
$("#back").click(function(){
$("#results").html(data1);
});
});
} else {
$.get( "processor.php?query=" + $("#exp").val(), function(data1) {
$("#results").html(data1);
});
}
}
HTML:
<div class="container">
<div class="col-md-6 col-md-offset-3" id="results">
<div id="back">Back</div>
</div>
</div>
Try
<div id="back" onclick="finddata(2)">Back</div>
to set def parameter to value other than 1 , which should call $.get() within else statement of finddata
Edit, Updated
var data;
function finddata(def) {
if (def === 1) {
// do stuff
} else {
// if `data` defined
if (data) {
// do not do stuff here
}
// else call `.get()`
else {
var word = id.innerHTML;
$.get( "processor.php?query=" + word + "&def=" + def, function(data2) {
$("#results").html(data2);
$("#back").click(function(){
$("#results").html(data1);
});
});
}
}
}
$("#back").click(function() {
finddata(2)
})
jsfiddle http://jsfiddle.net/229ad2b2/2/
If record has null value then it must show alert message, code not working. Please consider the following code:
function DiseasesByName() {
var dsName = $('#dsName').val();
$.getJSON('http://54.148.253.123/edoctor/HHS_Service/HealthService.svc/DiseasesByName', {
diseaseName: dsName
}, function(data) {
var tasks = $.parseJSON(data.d);
$("#DiseasesList").empty();
$.each(tasks, function(key, value) {
if (data.d != 'null') {
$('<div data-role="collapsible" data-content-theme="a" data-collapsed="true"><h3>' + value.diseaseName +
'</h3><ul data-role="listview" id="diseaseListView" data-inset="true" data-theme="a"><li><strong>Detail:</strong><span>' + value.description + '</span></li></ul></div>').appendTo('#DiseasesList');
// refreshing collapsible created dynamically "its necessary to refresh for a jQuery look and feel"
$('div[data-role=collapsible]').collapsible({
theme: 'b',
refresh: true
});
} else {
alert('No record Found');
}
$("#clear").click(function() {
$("#DiseasesList").empty();
$("#dsName").val('');
});
});
});
}
You need to compare to null itself, not the string "null":
if(data.d!=null)
There are multiple problems
null is not a string value, so your comparison should be data.d != null
The comparison should be done out of the each loop because if data.d is not there, then there is nothing to loop through
The clear click handler should be added outside of the method as that element is not created dynamically
So
function DiseasesByName() {
var dsName = $('#dsName').val();
$.getJSON('http://54.148.253.123/edoctor/HHS_Service/HealthService.svc/DiseasesByName', {
diseaseName: dsName
}, function(data) {
//do it before the loop
var array = data.d ? JSON.parse(data.d) : [];
if (array && array.length) {
$("#DiseasesList").empty();
$.each(JSON.parse(data.d), function(key, value) {
$('<div data-role="collapsible" data-content-theme="a" data-collapsed="true"><h3>' + value.diseaseName +
'</h3><ul data-role="listview" id="diseaseListView" data-inset="true" data-theme="a"><li><strong>Detail:</strong><span>' + value.description + '</span></li></ul></div>').appendTo('#DiseasesList');
// refreshing collapsible created dynamically "its necessary to refresh for a jQuery look and feel"
$('div[data-role=collapsible]').collapsible({
theme: 'b',
refresh: true
});
});
} else {
alert('No record Found');
}
});
}
jQuery(function() {
//it should be out of the `DiseasesByName` method
$("#clear").click(function() {
$("#DiseasesList").empty();
$("#dsName").val('');
});
$('#get').click(DiseasesByName)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input id="dsName" />
<input id="get" type="button" value="get" />
<input id="clear" type="button" value="clear" />
<div id="DiseasesList"></div>
I need to return my behaviors but its not working
function getBehaviorList() {
var behaviors = getBehaviors();
console.log("Making behavior list");
console.log(behaviors);
$.each(behaviors, function (index, value) {
if (value.indexOf("User/.lastUploadedChoregrapheBehavior") < 0) {
$('#installedBehaviors tr:last').after('<tr><td>' + value.split('/').pop() + '</td><td><span class="text-color-green glyphicon glyphicon-play-circle"></span> Start</td></tr>');
}
});
$("#installedBehaviors a").click(function () {
startBehavior(this);
});
}
function getBehaviors() {
console.log("Getting behaviors");
session.service("ALBehaviorManager").done(function (behaviorManager) {
behaviorManager.getUserBehaviorNames().done(function (behaviors) {
behaviors;
console.log(behaviors);
return behaviors;
});
}).fail(function (error) {
console.log("An error occurred: ", error);
});
}
this is the error i get in the console
Getting behaviors
Making behavior list
undefined
Uncaught TypeError: Cannot read property 'length' of undefined
["User/.lastUploadedChoregrapheBehavior/test","User/actura-test/test", "User/check-update", "User/follow-me"]
dose anyone got an idea why?
You can't return a value from the middle of a callback inside your function. That is quite likely an asynchronous call (or two it appears).
You can use deferreds or promises to do this. Here is a simple example using a callback:
function getBehaviorList() {
getBehaviors(function (behaviors) {
console.log("Making behavior list");
console.log(behaviors);
$.each(behaviors, function (index, value) {
if (value.indexOf("User/.lastUploadedChoregrapheBehavior") < 0) {
$('#installedBehaviors tr: last ').after(' < tr > < td > ' + value.split(' / ').pop() + ' < /td><td><a href="#" class="btn btn-default" id="' + value + '"><span class="text-color-green glyphicon glyphicon-play-circle"></span > Start < /a></td > < /tr>');
}
});
$("#installedBehaviors a").click(function () {
startBehavior(this);
});
});
}
function getBehaviors(callback) {
console.log("Getting behaviors");
session.service("ALBehaviorManager").done(function (behaviorManager) {
behaviorManager.getUserBehaviorNames().done(function (behaviors) {
console.log(behaviors);
callback(behaviors);
});
}).fail(function (error) {
console.log("An error occurred: ", error);
callback(); // Possibly callback with [] instead.
});
}
Using deferreds is probably a better pattern, but takes more work and I would need to know more about the services you are calling.
You are call in upon getBehaviours() --> getting behaviors
Next you are making an async call (it does not have a direct answer timewise, but later.
You are returning to getBehaviorList without any returned values (undefined), which has no length.
Then later you receive the answer from getUserBehaviorNames and the console.log(behaviors).
You need to call a new function from .done()
function continueBuildBehaviorList(behaviors) {
$.each(behaviors, function (index, value) {
if (value.indexOf("User/.lastUploadedChoregrapheBehavior") < 0) {
$('#installedBehaviors tr:last').after('<tr><td>' + value.split('/').pop() + '</td><td><span class="text-color-green glyphicon glyphicon-play-circle"></span> Start</td></tr>');
}
});
$("#installedBehaviors a").click(function () {
startBehavior(this);
});
}