JavaScript(jquery) function does not finish its excution - javascript

I have a php file which returns a large json string (~2000 elements , each have 14 child element).
I use jquery ajax to fetch the json and put them in to id-identified table.
but it stops filling in mid-way(~1100).Here's the code:
var max = <?php echo $max; ?>; //max is the total number of elements in the database called by php.
$.ajax({
url: "all_arr.php",
type: 'POST',
dataType: "json",
success: function(data) {
for (var i = 0; i < max; i++) {
$("#name_" + i).html(data[i].eng);
$("#slot_" + i).html(data[i].slot);
}
}
});
UPDATE:The code works fine in Safari,but not in chrome.
Uncaught TypeError: Cannot read property 'eng' of undefined

How you get count of values in data table?:
var max = <?php echo $max; ?>; //max is the total number of elements in the database called by php.
It is wrong. You pass data parameter in your success function. Loop through it and receive all data this way.
Your final code will be (if data is array):
$.ajax({
url: "all_arr.php",
type: 'POST',
dataType: "json",
success: function(data) {
for (var i = 0; i < data.length; i++) {
$("#name_" + i).html(data[i].eng);
$("#slot_" + i).html(data[i].slot);
}
}
});
Also, you can use this:
$.ajax({
url: "all_arr.php",
type: 'POST',
dataType: "json",
success: function(data) {
var i;
for (i in data) {
$("#name_" + i).html(data[i].eng);
$("#slot_" + i).html(data[i].slot);
}
}
});
Both approaches based on length of received object in success function, but not on length you specified. Possibly, you set wrong length of data array, which you want to receive in this code: var max = <?php echo $max; ?>;.
Tell me about result.

