简体   繁体   中英

Returning an itterable object to Ajax from php

How can I iterate through the object sent back from the php script below in my jquery/ajax call? I tried result[0] whiche gave me back c . That means that I'm being returned a string.What code should I write to be returned company1 etc. ?

DROP DATABASE IF EXISTS test;
CREATE DATABASE test;
USE test;

CREATE TABLE company(
name VARCHAR(255),
id INT PRIMARY KEY AUTO_INCREMENT
);

INSERT INTO company(name) VALUES( 'company1'); 
INSERT INTO company(name) VALUES( 'company2');
INSERT INTO company(name) VALUES( 'company2');
$.ajax({
    type: "GET",
    url: "manager-get-company.php",
    success: function (response) {
        //iterate through response here
        //console.log(response[0]; -> log Company1
        //console.log(response[1]; -> log Company2
    }
});
<?php

//manager-get-company.php

$hostname = 'localhost';
$username = 'root';
$password = '';
$database_name = 'test';
 $con = mysqli_connect($hostname,$username,$password,$database_name);

 //Check connection
if (mysqli_connect_errno()) {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  exit();
}

$sql= mysqli_query($con, 'SELECT name FROM company');
while($row = mysqli_fetch_array($sql)){
    echo $row['name'];
}

In ajax add dataType: "json",

$.ajax({
    type: "GET",
    dataType : "json",
    url: "manager-get-company.php",
    success: function (response) {
        //iterate through response here
        if(!response.error){
          console.log(response[0]);
        }
    }
});

In php

$result = [];
 //Check connection
if (mysqli_connect_errno()) {
  $result['error'] = "Failed to connect to MySQL: " . mysqli_connect_error();
}else{
  $sql= mysqli_query($con, 'SELECT name FROM company');
  while($row = mysqli_fetch_array($sql)){
    $result[] = $row['name'];
  }
}
echo json_encode($result);

Edited: use $result['error'] not result['error']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM