The Root Cause: String vs. Array in JavaScript
The core issue isn't how you send data from PHP; it's what JavaScript expects to receive. In your current setup, $.ajax fetches a string of text from select.php. When that text is parsed by the browser, the structure matters immensely.
Your PHP output generates a valid JSON array:
[{"0":1,"1":"name1","id":1,"name":"name1"},{"0":2,"1":"name2","id":2,"name":"name2"}]
However, your jQuery success callback treats this string as if it were already an array of objects. You are attempting to iterate directly over the raw response text: foreach (results as obj). In JavaScript, iterating over a string iterates over its individual characters (e.g., [ , {, 0), not the JSON objects inside it. Consequently, your loop never finds the data you expect, and JSON.parse(obj) fails because you are trying to parse single characters like "[" or "{" instead of the full object strings.
To fix this, you must transform the incoming string into a JavaScript array before iterating. The standard approach is using the global JSON.parse() function immediately inside your success handler.
Correcting the Client-Side Logic
Once the response text is parsed, results becomes a genuine JavaScript array. You can then use a standard forEach, for...of, or .map loop to process each item. Here is how you should structure the success callback:
$.ajax({
type: "POST",
url: "select.php",
data: { columns: "*", table: "tbUsers", conditions: "" },
dataType: "json", // Explicitly telling jQuery to parse response
success: function(results) {
// At this point, 'results' is already a parsed JSON object (Array)
// because dataType: 'json' or manual JSON.parse() was used.
results.forEach(function(item) {
console.log(item.id + " " + item.name);
// Or update the DOM dynamically
$("#page").append(item.id + " " + item.name).append("<br>");
});
}
});
Notice the dataType: "json" property in the AJAX call. This is a crucial configuration option. It instructs jQuery to automatically run JSON.parse() on the response text before passing it to your success function. If you omit this, you must manually parse the string yourself using JSON.parse(results).
Addressing PHP Array Index Issues
Your sample PHP output reveals a specific quirk: [{"0":1, "1":"name1", ...}]. The keys "0" and "1" suggest your PHP array is associative rather than strictly indexed numerically. While valid JSON, this can lead to confusing debug output if you aren't expecting it.
In PHP, when you convert an array using json_encode(), the resulting keys depend on how the array was constructed. If you used foreach ($rows as $row) inside a loop where $row is an associative array (which happens often with MySQLi or PDO fetches), the resulting JSON might retain internal index artifacts if not handled carefully, or it might look like your example if specific logic added those keys.
Ideally, your PHP should return clean data:
// PHP Example
$rows = ['id' => 1, 'name' => 'name1']; // Associative array
$json = json_encode($rows);
// Result: {"id":1,"name":"name1"} (No "0" or "1" keys unless explicitly added)
Ensure your PHP code returns a standard indexed array of associative arrays. If you are fetching rows from MySQL, use fetch() to get an associative array by default, then wrap them in another array before encoding:
$rows = [];
while ($row = $result->fetch()) {
$rows[] = $row;
}
header('Content-Type: application/json');
echo json_encode($rows);
Modern Alternatives with Laravel
If you are working within a Laravel ecosystem, handling raw AJAX calls can become cumbersome due to session management and CSRF protection. In such scenarios, leveraging the laravelcompany ecosystem resources or standard Laravel controllers is often more robust.
You can define a route that handles the request:
// routes/web.php or api.php
Route::post('/users', function (Request $request) {
$rows = DB::table('tbUsers')
->where($request->get('conditions'))
->get()
->toArray(); // Returns a standard PHP array
return response()->json($rows);
});
This approach automatically sets the Content-Type header to application/json, ensuring your client receives the correct MIME type. It also handles CSRF tokens if you are using Laravel's frontend, which is essential for security in production environments. The controller returns a JSON response directly, eliminating the need for manual header() calls and ensuring the data structure is consistent with what your JavaScript expects: a parsed array ready for iteration.