Please post the code for all_arr.php because the problem could be there.
try the error paramenter if there is any errors:
try the max=2200 see if that works. max maybe set to wrong number in php.
.
var max = <?php echo $max; ?>;
$.ajax({
url: "all_arr.php",
type: 'POST',
dataType: "json",
timeout: 10000, //add this if there a timeout
success: function(data) {
for (var i = 0; i < max; i++) {
if(data[i] != undefined){
$("#name_" + i).html(data[i].eng);
$("#slot_" + i).html(data[i].slot);
}
}
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
Timeout Error:
Your error event handler takes the three arguments (xmlhttprequest, textstatus, message) when a timeout happens, the status arg will be timeout. Then add:
timeout: 10000, //10seconds
Regarding your error: Uncaught TypeError: Cannot read property 'eng' of undefined
This is cleary an error in the .php file and what it returns.
if(data[i] != undefined){ // if nothing is returned, print nothing.

Related

Uncaught TypeError: Cannot read properties of undefined (reading 'Hobbies')

I am running into an interesting issue that is throwing me for a loop. I am doing a Sharepoint RestAPI call that returns data correctly, when I run a for loop over the data it builds out the html but still tosses the error that I used as the title. Code is below. If I console log each loop it will return the value. The HTML also works fine. The issue is that error still comes up.
function getSlideData() {
var query = "$expand=AttachmentFiles&$select=Title,Team,State,Location,Hobbies,Favorite,Askme,GreatPlace,imageFact,ImageText,Attachments,AttachmentFiles&$expand=AttachmentFiles&$top=1000&$orderby=Created desc&$filter=Display eq 'Active'";
var svcUrl = SITE_URL + "_api/web/lists/getbytitle('"+LIST_NAME+"')/items?"+query;
var employeeData;
$.ajax({
url: svcUrl,
type: "GET",
headers: { "Accept": "application/json; odata=verbose" },
async: false,
success: function (data) {
employeeData = data.d.results;
},
error: function (xhr) {
alert("Can't get list items.", xhr.status + ": " + xhr.statusText);
}
});
return employeeData;
}
function buildSlides() {
var slideData = getSlideData();
var sliderWrapper = $('#slider-wrapper');
var sliderWrapperContent = "";
for(i=0;i<=slideData.length;i++) {
sliderWrapperContent += '<div><h2>'+slideData[i].Hobbies+'</h2></div>';
sliderWrapper.html(sliderWrapperContent);
}
}
The error is that you are trying to access an index that does not exist in the array because of <= in the for loop, try to use < when you use .length of an array.

JQuery Ajax limiting deep recursion "too much recursion"

The idea is that I send lots of synchronous requests to an API to create a JSON that I will need later to do some clusterizations. This API gives me information about articles, review etc. from a site (scopus.com). First I send a request based on a query from which I get a JSON which contains information about some articles. These articles are cited by other articles. I have to get information about these ones too so I need recursion. The problem is that I get an error because of "too much recursion". It seems that the error appears when the recursion is over and the program has to go back to the "root"/the first call. So the program will look like a very deep tree.
Pure Javascript does have this limitation too? What can I do?
Also I have to do SYNCHRONOUS requests otherwise the JSON I will get will be a mess.
EDIT:
I tested the script on queries that need a small recursion such as a tree with 4-5 levels.
var result = '{"entry":[ ';
function query(){
var results = getNumberResults();
if(results>0)
{
var pages = Math.ceil(results/25);
var i;
for(i=0; i<pages; i++){
$.when($.ajax({
url: url,
type: "GET",
async: false,
headers: {'Accept':'application/json'},
success: function(data){
$.each( data['search-results']['entry'], function( i, item ) {
get info from json and save it in my variable
if(data['search-results']['entry'][i]['citedby-count'] > 0)
getCitedBy(data['search-results']['entry'][i]['eid']);
else{
result += '"children-id":[]},';
}
});
}
}));
}
}
result = result.slice(0,-1);
result += "]}";
}
function getCitedBy(eid){
var results = getCitedByNumberResults(eid);
if(results>0)
{
var pages = Math.ceil(results/25);
var i;
for(i=0; i<pages; i++){
$.when($.ajax({
url: url,
type: "GET",
async: false,
headers: {'Accept':'application/json'},
success: function(data){
$.each( data['search-results']['entry'], function( i, item ) {
get info from json and save it in my variable
if(data['search-results']['entry'][i]['citedby-count'] > 0)
getCitedBy(data['search-results']['entry'][i]['eid']);
else{
result += '"children-id":[]},';
}
});
}
}));
}
}
}
function getNumberResults(){
var innerResult;
$.ajax({
url: url,
type: "GET",
async: false,
headers: {'Accept':'application/json'},
success: function(output){
innerResult = output['search-results']['opensearch:totalResults'];
},
error: function (xhr, ajaxOptions, thrownError) {
innerResult = 0;
}
});
return innerResult;
}
function getCitedByNumberResults(eid){
var innerResult;
$.ajax({
url: url,
type: "GET",
async: false,
headers: {'Accept':'application/json'},
success: function(output){
innerResult = output['search-results']['opensearch:totalResults'];
},
error: function (xhr, ajaxOptions, thrownError) {
innerResult = 0;
}
});
return innerResult;
}
The problem was as trincot mentioned and I also thought so was that 2 or more articles are referencing each other making an infinite cycle. I fixed it by searching my string variable for the unique identifier. So if in my variable already exists and article with that identifier I will skip recursion for the current article.
So I tested my script again for relative short queries (few hundreds of articles returned) because there are queries with huge outputs (millions of articles). When I will search for big queries I could come upon string size limitations(browser specific) or even “too much recursion”. If so I will let you know.
Advice: if “too much recursion” error occurs in your ajax request search first for an infinite cycle because this is the most probable cause.

Uncaught TypeError: undefined is not a function jquery

I really new to ajax and jsonp and having a problem reading from a file when called. The code works. But every time I call the same function again in the same script it says 'Uncaught TypeError: undefined is not a function'. If the function works once shouldn't it always work?
Here is a sample of my code
var resultAmount = 0;
start = function(teamFile, rowsInDB, ratio_Over_rows, opplastx_gp, callfunction){
//ajax ONLY calls don't return anything
(function($) {
//Connects to the json teamFile
var url = 'http://xxx.co.uk/football/'+teamFile+'.json?callback=?';
//Automatic refresh
$.ajax({
type: 'GET',
url: url,
async: false,
jsonpCallback: 'jsonCallback',
contentType: "application/json",
dataType: 'jsonp',
success: function(data) {
if(callfunction == 'mep'){
resultCount(data, rWin, count);
resultCount(data, rDraw, count);
resultCount(data, rLose, count);
//the total of w/d/l
resultAmount = total[rWin] + total[rDraw] + total[rLose] ;
}else{}
},
error: function(e) {
console.log(e.message);
}
});
})(jQuery);
}
//Adds the results w, d, l up
resultCount = function(for_data, result, count_r){
count_r = 0;
//Goes through the data
for(k in for_data){
//if equals w, d, 1
if(for_data[k].Results == result){
//Add 1
count_r++;
}else{
}
}
}
//Then I call the function start twice only one works
console.log(start('ast', 7,5,5, 'mep'));
console.log(start('ars', 7,5,5, 'mep'));
Only the first function runs and not the second it says 'Uncaught TypeError: undefined is not a function'. And when I change them around the first function runs and the second says 'Uncaught TypeError: undefined is not a function'.
If it helps my file looks like this
jsonCallback([{"Brad Guzan":"yes","Jed Steer":"no","Ashley Westwood":"yes","Fabian Delph":"no","Ron Vlaar":"yes","Andreas Weimann":"yes","Gabriel Agbonlahor":"no","Nathan Baker":"yes","Leandro Bacuna":"yes","Karim El Ahmadi":"no","Christian Benteke":"no","Ciaran Clark":"no","Matthew Lowton":"yes","Ryan Bertrand":"yes","Antonio Luna":"no","Marc Albrighton":"yes","Libor Koz\u00e1k":"no","Aleksandar Tonev":"no","Yacouba Sylla":"no","Grant Holt":"yes","Joseph Bennett":"yes","Chris Herd":"no","Jordan Bowery":"no","Jores Okore":"no","Gary Gardner":"no","Daniel Johnson":"no","Nicklas Helenius":"no","Jack Grealish":"no","Janoi Donacien":"no","Callum Robinson":"no","last_gp":"lose","2nd_gp":"lose","3rd_gp":"win","4th_gp":"lose","5th_gp":"lose","Home":"home","Results":"lose"});
What I found out was that both of the files had 'jsonCallback' as a function on the document being read. Each jsonCallback or function should be unique. What was happening before was a conflict and now it is unique.
Examle:
function handleData( responseData ) {
// do what you want with the data
console.log(responseData);
}
$.ajax({
url: "hi.php",
...
success: function ( data, status, XHR ) {
handleData(data);
}
});

Retrieving Records From Entity in Dynamics Crm using odata and jquery

I want to print the values retrieved from my entity in an alert message.I store the values in relatedproduct array i want to print these value.When it try to print them it gives undefined message.Plz help me
relatedProducts = [];
function onload() {
var oDataUri="https://yanceyworksllc.crm.dynamics.com/xrmservices/2011/OrganizationData.svc/ProductSet?$select=new_price,ProductId&$filter=new_TaxInformation/Value eq 1";
GetRecords(oDataUri);
var totalRecords = relatedProducts .length;
}
function GetRecords(url) {
jQuery.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
datatype: "json",
url: url,
async: false,
beforeSend: function (XMLHttpRequest) {
var x= XMLHttpRequest.setRequestHeader("Accept", "application/json");
},
success: function (data, textStatus, XmlHttpRequest) {
if (data && data.d != null && data.d.results != null) {
AddRecordsToArray(data.d.results);
FetchRecordsCallBack(data.d);
}
},
error: function (XmlHttpRequest, textStatus, errorThrown) {
// FetchRecordsCallBack(data.d);
alert("Error : has occured during retrieval of the records ");
}
});
}
function AddRecordsToArray(records) {
for (var i = 0; i < records.length; i++) {
relatedProducts .push(records[i]);
alert(relatedProducts[i].Value) ;
}
}
function FetchRecordsCallBack(records) {
if (records.__next != null) {
var url = records.__next;
GetRecords(url);
}
}
A very easy way to troubleshoot OData calls is to copy the URI into your browser and navigate to the page. If it does not bring you to a page with data, that means your uri is wrong. If it does, then you are handling the resulting data incorrectly (ie if the debugger hits the success block in GetRecords, then your AddRecordsToArray or FetchRecordsCallBack is broken).
Side note - I have never seen a space before a ".[Attribute Name]". Is that even a valid JavaScript syntax (as in your relatedProducts .push or relatedProducts .length)?

error looping through Ajax (JSON) response

I'm trying to loop through an array that gets returned from a php file.
If I run this:
$.ajax({
type: "POST",
url: "lib/search/search.standards_one.php",
async: "false",
dataType: "json",
data: {subjects: subjects, grades: grades},
success: function(response){
$("#standards_results").html("");
$.each(response[0], function(){
console.log(this['code'], this['standard_id']);
});
}
});
everything works perfectly.
but, I need to loop through this response using an array (grades) as parameters.
like this:
$.ajax({
type: "POST",
url: "lib/search/search.standards_one.php",
async: "false",
dataType: "json",
data: {subjects: subjects, grades: grades},
success: function(response){
$("#standards_results").html("");
var len = grades.length;
var param = "";
for(var x=0; x < len; x++){
param = grades[x];
$.each(response[param], function(){
console.log(this['code'], this['standard_id']);
});
}
}
});
however, when I run this I get the "Cannot read property 'length' of undefined" error.
I've tried a number of different solutions, but I still arrive at this result.
////
this is where the JSON object gets created:
private function retrieve_standards_one(){
$dbh = $this->connect();
$stmt = $dbh->prepare("SELECT code, standard_one_id
FROM standard_one
WHERE grade_id = :grade_id
ORDER BY standard_one_id");
$stnd = array();
for($x = 0; $x < (count($this->grades)); $x++){
$stmt->bindParam(':grade_id', $this->grades[$x], PDO::PARAM_STR);
$stmt->execute();
$stnd[] = $stmt->fetchAll(PDO::FETCH_ASSOC);
}
$json = json_encode($stnd);
return $json;
}
grades is out of scope of your success function, that is why it is undefined. The ajax is asynchronous, so the call is fired off, and your success function is only executed when the response is received (and it was successful).
A quick fix would be to put the vars you need in the global scope, or get them from response if they are in there.
var len = response.length;

Categories