I'm working on a project with API calls. Basically, I need to be able to pass a parameter to a function with jQuery when a certain button is clicked.
I am working on a project that calls an API to display class buttons to a user.
Each button will be generated based on the presence of a classId, which is called in a jQuery file:
jQuery:
function getCourses() {
$.ajax({
url: apisource + "/courses",
dataType: "json"
}).done(function(data) {
let dataLength = Object.keys(data).length;
for (let i = 0; i < dataLength; i++) {
courseId = data["courses"][i].id; //this is the important part
nameOfClass = data["courses"][i].name;
let classButton = ('<button type=\'button\' class=\'classButton\' onclick=\'javascript:getStudentsInCourses(' + courseId + ');\'>' + nameOfClass + '</button>');
$('#classButtonContainer').append(classButton);
}
})
}
getCourses();
function getStudentsInCourses(currentCourseId) {
console.log("current course id: " + currentCourseId);
$.ajax({
url: apisource + "/course=" + currentCourseId + "/students",
dataType: "json"
}).done(function(data) {
console.log("here are the students");
console.log(data);
}}
What I want to do here is that when a user clicks on a class button, the courseId for that button becomes the "currentCourseId", and is able to be passed to getStudentsInCourses so that it can call the students for that course. I've been scouring the web for the proper way to pass that variable but no method has worked so far. Does anyone have any pointers for how to pass this variable?
So it should be something like this:
when a user clicks one of the classButtons, that button's courseId will pass to the "getStudentsInCourses" function as the "currentCourseId"
In Jquery you can use the click event to execute a logic.
Do not forget to call the function before the click event below.
//your functions
$('.classButtons').on('click', function(){
const id = $(this).attr('id');
//now call your function with the id
getStudentsInCourses(id);
});
If you have questions or misunderstood your request let me know =)
It seems to be working for me. Perhaps, it's your courseId variable that's causing an issue ? Are you sure it's not the same id ?
courseId = data["courses"][i].id;
function getCourses() {
for (let i = 0; i < 5; i++) {
let classButton = ('<button type=\'button\' class=\'classButton\' onclick=\'javascript:getStudentsInCourses(' + i + ');\'>Test ' + i + '</button>');
$('#classButtonContainer').append(classButton);
}
}
getCourses();
function getStudentsInCourses(currentCourseId) {
console.log("current course id: " + currentCourseId);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="classButtonContainer"></div>
Related
I’ve ajax code to append “unit menu” based on “product item” selection.
When I create a new row, and select an item from “product menu” I expected that the “unit input” of the same row must affect and append the “unit menu” belongs to the selection of the "product item" in the same row.
But I noticed that when a new row created by cloning and I select a product (all the above rows also affect, i.e after product item selection the "unit menu" of the same row and the "unit menu" of the above rows also affected)
The next code illustrate what I mean....
$(document).ready(function() {
var purchase = $('.purchase-row').last().clone();
let purchaseCount = 0;
$(document).on('click', '.add_item', function() {
var clone = purchase.clone().prop('id', 'product_' + purchaseCount);
// var clone = purchase.clone().prop('class', 'product_' + purchaseCount);
console.log('clone: ', clone);
$(this).prevAll('.purchase-row').first().after(clone.hide());
clone.slideDown('fast');
$('#product_'+ purchaseCount).find('#id_pro-product').removeClass('product').addClass('newProduct');
$('#product_'+ purchaseCount).find('#id_pro-unit').removeClass('unit').addClass('newUnit');
purchaseCount++;
console.log('PURCHASE-COUNT: ', purchaseCount);// $(this).parent().slideUp('fast');
// The next code for reinitialize select2
var $example = $(".js-programmatic-init").select2();
$example.select2();
});
$(document).on('click', '.purchase-minus', function() {
if (purchaseCount == 0) {
// Do nothing.
alert('You can not delete this row' );
} else {
$(this).closest('.purchase-row').remove();
purchaseCount--;
console.log('PURCHASE-COUNT2: ', purchaseCount);
}
});
$(document).on('click', '.purchase-broom', function() {
$(this).closest('.purchase-row').find('input').val('');
});
$(document).on('change', '.product', function(e){
var id = $(this).val();
console.log('CHANGED-PRODUCT: ', id);
$.ajax({
type: 'POST',
url: '{% url "purchases:get_product_unit" %}',
// dataType: 'json',
// async: true,
// cache: false,
data: {
'pro-product': $('.purchase-row select').closest('.product').val(), // this is right
// find('#id_pro-product')
},
success: function (data) {
console.log(
'FROM SUCCESS: ', data['unit'],
);
var values_3 = data['unit'];
// $('#id_pro-unit').text('');
// $('select').closest('.unit').find('select').text('');
$('select').closest('.unit').text('');
if (values_3.length > 0) {
for (var i = 0; i < values_3.length; i++) {
// $('#id_pro-unit').append('<option>' + values_3[i] + '</option>');
$('select').closest('.unit').append('<option>' + values_3[i] + '</option>');
}
}
},
error: function (){
console.log('ERROR with ajax request in Adding Purchase !!!');
},
});
e.preventDefault();
});
The next image indicates the main row which I want to clone
Image of the main row
The next image indicates an example for creating 2 rows from the main one.
Image of cloning rows
You can notice a bug in the cloning inputs due to using of (select2 plugin),I raised an issue in Select2 forum(but I havegot no answer till now), So I'll ask a new question here about that behavior..
My view to handle ajax
from django.http import JsonResponse
def get_product_unit(request):
data = {}
product = request.POST.get('pro-product')
if product is not None:
unit = UOM.objects.values('unit__name', 'uom_options', 'unit').filter(product_id=product)
print('purchase not purchase')
else:
unit = []
data['unit'] = [(obj['unit__name']) for obj in unit]
print(
'PRODUCT: ', product,
'UNIT: ', unit,
)
return JsonResponse(data)
My tries to fix this problem
1- In fact I tried to make a new ajax call for the new cloned row, but I realize that it can solve by the above ajax code (I don't know how).
I think if I knew to access the "class and id" of the new row itself
$(document).on('change', '.newProduct', function(e){
var id = $(this).val();
console.log('SUCCESS-CHANGE-PRODUCT-FROM-NEW-CLASS: ', id);
$.ajax({
type: 'POST',
url: '{% url "purchases:get_new_row_unit" %}',
// dataType: 'json',
// async: true,
// cache: false,
data: {
'pro-product': id,
// $('#product_'+purchaseCount).closest('.newProduct select').val(),
// find('#id_pro-product')
},
success: function (data) {
console.log(
'FROM SUCCESS-NEW-CLASS: ', data['unit'],
'PRODUCT-FROM-NEW-CLASS: ', data['product'],
);
var values_3 = data['unit'];
// $('#id_pro-unit').text('');
// $('select').closest('.newUnit').text('');
if (values_3.length > 0) {
for (var i = 0; i < values_3.length; i++) {
// $('#id_pro-unit').append('<option>' + values_3[i] + '</option>');
// $('.newUnit select').closest('#product_'+ purchaseCount).append('<option>' + values_3[i] + '</option>');
// $('select').closest('#product_'+ purchaseCount).find('.newUnit').append('<option>' + values_3[i] + '</option>');
//$('select').closest('.newUnit').append('<option>' + values_3[i] + '</option>');
$('.purchase-row #id_pro-unit').append('<option>' + values_3[i] + '</option>');
}
}
},
error: function (){
console.log('ERROR with ajax request in Adding Purchase-New Class !!!');
},
});
e.preventDefault();
});
});
My view
def get_new_row_unit(request):
data = {}
product = request.POST.get('pro-product')
data['product'] = product
if product is not None:
unit = UOM.objects.values('unit__name', 'uom_options', 'unit').filter(product_id=product)
else:
unit = []
data['unit'] = [(obj['unit__name']) for obj in unit]
print(
'PRODUCT: ', product,
'UNIT: ', unit,
)
return JsonResponse(data)
2- Also I tried to do like this Answer But I failed.
3- Also I follow instructions in this answer
But I get the "unit menu" of the main row in all new row when I select an item from the "product menu" in the new row.
My Problem in brief
When I select an item from "product" menu in the first "new cloned row" (or from any new rows)."unit menu" append to all above rows.
What I want to achieve
I want when I select an item from "product menu" only "unit menu" append to the "unit input" of the same row.
I knew that I've missed something but I failed to discover it.
Any suggestions will be appreciated.
=============================================================
My Answer To This Issue After searching and Thinking
=============================================================
Finally I fix my issue as usual (thanks to stackoverflow community).
I want to share my solution of this issue.
Really it took time to understand how it works and how to access the new row or (in other words "how to access the row inputs itself").
My Problem in brief :
When I select an item from "product" menu in the first "new cloned row" (or from any new rows)."unit menu" append to all above rows.
After searching on the web and searching here in the community questions. I found the next answers are useful and helpful.
Thanks to this answer by #martynas
Thanks to this answer by #Евгений Одинец
Thanks to this tutorial
And as I said it can be done by one ajax call.
1- In fact I tried to make a new ajax call for the new cloned row, but I realize that it can solve by the above ajax code (I don't know how).
The final code has became as follow
$(document).on('change', '.product', function(e){
var product_id = $(this).val();
let $el = $(this).closest('.purchase-row');
console.log('SUCCESS-CHANGE-PRODUCT: ', product_id,);
$.ajax({
type: 'POST',
url: '{% url "purchases:get_product_unit" %}',
data: {
'pro-product': product_id,
},
success: function (data) {
if (purchaseCount == 0) {
console.log('purchase count equal to ZERO: ');
console.log(
'FROM SUCCESS: ', data['unit'],
);
var values_3 = data['unit'];
if (values_3.length > 0) {
for (var i = 0; i < values_3.length; i++) {
$el.find('.unit').append('<option>' + values_3[i] + '</option>');
}
}
} else {
let unit = $el.find('.newUnit'); // here I can access the "unit input" of the same row of the "product input"
var values_3 = data['unit'];
unit.text('');
console.log('COUNT IS NOT EQUAL TO ZERO:', values_3);
if (values_3.length > 0) {
for (var i = 0; i < values_3.length; i++) {
unit.append('<option>' + values_3[i] + '</option>');
}
}
}
},
error: function (){
console.log('ERROR with ajax request in Adding Purchase !!!');
},
});
e.preventDefault();
});
Also I found some answers about how to copy table row to another table and these answers help me a lot.
Here is some of them
How to pass clicked/selected row data from one table to another table
Remove row from one table and add it to another with jQuery
How to read dynamically generated HTML table row's 'td' value
I've created an application using codeigniter 3 that gets quizzes stored in the SQL database using a model and populate in the view using ajax and jquery.
Below is the code for populating data inside a div.
$(document).ready(function() {
$.ajax({
url: "/CW2/ASSWDCW2/cw2app/index.php/Leaderboard/quiz",
method: "GET",
dataType: "json"
}).done(function(data) {
$('#modtable tr').remove(); // clear table for new result
var quizzes = data.allQuizzes;
alert(quizzes.length);
var i;
for (i = 0; i < quizzes.length; i++) {
quiz = quizzes[i];
var block = ' <div id="quizMainBox"><h1>' + quiz.quizName + '</h1><br/><h3>' + quiz.creatorName + '<button onclick="myFunction(\''+quiz.quizId+'\')">Try it</button>'+'</h3></div>'
$('#allQuizBox').append(block);
}
});
return false;
// });
});
Below are 3 quizzes populated in the view.
What I want to do is when the user clicks on the "try it " button, I want the user to be directed to the "single_quiz_view" using the quiz id. So I wrote this ajax function (myFunction) below the above code.
function myFunction(quizId) {
// console.log("heyyyy");
// document.getElementById("demo").innerHTML = "Welcome"+quizId ;
$.ajax({
url: "/CW2/ASSWDCW2/cw2app/index.php/Quiz/loadQuiz/",
method: "POST",
}).done(function(data) {
alert("heyyy")
});
return false;
}
where Quiz is the controller name and loadQuiz is the function calling the "single_quiz_view"
//Quiz Controller
public function loadQuiz()
{
// $quizId = $this->uri->segment(3);
$this->load->view('quiz/single_quiz_view');
}
My problem is,
When I click on the "try it button", I get the alertBox inside the done function. I get the status code as 200 but still wont navigate to "single_quiz_view".Console wont give any errors.Please help
I am trying to load a chat box when a contact name is clicked. On initial load it displays the inbox. All functionality works ok until I try and click the contact name a second time. It loads the new contacts chat but also displays the original contact chat even though I set clearTimeout().
Here is the JS file -
$(document).ready(function(){
var contactTimeout;
var inboxTimeout;
function contact() {
var fromName = $('#from').val();
var toName = $("#to").val();
$(".chat-title").replaceWith("<div class='chat-title'>" + toName + "</div>");
$(".chat-form").fadeIn(100);
$.ajax('chat/get-chat.php', {
data: ({ to: toName,from: fromName}),
type: "POST",
success: function(data) {
$(".chat-body").replaceWith("<div class='chat-body'>" + data + "</div>");
contactTimeout = setTimeout(contact, 2000);
}
});
}
function inbox() {
var user = $('#from').val();
$.ajax('chat/get-chat-inbox.php', {
data: ({ user: user}),
type: "POST",
success: function(data) {
$(".chat-body").replaceWith("<div class='chat-body'>" + data + "</div>");
inboxTimeout = setTimeout(inbox, 2000);
}
});
}
// Load inbox when chat box is opened
$(".chat-arrow").click(function(){
clearTimeout(contactTimeout);
inbox();
});
// Load chat from contact name
$(".contact-name").click(function() {
clearTimeout(contactTimeout); // Here I try and kill previous timeout
clearTimeout(inboxTimeout);
var contactName = $(this).attr('id');
$("#to").val(contactName);
contact();
});
});
Why would it just add more timeout functions rather than replace them when a new contact name is clicked?
First i would suggest you instead of using replace each time, you could easily use .html(data) to put new data in existing content of chat-body.
And explanation is you call your function on ajax success (there's wait time to server respond to your request) and if you click in meanwhile on your another call, you will have two calls instead of one, because you can't clear timer that's not started yet.
Well one of the solutions would be, let timer works only through it's default state, and when you need some fast data, you can call your contact without calling the next timer.
$(document).ready(function(){
var contactTimeout;
var inboxTimeout;
/* add parameter which will mean will we call timer or not */
function contact(dotimer) {
var fromName = $('#from').val();
var toName = $("#to").val();
$(".chat-title").replaceWith("<div class='chat-title'>" + toName + "</div>");
$(".chat-form").fadeIn(100);
$.ajax('chat/get-chat.php', {
data: ({ to: toName,from: fromName}),
type: "POST",
success: function(data) {
$(".chat-body").replaceWith("<div class='chat-body'>" + data + "</div>");
/* default calling of timer with repeating */
if (dotimer) { contactTimeout = setTimeout(function(){ contact(true); }, 2000); }
}
});
}
function inbox() {
var user = $('#from').val();
$.ajax('chat/get-chat-inbox.php', {
data: ({ user: user}),
type: "POST",
success: function(data) {
$(".chat-body").replaceWith("<div class='chat-body'>" + data + "</div>");
inboxTimeout = setTimeout(inbox, 2000);
}
});
}
// Load inbox when chat box is opened
$(".chat-arrow").click(function(){
clearTimeout(contactTimeout);
inbox();
});
// Load chat from contact name
$(".contact-name").click(function() {
clearTimeout(inboxTimeout);
var contactName = $(this).attr('id');
$("#to").val(contactName);
/* call function without TIMER, default one will work as it works */
contact(false);
});
});
i am calling an ajax and output api response in textbox. I want count total number of data sets received(counteri) and display it each time i click a button. For example if i click the button first time i want to an alert display counteri=20 and next time i click button it display counteri=40 and... counteri=60.
Currently my code keeps showing 20 each time and not adding the values. could any one tell me how to fix this.Thanks
<script>
var maxnumId = null;
var counteri= null;
function callApi() {
$.ajax({
type: "GET",
dataType: "jsonp",
cache: false,
url: "https://api.somesite.com/......"),
success: function(data) {
maxnumId = data.pagination.next_num_id;
for (var i = 0; i < 100; i++) {
$(".galaxy").append("<div class='galaxy-placeholder'><a target='_blank' href='" + data.data[i].link +"'><img class='galaxy-image' src='" + ok.images.standard_resolution.url +"' /></a></div>");
document.myform.outputtext.value = document.myform.outputtext.value+data.data[i].images.ok.url+'\n' ;
//alert('www!'+i);
counteri=i;
}
}
});
counteri=counteri+counteri;
alert('counteri is now: ' + counteri);
}
</script>
<body>
<br>
<center>
<div id="myDiv"></div>
<div class="galaxy"></div>
<button id="mango" onclick="callApi()">Load More</button>
</html>
EDIT:
Adding this in start of success added up total number of records from ajax response
var num_records = Object.keys(data.data).length;
num_records2=num_records2+num_records;
alert('number of records:'+ num_records2);
and
var num_records2 =null; // outside function
Ajax are async calls.
Move the alert to just after the for. Not outside the success callback.
Looks like the problem is that you are setting counteri to the value of i instead of adding the value of i. Try this instead:
counteri += i;
Ajax calls are asynchronous. You should increment your counter on success, not outside of the ajax call. Something like this:
function callApi() {
$.ajax({
type: "GET",
dataType: "jsonp",
cache: false,
url: "https://api.somesite.com/......",
success: function(data) {
maxnumId = data.pagination.next_num_id;
for (var i = 0; i < 100; i++) {
document.myform.outputtext.value = document.myform.outputtext.value+data.data[i].images.ok.url+'\n' ;
}
counteri=counteri+i;
alert('counteri is now: ' + counteri);
}
});
}
Considering that your ajax request is executed with success, to get what you want you need to declare the i variable before for ( ....) loop as is the follow script:
var counteri = 0;
function callApi() {
$.ajax({
type: "GET",
dataType: "jsonp",
cache: false,
url: "https://api.somesite.com/......",
success: function(data) {
var i,
maxnumId = data.pagination.next_num_id;
for (i = 0; i < 100; i++) {
document.myform.outputtext.value = document.myform.outputtext.value+data.data[i].images.ok.url+'\n' ;
}
counteri=counteri+i;
alert('counteri is now: ' + counteri);
}
});
}
Please ses here demo
EDIT
Also i have rechecked if the variable i is not declared before for(...) loop and works OK. So, the only fix is to remove counter=i from for(...) loop and to change the counteri=counteri+counteri; to counteri+=i;
Take in consideration that the ajax requests produce a number of different events that you can subscribe to. Depending of your needs you can combine this events to accomplish the desired behavior. The complete list of ajax events is explained here
EDIT2
After reading your comments, i see that you need the last value of i globally,
you need to add a second global variable too keep the sum of last i during all ajax requests.
To do this, id have added a minor change to answer:
var counteri = 0,
totali =0;
function callApi() {
$.ajax({
type: "GET",
dataType: "jsonp",
cache: false,
url: "https://api.somesite.com/......",
success: function(data) {
var i,
maxnumId = data.pagination.next_num_id;
for (i = 0; i < 100; i++) {
document.myform.outputtext.value = document.myform.outputtext.value+data.data[i].images.ok.url+'\n' ;
}
counteri = i;
totali = totali + i;
alert('totali is now: ' + totali );
}
});
}
JSFiddle demo
EDIT 3
After your last comment, you need to add in the API response the number of returned rows. For this, you need to change for (i = 0; i < 100; i++) { to something like this:
var num_records = data.num_rows;
for (i = 0; i < num_records ; i++) {
or, without adding the number of rows in response
var num_records = Object.keys(data.data).length;
for (i = 0; i < num_records ; i++) {
So, to be honest I am going to have a hard time explaining this so I apologize in advanced.
Basically I am populating a list of checkboxes with the names of cities. using ajax. What I want to do is allow multiple checkboxes to be checked and store each checkbox value in one single key in local storage. I guess it would look something like this as an example in local storage: city: new york,Los Angeles,Miami. I have tried everything I know and I don't even know how to phrase it in google so if anyone could me that would be great. Ill post my code below.
--This is how I am currently populating the checkbox list:
$(document).delegate("#main", "pagecreate", function () {
var citySelect = new Array();
$.ajaxSetup({
cache: false
})
$.ajax({
url: 'base_city.php',
data: '',
isajax: 1,
dataType: 'json',
success: function (data) {
var $city_box = $('#city-selector');
$city_box.empty();
for (var i = 0, len = data.length; i < len; i++) {
$city_box.append("<label for='city_select'><input type='checkbox' name='city_select[]' class='citySelect' value='" + data[i].city + "'>" + data[i].city + "</label>");
}
}
});
});
--This is how I am currently storing the values:
<script type="text/javascript">
function filterForm() {
var cityNames = $('.city_select').attr('value');
localStorage.setItem("city2", JSON.stringify(cityNames));
window.location = "#main";
location.reload();
}
</script>
try to replace
$('.city_select').attr('value');
by
var arr = [];
$("input[type=checkbox].city_select:checked").each(function(){arr.push(this.value);});