Changing value of a td from another api with same name - php

So i am using 2 apis of php that echo's value in json encode
one api contains all the data and the other api has the same data but only where one of the value is true
e.g
data from api contains 50 rows
data from api 2 contains 20 rows because that api shows same data but where a value is Yes
i cannot use join in tables as they are from different sources
so i was trying to join them using jQuery
with my code only the first value changes but not the rest
ive tried the following code but it will only change the first value
$.get("customapi.php", {
data: 'get_data'
}, function(response) {
$("#autovisit tbody").html("");
for (var i = 0; i < response.length; i++) {
html = "<tr>";
html += `
<td><b>${i+1}</b></td>
<td>${response[i]['name']}</td>
<td>${response[i]['p_name']}</td>
<td>${response[i]['p_type']}</td>
<td>${response[i]['a_date']}</td>
<td>${response[i]['l_date']}</td>
<td>${response[i]['r_date']}</td>
<td>${response[i]['d_name']}</td>
<td id="get_visit" class="text-center">NO</td>
<td id="get_invoice" class="text-center">NO</td>`;
$("#autovisit tbody").append(html);
$.get("customapi2.php", {
data: 'get_data'
}, function(result) {
for (var i = 0; i < result.length; i++)
$("#get_visit").text(result[i]['VISITED']);
$("#get_invoice").text(result[i]['INVOICED']);
}, 'JSON');
}
}, 'JSON');
in the above api both have the same data in the following values
{response[i]['name']}
{response[i]['p_name']}
{response[i]['p_type']}
{response[i]['a_date']}
{response[i]['l_date']}
{response[i]['r_date']}
{response[i]['d_name']}
the rest two
that is visit and invoice is comming from the other api and i need to change that text but with this code when the first name is true it only changes that not the others

You can use the following code to update your column values.
What you will be doing here is assigning a specific id to a data cell and then using that id to update data cell based on values from second api call.
This is done assuming that name is unique in response
$.get(
"customapi.php",
{
data: "get_data"
},
function(response) {
$("#autovisit tbody").html("");
for (var i = 0; i < response.length; i++) {
html = "<tr>";
html += `
<td><b>${i + 1}</b></td>
<td>${response[i]["name"]}</td>
<td>${response[i]["p_name"]}</td>
<td>${response[i]["p_type"]}</td>
<td>${response[i]["a_date"]}</td>
<td>${response[i]["l_date"]}</td>
<td>${response[i]["r_date"]}</td>
<td>${response[i]["d_name"]}</td>
<td id="visit-`${response[i]['name']}`" class="text-center">NO</td>
<td id="invoice-`${response[i]['name']}`" class="text-center">NO</td>`;
$("#autovisit tbody").append(html);
}
$.get(
"customapi2.php",
{
data: "get_data"
},
function(result) {
for (var i = 0; i < result.length; i++)
$("#visit-`${result[i]['name']}`").text(result[i]["VISITED"]);
$("#invoice-`${result[i]['name']}`").text(result[i]["INVOICED"]);
},
"JSON"
);
},
"JSON"
);
Please not that your 2nd API call should be outside the for loop, otherwise it will have too many unnecessary requests

You need UNIQUE IDs!
There cannot be more than one get_visit and one get_invoice so change the ID of the cells to some unique you also can know in the second code
An actual ID is best, so change the uniqueID combo below to an database ID if you have it
var uniqueID;
for (var i = 0; i < response.length; i++) {
uniqueID = response[i]['name'] + "_" + response[i]['p_name']; // or whatever is unique
html = "<tr>";
html += `
<td><b>${i+1}</b></td>
<td>${response[i]['name']}</td>
<td>${response[i]['p_name']}</td>
<td>${response[i]['p_type']}</td>
<td>${response[i]['a_date']}</td>
<td>${response[i]['l_date']}</td>
<td>${response[i]['r_date']}</td>
<td>${response[i]['d_name']}</td>
<td id="${uniqueID}_visit" class="text-center">NO</td>
<td id="${uniqueID}_invoice" class="text-center">NO</td>`;
}
html += "</tr>";
...
for (var i = 0; i < result.length; i++)
uniqueID = result[i]['name'] + "_" + result[i]['p_name']; // or whatever is unique from above
$(`#${uniqueID}_visit`).text(result[i]['VISITED']);
$(`#${uniqueID}_invoice`).text(result[i]['INVOICED']);
}

Related

Display DB fetched data using foreach loop in ajax request using jQuery

