Trying to get the maximum value of an array element using JavaScript tools:

On the server, the array is formed as follows:

$usr = mysql_query($query); while ($row = mysql_fetch_array($usr)) { $products_code_arr[] = $row[0]; } echo $products_code_arr; 

print_r indicates that we have an array of the form

 Array ( [0] => 1237 [1] => 234 ) 

I take it as ajax and try to find the maximum value:

 var url = 'get_data.php'; $.post( url, function(data) { var arr = data; function getMax(arr){ return Math.max.apply(Math,arr); } var max = getMax(arr); ); 

The method is described here , but it does not work for me, I get the error: Uncaught TypeError: CreateListFromArrayLike is called on non-object

Please suggest where the error is and how to fix it.

  • In the $.post handler, add the line console.log(data) and see what is displayed in the console. - Dmitry Shevchenko
  • The $.post() method should have an object with values ​​of the form { a: 'b', c: 'd' } as the second parameter, you have the same function (it should be the third one). - mix
  • PS You pass php array to js , what do you hope for? - mix
  • @ DmitryShevchenko, "Array" is displayed - 118_64
  • one
    @ 118_64 If "Array" is displayed, then something is wrong. The console should display the contents of the array. Perhaps in PHP you somehow incorrectly serialize an array. Show the code that you send the array from PHP in the response of the ajax request. - Dmitry Shevchenko

1 answer 1

Hey. An array is formed on your server, but you do not convert it. If you add echo json_encode($products_code_arr); , the array will be of the form [12,3,4,15,2] and then everything will work. Otherwise, you output the string "Array" on the server

As it was before the conversion:

 Array ( [0] => 15 [1] => 2 [2] => 155 ) 

As it became:

 [15,2,155] 

Also correct ajax request:

 ... function(data) { // Парсим строку json и преобразуем в массив чисел var arr = JSON.parse(data).map(function (el) { return parseInt(el); }); ... 
  • Thanks for the answer, corrected and received an array. But the error remains: Uncaught TypeError: CreateListFromArrayLike called on non-object - 118_64
  • I checked it myself, everything works, output the incoming array to the console, write, see. - Vasily Barbashev
  • in the console - ["1237", "234"] - 118_64
  • everything is simple, you now have each element become a string. The maximum can be found only on the number. Before casting an array into a method, convert it like this: data.map(function (el) { return parseInt(el);}) - Vasily Barbashev
  • there is some kind of problem either with an array that I don’t see, or with syntax. I tried to feed the array to the method you specified and could not: var new_arr = data.map (function (el) {return parseInt (el);}); - Uncaught TypeError: data.map is not a function. Even the elementary action var new_arr = data.map (Math.sqrt); gives the same error - 118_64