Jquery For Loop with AJAX - javascript

I'm trying to display a drop down menu of options that are from database (I used ajax to retrieve these). The retrieving of the data using ajax is working but what I'm having trouble is displaying them.
This is my code.
<div id='advocacy'>
<select name='advocacy[]'>
<?php
while ($row = mysqli_fetch_array($data)){
echo "<option>".$row['advocacy_name']."</option>";
}
?>
</select>
Add
</div>
and this is the jquery code
$(document).ready(function(){
$("#add").click(function(){
fetch();
});
$("#advocacy").on("click", "#remove", function(){
$(this).parent("div").remove();
});
});
function fetch(){
$.ajax({
url: "viewAd.php",
method: "POST",
dataType: "json",
success: function(retval){
for (var i = 0; i<retval.length; i++){
addAd = "<div id='advocacy'><select name='advocacy[]'><option>"+retval[i].advocacy_name+"</option></select><a href='#' id='remove'>Remove</a></div>";
$("#advocacy").append(addAd);
}
}
})
}
now my expected output would be a single drop down menu but what I'm getting is a drop down menu for every retval[i].advocacy_name. How can i fix it?

You are trying to insert the whole SELECT component for each option of the returned array. Try this callback instead:
success: function(retval){
var addAd = "<div id='advocacy'><select name='advocacy[]'>"
for (var i = 0; i<retval.length; i++){
addAd +="<option>"+retval[i].advocacy_name+"</option>";
}
addAd += "</select><a href='#' id='remove'>Remove</a></div>";
$("#advocacy").html(addAd);
}

The $("#advocacy").append(addAd); should be outside the loop, and it should be replaceWith instead of append since you are overwritting the same element.
Moreover inside the loop you should only add the option elements.
function fetch(){
$.ajax({
url: "viewAd.php",
method: "POST",
dataType: "json",
success: function(retval){
var addAd = '';
for (var i = 0; i<retval.length; i++){
addAd += "<option>"+retval[i].advocacy_name+"</option>";
}
addAdd = '<div id='advocacy'><select name='advocacy[]'>'+ addAd + '</select><a href='#' id='remove'>Remove</a></div>';
$("#advocacy").replaceWith(addAd);
}
})
}

You're adding an entire <div> on every iteration of your loop. Only use the loop to generate <option>s:
success: function(retval) {
let options = '';
for (var i = 0; i < retval.length; i++){
options += `<option>${retval[i].advocacy_name}</option>`;
}
let addAd = `<div id='advocacy'><select name='advocacy[]'>${options}</select><a href='#' id='remove'>Remove</a></div>`;
$("#advocacy").replaceWith(addAd);
}
Or reduce the loop to a line:
success: function(retval) {
let options = retval.map(r => `<option>${r.advocacy_name}</option>`).join('');
let addAd = `<div id='advocacy'><select name='advocacy[]'>${options}</select><a href='#' id='remove'>Remove</a></div>`;
$("#advocacy").replaceWith(addAd);
}

Related

how to set dynamic data in var a

I want to get dynamic data in one <div id = "view"> </div>
I use ajax to take dynamic data from api and insert it with var a. I will try to describe with code what I want to get exactly
$.ajax({
url:'url', // [{id:"1",name:"name1"},{id:"2",name:"name2"},{id:"3",name:"name3"}];
method: 'get',
dataType: "json",
success: function (data) {
data.forEach(function(elem){
var a = "ID: " elem.id +"<b>" + elem.name"</b> ";
})
$('#view').html(a);
}
});
Here you are getting the result in a foreach loop which means "a" contains all the results returned by the ajax call, in order to show only one result in a single div we would need to put the value of each loop call in the div, one way is to append the div for each result inside a parent div. I have modified your code below hopefully it helps.
HTML:
<div id = "dataholder"> </div>
JS:
$.ajax({
url:'url', // [{id:"1",name:"name1"},{id:"2",name:"name2"},{id:"3",name:"name3"}];
method: 'get',
dataType: "json",
success: function (data) {
var j = 1;
data.forEach(function(elem){
var a = "ID: " elem.id +"<b>" + elem.name"</b> ";
var view_div_id = "view-"+j;
$( "#inner" ).append( "<div id ="+ view_div_id +"> </div>" );
$('#view-'+j).html(a);
j++;
})
}
});

Redirect to URL in json response

