I have HTML code looped with another jQuery. There is an input which looped too. I want to address it in jQuery Ajax... but only the first input works... and the same values are printed for the rest in the console.
success: function (r) {
var posts = JSON.parse(r)
$.each(posts, function (index) {
$('.timelineposts').html(
$('.timelineposts').html() + '<blockquote><p>' + posts[index].PostBody + '</p><footer>Posted by ' + posts[index].PostedBy + ' on ' + posts[index].PostDate + '<button class="btn btn-default" data-id="' + posts[index].PostId + '" type="button" style="color:#eb3b60;background-image:url("none");background-color:transparent;"> <i class="glyphicon glyphicon-heart" data-aos="flip-right"></i><span> ' + posts[index].Likes + ' Likes</span></button><button class="btn btn-default comment" type="button" data-postid="' + posts[index].PostId + '" style="color:#eb3b60;background-image:url("none");background-color:transparent;"><i class="glyphicon glyphicon-flash" style="color:#f9d616;"></i><span style="color:#f9d616;"> Comments</span></button></footer><input type="text" class="c"><button comment-postid="' + posts[index].PostId + '">comment</button></blockquote>'
)
/////////////////////ajax/////////////////////////
$('[comment-postid]').click(function () {
var buttonid = $(this).attr('comment-postid');
var value = $('.c').val();
$.ajax({
type: "POST",
url: "api/comments1?id=" + buttonid,
processData: false,
contentType: "application/json",
data: '{ "commentBody": "' + value + '"}',
success: function (r) {
//var res = JSON.parse(r)
console.log(buttonid);
console.log(value);
value = "";
buttonid = "";
},
error: function (r) {
console.log("ddd")
}
});
})
})
I have figured it out!
I named each class with a different postid value...so when the loop iterates, each post will have anew class, so I address it in the ajax!
<input type="text" class="'+posts[index].PostId+'" >
and in ajax: var buttonid = $(this).attr('comment-postid');
var v=$('.'+buttonid).val();
Related
I would like once the user selects a different item in the drop box list which was taken from a mysql database, that specific data to that field be displayed.
Currently, I am able to get the value of the item in the drop down box but I am unable to use it.
<h3>Drop down Menu</h3>
<select id="dmenu">
<option selected="selected" id="opt">Choose your station</option>
</select>
<div id="optionT"></div>
$(document).ready(() => {
window.onload = ajaxCallback;
function ajaxCallback(data) {
var data;
var myOptions;
var output;
$.ajax({
url: 'http://localhost:5000/alldata',
type: 'GET',
datatype: 'json',
success: (data) => {
//$.each(data, function (index, value) {
var output = [];
$.each(data, function(key, value) {
output.push('<option value="' + key + '">' + value.Station +
'</option>');
});
$('#dmenu').html(output.join(''));
}
})
}
});
$('#dmenu').on('change', function() {
//alert( this.value );
//alert($(this).find(":selected").value());
function stationData(data) {
var stationName = $(this);
alert(stationName.val());
//var stationName = $(this).value();
//var stationName = $(this).find(":selected").value()
$.ajax({
url: 'http://localhost:5000/alldata',
method: 'POST',
data: {
station: stationName
},
success: (data) => {
$.each(data, function(i) {
data[i]
//console.log(i);
var station_loopOp = '';
//console.log(JSON.stringify(data[i].Station));
station_loopOp += '<li>ID: ' + JSON.stringify(data[i].ID) +
'</li>' +
'<li>Station: ' + JSON.stringify(data[i].Station) +
'</li>' + '<li>Address:
'+JSON.stringify(data[i].Address) +
'</li>' + '<li>' +
Sales: JSON.stringify(data[i].Monthly_CStore_Sales) +
'</li>' + '<li>Operator: ' +
JSON.stringify(data[i].Operator) + '</li>' +
'<li>Top SKU: ' + JSON.stringify(data[i].Top_SKU) +
'</li>' +
'</<li>' + '<br/>');
$('#optionT').html(station_loopOp);
}
});
}
});
You are just defining the function stationData(data){....} inside the callback function but not calling it anywhere inside of it .
Add this line into your function : stationData(<your-data>);
In this code I used JQuery with javascript first I defined room variable as 0. But inside the add_fields function I increment the room variable. add_fields function only works when user clicks a button.
But in keyup method in Jquery always gets the room as 0 because I defined it in the code. Although after I click the button and run add_fields function the room variable increased (I checked it inside the function by console.log(room)) but keyup method still see it as 0.
Help me out please.
var room = 0;
$('#room_fileds').on('keyup', '.item_name' + room + '', function() {
var query = $(this).val();
if (query != '') {
var _token = $('input[name="_token"]').val();
$.ajax({
url: "{{ route('FoodItemController.fetchNameWhenType')}}",
method: "POST",
data: {
query: query,
_token: _token
},
success: function(data) {
$('#name_list' + room + '').fadeIn();
$('#name_list' + room + '').html(data);
}
})
}
});
//set item-id when user selcts the item name from the dropdown list
$(document).on('click', '#list2', function() {
$('.item_name' + room + '').val($(this).text());
$('#name_list' + room + '').fadeOut();
});
function add_fields() {
room++;
var objTo = document.getElementById('room_fileds')
var divtest = document.createElement("div");
divtest.innerHTML = '<div class="form-row"><div class="form-group col"><label>Ingrediants</label><input type ="text" placeholder="Item" name="ingri[' + room + ']" class="form-control item_name' + room + ' "><div id="name_list' + room + '" style="z-index: 1;position:absolute;"></div> </div><div class="form-group col"><label>Amounts</label><input type ="text" placeholder="Amounts" name="amount[' + room + ']" class="form-control"></div><div class="col form-group"><a type="button" id="clickR[' + room + ']" class="btn-floating cyan"><i class="fa fa-check" aria-hidden="true"></i></a><a type="button" id="clickX[' + room + ']" class="btn-floating cyan"><i class="fa fa-close" aria-hidden="true"></i></a></div></div>';
objTo.appendChild(divtest);
document.getElementById('length').value = room + 1;
var hello = document.getElementById("length").value
}
I have this Array
var testFlows = ["test1","test2","test3","test4","test5"];
I'm trying to get the inputs one by one and generating some html (the html generated doesn't really matter).
What matters is that I want to see this html panels by the order of the testFlows array. My code is completely random. If I refresh the page they are on different positions.
One solution would be to make a synchronous ajax but it's deprecated and bad, so what else can I do?
Code:
var testFlows = ["test1","test2","test3","test4","test5"];
$.each(testFlows, function (index, testFlow) {
//get the inputs
$.ajax({
url: '/flow/getInputs',
type: 'post',
data: {testCaseName: testFlow.testCase.name},
success: function (inputNames) {
testCaseAccordion = '<div class="panel panel-default"><div class="panel-heading"><h4 class="panel-title"><a class="collapseTitle" data-toggle="collapse" data-parent="#accordion" href="#collapse-' + testFlow.testCase.name + index + '">' + testFlow.testCase.name + '(' + testFlow.testCase.type.name + ') <span id="eyeIcon" class="fas fa-eye float-right"></span></a></h4></div>';
testCaseAccordion += '<div id="collapse-' + testFlow.testCase.name + index + '" class="panel-collapse collapse"><div id="panel-body-' + testFlow.testCase.name + index + '" class="panel-body"></div></div>';
$('#accordion').append(testCaseAccordion);
if (testFlow.params !== null) {
var inputs = testFlow.params.split(',');
for (var i = 0; i < inputs.length; i++) {
$('#panel-body-' + testFlow.testCase.name + index).append('<strong class="color-red">' + inputNames[i] + ': </strong>' + inputs[i] + '<br>');
}
}
else {
$('#panel-body-' + testFlow.testCase.name + index).append("This test case doesn't have any inputs");
}
}
});
});
You can use promises, for example, in your case:
var testFlows = ["test1","test2","test3","test4","test5"];
function success(testFlowAndInputNames, index) {
var testFlow = testFlowAndInputNames[0];
var inputNames = testFlowAndInputNames[1];
var testCaseAccordion = '<div class="panel panel-default"><div class="panel-heading"><h4 class="panel-title"><a class="collapseTitle" data-toggle="collapse" data-parent="#accordion" href="#collapse-' + testFlow.testCase.name + index + '">' + testFlow.testCase.name + '(' + testFlow.testCase.type.name + ') <span id="eyeIcon" class="fas fa-eye float-right"></span></a></h4></div>';
testCaseAccordion += '<div id="collapse-' + testFlow.testCase.name + index + '" class="panel-collapse collapse"><div id="panel-body-' + testFlow.testCase.name + index + '" class="panel-body"></div></div>';
$('#accordion').append(testCaseAccordion);
if (testFlow.params !== null) {
var inputs = testFlow.params.split(',');
for (var i = 0; i < inputs.length; i++) {
$('#panel-body-' + testFlow.testCase.name + index).append('<strong class="color-red">' + inputNames[i] + ': </strong>' + inputs[i] + '<br>');
}
}
else {
$('#panel-body-' + testFlow.testCase.name + index).append("This test case doesn't have any inputs");
}
}
var arrayOfPromises = testFlows.map(function (testFlow) {
return new Promise(function (resolve, reject) {
$.ajax({
url: '/flow/getInputs',
type: 'post',
data: {testCaseName: testFlow.testCase.name},
success: resolve
});
})
.then(function(inputNames) {
return [testFlow, inputNames];
})
});
Promise.all(arrayOfPromises)
.then(function(results) {
results.forEach(success)
});
jQuery ajax returns a promise, so you could save all the promises into an array, eg:
var testFlows = ["test1", "test2", "test3", "test4", "test5"];
var testFlowsPromises = $.map(testFlows, function(testFlow, index) {
//get the inputs
return $.ajax({
url: '/flow/getInputs',
type: 'post',
data: {testCaseName: testFlow.testCase.name}
}).then(function(inputNames) {
return {
inputNames: inputNames,
testFlow: testFlow
};
});
});
Then, wait until all of them are done:
$.when.apply($, testFlowsPromises).done(function() {
$.each(arguments, function(index, data) {
// do stuff with index, data.inputNames, data.testFlow
});
});
Now you'd have an array of ajax data in the same order.
DEMO:
https://jsbin.com/fixuxezale/edit?js,console
I have a method defined as below :
function updateManagerPreferences(companyId, managerId, userId) {
console.log('inside method');
$.ajax({
type: 'GET',
url: admin_url + "/updatemanager/" + companyId + "/"
+ managerId + "/" + userId,
encode: false,
crossDomain: true
}).done(function (tresult) {
var success_result = jQuery.parseJSON(JSON.stringify(tresult));
console.log(success_result);
});
}
It takes 3 parameters from a button onclick and I am trying to call the method as follows :
<input type='button' class='btn btn-sm btn-success' value='Update' onclick='updateManagerPreferences(" + companyId + "," + $('#managerDropDown').val() + "," + result.ResponseMessage.users[i].user_id + ");'/>
I refered all the similar stackoverflow answers but none of them have helped.
Can someone please tell where am I going wrong ?
You can solve by getting directly your value from inside function and element value by jQuery .
<input type='button' class='btn btn-sm btn-success' value='Update' id='updatemanager' />
<script>
$("#updatemanager").on("click",function(){
var managerId = $('#managerDropDown').val();
var userId = result.ResponseMessage.users[i].user_id;
$.ajax({
type: 'GET',
url: admin_url + "/updatemanager/" + companyId + "/"
+ managerId + "/" + userId,
encode: false,
crossDomain: true
}).done(function (tresult) {
var success_result = jQuery.parseJSON(JSON.stringify(tresult));
console.log(success_result);
});
});
</script>
I did a multilevel ajax call .i.e. make an ajax call and use the id value from the call to make another call... I tried calling a jquery .empty() isn't working for the data generated in the inner ajax call... But when i place the .empty() function on the outer generated element, it worked just fine... How can i fix this issue? This is my code../
$(document).on('click', '.stories', function(e) {
e.preventDefault();
var request = $.ajax({ //first ajax call///
url: 'includes/functions.php?job=front_title',
cache: false,
dataType: 'json',
contentType: 'application/json; charset=utf-8',
type: 'get'
});
request.done(function(output) {
if (output.result === 'success') {
$('.blog').empty();
var jsonArray = $(jQuery.parseJSON(JSON.stringify(output.data))).each(function() {
var id = this.titleID;
var storyTitle = this.story_view;
var frontTitle = '<div class="blog-item"><h3>' + storyTitle + '</h3>' + '<img class="img-responsive img-story" src="images/blog/blog1.jpg" width="100%" alt="" />' + '<div class="blog-content"><div class="entry-meta"><h4>Episodes</h4></div>' + '<div class="well" style="padding-right: 10px; padding-left: 5px; width: 105%;">' + '<ul class="tag-cloud stories">';
var request2 = $.ajax({ ////inner ajax call//////
url: 'includes/functions.php?job=story_episodes',
cache: false,
data: 'id=' + id,
dataType: 'json',
contentType: 'application/json; charset=utf-8',
type: 'get'
});
request2.done(function(output2) {
var i = 1;
if (output2.result === 'success') {
var jsonArray2 = $(jQuery.parseJSON(JSON.stringify(output2.data))).each(function() {
var id2 = this.id;
var title = this.title;
var count = this.episode_count;
if (count == 0) {
frontTitle += id2;
} else if (i % 20 == 0) {
frontTitle += '<li data-id="' + id2 + '" id="singleEpisode"><a class="btn btn-sm btn-primary" href="#story/' + storyTitle + '/' + title + '">' + i + '</a></li></ul><ul class="tag-cloud">';
} else {
frontTitle += '<li style="margin: 1px" data-id="' + id2 + '" id="singleEpisode"><a class="btn btn-sm btn-primary" href="#story/' + storyTitle + '/' + title + '">' + i + '</a></li>';
}
i += 1;
})
}
$('.blog').append(frontTitle);
frontTitle += '</ul></div></div>';
})
})
} else {
console.log('failed');
}
});
});
I really need help for this, i av been on this for two days now... I would really appreciate the help.. or is there a better way i could do this?