JSON Can't pick any rows of my data array - php

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];
}

Related

Changing value of a td from another api with same name

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']);
}

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]);
}
}

Jquery JSON in PHP

How do I get all the filenames in the php file with jQuery getjson?
Json encoded data from PHP
[{"Filename":"941-2"},{"Filename":"941"}]
My code:
$.getJSON('json.php',{id: id, ajax: 'true'}, function(j){
$('#filename').append(j[0].Filename);
})
Do a simple forloop on j.
For example:
for (var i = 0; i < j.length; i++)
$('#filename').append(j[i].FileName);

How to Get Checked Radio In Array using Java script in php my code attached?

i am trying to get checked radio "id" and "name" as my radio name and id are same like 1,2,3... and so on
my code is here,
var selection=new Array();
var allR = document.getElementsByTagName('input');
var a=0;
var b=0;
for(var i=0; i<allR.length; i++){
if(allR[i].type=='radio') { b++; }
if(allR[i].type=='radio' && allR[i].checked) { a++; }
}
var num=0;
alert(b);
for(var j=1;j<=b ;j++) {
//for(var i=0; i<alr.length; i++){
if(document.getElementsByName('j').checked) {
selection[num]=j;
num++;
alert(j);
//}
}
}
in this code var "b" is the number of radio counts and in second loop i am trying to get checked radio in array and printing them too but it just print the total radio button but do not print checked radio ???
hopes for your suggestions
You should change
if(document.getElementsByName('j').checked)
to
if(document.getElementsByName(j)[0].checked)
as your control has name as 1, 2 , 3. not 'j', and j is your for loop initial, so it not need to be enclosed in single quotes.
as document.getElementsByName returns a collection. you should check element by 0 index.
Just a comment.
the block inside the first for loop can be:
for (var i=0; i<allR.length; i++){
if (allR[i].type=='radio') {
b++;
a += allR[i].checked;
}
}
but there are those who dislike depending on type conversion like that.

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