I have two files fetch.php and index.php. The fetch.php file does a search and converts the results to Json.
Index.php has Jquery which loops through the Json result. One of the cells contains a URL. How can I get a user to redirect to the URL.
//index.php==============================
<script>
$(document).ready(function(){
function load_data(query)
{
$.ajax({
url:"fetch.php",
method:"POST",
data:{query:query},
dataType:"json",
success:function(data)
{
$('#total_records').text(data.length);
var html = '';
if(data.length > 0)
{
for(var count = 0; count < data.length; count++)
{
html += '<hr>';
html += '<tr>';
html += '<div>'+data[count].title+'</div>';
html += '<td>'+data[count].book+'</td><tr/>';
html += '<br/><td>'+data[count].description+'</td><tr/>';
html += '<td><button> VIEW </button> '+data[count].url+'</td>'; //Is there a way to redirect to this URL by clicking on the VIEW button
html += '<hr>';
}
}
else
{
html = '<tr><td colspan="5">No Data Found</td></tr>';
}
$('tbody').html(html);
}
})
}
$('#search').click(function(){
var query = $('#search_id').val();
load_data(query);
});
</script>
Simple solution:
html += '<td><button onclick="window.location.href=\''+data[count].url+'\'"> VIEW </button> '+data[count].url+'</td>';
Consider the following suggestions:
$(function() {
function load_data(q) {
$.ajax({
url: "fetch.php",
method: "POST",
data: {
query: q
},
dataType: "json",
success: function(data) {
$('#total_records').text(data.length);
var row;
if (data.length > 0) {
$.each(data, function(k, d) {
row = $("<tr>");
$("<td>").html(d.title).appendTo(row);
$("<td>").html(d.book).appendTo(row);
$("<td>").html(d.description).appendTo(row);
var e = $("<td>").appendTo(row);
$("<button>").html("VIEW").click(function(e) {
window.location.href = d.url;
}).appendTo(e);
});
} else {
row = $("<tr>");
$("<td>", {
colspan: 4
}).html("No Results Found.").appendTo(row);
}
}
});
}
$('#search').click(function() {
var query = $('#search_id').val();
load_data(query);
});
});
As you can see, this makes use of a few more jQuery parts to help slimline your code. Additionally, we create a Click event callback when the button is created and added to the table.
You had a lot of improper HTML Syntax. My example does not replicate that. A Row Element should contain Cells and not other elements. Yes, you can do it, yet it's not good practice. This is why I removed them. If they are needed for some reason, you should provide a more complete example so it's clear why they are needed.

How to make table updating content without refresh the whole page

i've made a project using php ajax i use it for input data and displaying data into a table. the code work fine but when displaying data the table content didnt update the latest input in there i need to refresh page to update them.
anyone know how to make it update without refresh the whole page?
this my ajax function for input and displaying
INPUT
$(document).on('click','#ok',function(e) {
if ($('#netto').val() == '') {
alert('Kolom Netto Tolong Di Isi');
} else {
var data = $("#form_input").serialize();
$.ajax({
data: data,
type: "post",
url: "../php/bkk/bkk_i.php",
success: function(data){
alert("Data: " + data);
}
});
}
clearInput();
});
$("#form_input").submit( function() {
return false;
});
function clearInput() {
$("#form_input :input").each( function() {
$('#nopol').val('');
$('#netto').val('');
});
}
Display
$(document).ready(function(){
$.ajax({
type: "Post",
url: "../php/bkk/bkk_isel.php",
success: function(data){
var list = JSON.parse(data);
for(var i = 0; i < list.length; i++){
$('#mat').val((list[i]['material']));
$('#lok').val((list[i]['lokasi']));
$('#kpl').val((list[i]['kapal']));
$('#po_numb').val((list[i]['po']));
$('#dok').val((list[i]['doc_mat']));
var tr = "<tr>";
tr += "<td>"+list[i]['no']+"</td>";
tr += "<td>"+list[i]['tanggal']+"</td>";
tr += "<td>"+list[i]['no_pol']+"</td>";
tr += "<td>"+list[i]['netto']+"</td>";
tr += "</tr>";
$("#table_s tbody").append(tr);
}
return false;
}
});
});

how to count total number of ajax response data sets inside for loop?

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++) {

Creating table's and div's in javascript

I've got a javascript document where I'm getting a json object and I want to create div's because I can have more than an instance on the json array. I'm creating an article , changing his innerHTML and adding it to the body but it doesn't get added.
$.ajax({
url: 'myURL',
type: "GET",
data: query,
dataType: 'json',
success: function (data) {
alert(data);
for (var i = 0; i < data.length; i++)
{
var _body = document.getElementsByTagName('body') [0];
alert(_body.innerHTML);
var article = document.createElement('article');
article.id = 'invoiceno'+i;
article.innerHTML = '<div id="client"></div><table class="cabecalho"><tr><th><span>Invoice #</span></th><td id="invoiceno"><span>invoiceno</span></td></tr><tr><th><span>Date</span></th><td id="invoicedate"><span>invoicedate</span></td></tr></table><table class="total"><tr><th><span >Total</span></th><td><span data-prefix>€</span><span id="tots">(TotalAPagar)</span></td></tr></table>';
alert(article.innerHTML);
_body.appendChild(article);
$("#invoiceno"+i).html(data[i].InvoiceNo);
$("#invoicedate"+i).html(data[i].InvoiceDate);
$("#client"+i).html(data[i].CompanyName);
$("#tots"+i).html(data[i].GrossTotal);
}
}
});

Categories