MY PHP response after ajax call
echo json_encode(
array(
"id" => $id,
"msg" => $msg,
"data" => $result_data_came_from_foreach_loop
)
);
Then the result is here in JSON format
data:
1:"data1"
2:"data2"
3:"data3"
4:"data4"
5: "
"
"
id:"success"
msg:"Data has been fetched Successfully"
The problem is adding these data in html table
limit = 20; // limit of already displayed rows
total = 50; // total table rows count in db
dataType: 'json',
success:function (res){
if(res.id == "success"){
for(var i=limit; i>total; i--){ // I think I misconfigured here
console.log(res.data[i]);
$('.table tr:last').after("<td>"+res.data[i]+"</td>");
}
}
}
Nothing displayed in the HTML table please help?
for(var i=limit; i>total; i--)
Your loop variable is starting at limit i.e. 20, and the code is being executed while it is greater than total i.e. 50. So it's not being executed at all.
if you want to loop through res.data and stop either at the end, or at the limit, try this:
for(var i = 0; i < res.data.length && i < limit; i++)

JSON Can't pick any rows of my data array

Got an issue today, I can't pick any info of my JSON array.
Example of a row :
[{"0":"84","id_account":"84","1":"1500","count_soleillos":"1500","2":"2018-06-26 10:19:43","date_purchase":"2018-06-26 10:19:43","3":"Doe","name_account":"Doe","4":"Jhon","nickname_account":"Jhon","5":"standard","type_offer":"standard"},
And here is my javascript
$.ajax({
type: 'POST',
url: example/example.php,
success: function (data) {
var jsonData = JSON.parse(data);
var container = $('liste-offer');
for (var i = 0; i <= jsonData.length; i++) {
var counter = jsonData[i];
Info : when I do jsonData.length, it returns 8 rows (exact). When I do
jsonData[0] or anything else, it returns undefined
Hope you could help me :)
You could use < jsonData.length; instead of <= jsonData.length; because you are indexing into the object and that has 8 properties instead of 9. Then <= will match 0 till 8 inclusive and jsonData[8]; does not exist and will give you undefined.
You could update your code to:
for (var i = 0; i < jsonData.length; i++) {
Try to access any key by below way:
jsonData[0]['id_account'] or jsonData[0].id_account
For exact solution please update your question with complete JSON and with your JavaScript method
Try this, it's working for me
for (var i = 0; i < jsonData.length; i++) {
alert(jsonData[i].id_account);
var counter = jsonData[i];
}

appending $.ajax response to Jquery UI dialog box in table format

I am getting data in a php file from db as
while ($row=mysqli_fetch_row($result))
{
printf ("beacon id : %s \n",$row[2]);
printf ("beacon uuid :(%s)\n",$row[3]);
}
now i want to append that data in table and show in JQueryUI Dialog box like this
In ajax success form i tried to create hardcore table and get data
success: function(response){
for (var i = 0; i < 3; i++) {
var row = $('<tr></tr>').appendTo(mytable);
for (var j = 0; j < 3; j++) {
$('<td></td>').text("text1").appendTo(row);
}
}
$('<table></table>').appendTo("#dialog");
$("#dialog").dialog("open");
}
it is working fine
///////////////
when I tried to get to get my data in table its not working
I tried
success: function(response){
var table = $("#table tbody");
$.each(response, function(idx, elem){
table.append("<tr><td>"+elem.id+"</td></tr>");
});
$('<table></table>').appendTo("#dialog");
$("#dialog").dialog("open");
}
but it is not working ,
console.log is coming like
what can i modify to display data ?
You're not appending the table with data, instead you're creating a new empty table element and appending it.
Edit:
You also can't loop over a string (which is the ajax response). If you output the html in php things will be simpler. This is also untested but hopefully you get the idea.
php:
while ($row = mysqli_fetch_row($result)) {
printf("<tr><th>beacon id :<th> <td>%s</td><tr>", $row[2]);
printf("<tr><th>beacon uuid :<th> <td>(%s)</td><tr>", $row[3]);
};
js:
success: function (response) {
if (response) {
var table = $("#table tbody");
table.append(response);
table.appendTo("#dialog");
$("#dialog").dialog("open");
}
}
First, I would adjust your PHP so that it is sending back JSON data. The data you are sending back now is just text. It will not be read as an Object by JS.
PHP
$beacon = array();
while ($row=mysqli_fetch_row($result)){
$beacon[] = array("id" => $row[2], "uuid" => $row[3]);
}
header('Content-type:application/json;charset=utf-8');
echo json_encode($beacon);
See: Returning JSON from a PHP Script
This creates an array of arrays. The resulting page should be something like:
[
{
"id": "Beacon00UUID::fda50693-a4e2-4fb1-afcf-c6eb07647825",
"uuid": "(Beacon00RSSI::-69)"
},
{
"id": "Beacon01UUID::2f234454-f491-1ba9-ffaf-000000000001",
"uuid": "(Beacon01RSSI::-53)"
},
{
"id": "Beacon02UUID::b9407f30-f5f8-466e-aff9-25556b57fe6d",
"uuid": "(Beacon02RSSI::-75)"
},
{
"id": "Beacon04UUID::00000000-0000-0000-0000-000000000000",
"uuid": "(Beacon04RSSI::-88)"
},
]
This will allow your jQuery to collect the content as JSON. In your success callback, you can handle this better. this is also assuming you have dataType: "json" elsewhere in your AJAX call.
jQuery
success: function(response){
var $tbl = $("<table>");
$.each(response, function(key, val){
var $row = $("<tr>").appendTo($tbl);
if(key % 2 == 0){
$row.addClass("even");
} else {
$row.addClass("odd");
}
var $cell = $("<td>").html(val.id).appendTo($row);
});
$("#dialog").html($tbl.prop("outerHTML")).dialog("open");
}
Now, if your data was coming back with a key of beacon id, you would need to call this exactly. For example, it would not be elem.id, it would have to be elem['beacon id'] to call the right index in the object. You can't use the dot notation that includes a space in the index name. Bare that in mind when naming your indexes.
There is a subtle difference with $.each() and .each(), the former is designed for arrays and objects, with a key and value pair and the latter designed for jQuery objects, with an index and element pair. nothing wrong with what you did, just explaining why you might use one over the other.
Hope this helps. Let me know if something is not clear.

Processing json where the number of json array is dynamic

I have a json response from php to ajax. The thing is depending on the value entered in a text box the number of json arrays vary. Example: sometimes it may return {"count1":10, "ccc1":30} and sometimes like this {"count1":10, "ccc1":32, "count2":40, "ccc2":123,"count3":32,"ccc3":21}. I extract the value in jquery this way:
success: function(response){
var count = response.count1;
//do something
}
But now since the number of counts are different I used a loop. Question is I can figure out how many of them I am receiving but how can I process them? The var count = response.count needs to be specific right? I cannot just concate any strings like this:
var count = 0;
while(something){
count = count + 1;
var str = "count"+count;
var whatever = response.str;
}
So, can someone please help me with a suitable solution in this case?
You are on the right track there. Something like this should work for you.
var i = 1;
while(response['count' + i]) {
var count = response['count' + i++];
}
You can access the properties as if they were array indices. so response['count'+i] works.
Loop through all properties and add them in a variable like following.
var response = { "count1": 10, "ccc1": 32, "count2": 40, "ccc2": 123, "count3": 32, "ccc3": 21 };
var count = 0;
for (var prop in response) {
if (prop.startsWith('count'))
count += response[prop];
}
console.log(count);
To retrieve all values use jQuery $.each function.
var data_tmp = '{"count1":10, "ccc1":32, "count2":40, "ccc2":123,"count3":32,"ccc3":21}';
var data = $.parseJSON(data_tmp);
$.each(data, function(k,val){
if(k.toLowerCase().indexOf("count") >= 0){
$('.wr').append('<div>' + val + '</div>')
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div class="wr"></div>
success: function(response){
var count = response.count1;
var object = JSON.parse(response);
alert(object.length);
for (i = 0; i < object.length; i++) {
console.log(object[i]);
}
}

How to iterate through multiple rows in jquery using ajax, json, and php?

I have a php page that returns json like this:
while ($row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS)) {
$rows[] = $row;
}
print json_encode($rows);
When I run the php page I get back something like:
[{"phone":"1234567"},{"phone":"1234567"}]
This is my jquery code:
$.ajax({
url: 'test.php',
type: 'POST',
dataType: 'json',
contentType: "application/json; charset=utf-8",
success: function(response) {
$.each(response, function() {
$.each(this, function(key, value){
alert(key + " --> " + value);
});
});
}
});
});
I got that from another SO question. This will give me my keys and value in the alert. This was just for me to make sure everything works. I have searched but cannot figure out how to just get one value. Say I wanted the name, what do I put? I have tried:
success: function(response) {
var obj = $.parseJSON(response);
alert( obj.phone );
}
But since it is multiple rows it won't work unless I have, and it also fails when I have one row like this:
echo json_encode(array("phone" => "123")
How do I get a single value from a row?
How do I iterate through multiple rows and only get one of the column values?
The response variable is an array of objects. To access a single index in your response variable:
var phone = response[0].phone;//replace `0` with the index you want
If you end-up iterating through your response in a loop make sure to do it like this for the best performance:
var len = response.length;
for (var i = 0; i < len; i++) {
console.log(response[i].phone);
}
Check-out this jsperf to see how much faster this type of loop is than for(i in array): http://jsperf.com/for-in-tests
The response JSON is an array. To get the first phone number, retrieve the first object through response[0], then get the property using .phone:
success: function(response) { //response = array, when using dataType:"JSON"
alert(response[0].phone);
}
Replace 0 with any number between 0 and response.length to get the corresponding phone property.
Javascript:
for (var i; i < response.length; i++) {
console.log(response[i].phone);
}

Categories