set ajax response to a variable to make it an object

here is the returned data

name: "Doe, John ", salary: "1000"

here is the code

$.ajax({
   url: 'ajax.php',
   method: 'POST',
   data: {id: name.val()},
   success: function(data){
      var payObject = {data};
      alert(payObject["name"]);
   }
}};

it always return undefined, how can i fix this?

here is the employee table in the database

name       salary
Doe, John  1000

here is the ajax.php

<?php
    include 'db.php';
    $sql = $db->query("SELECT * FROM employee");
    $res = mysqli_fetch_assoc($sql);
    echo 'name:"'.$res['name'].'", salary: "'.$res['salary'].'"';
?>

You returning just a string that cannot be used by JavaScript itself as an object. To fix this you can convert your database data to JSON and simply return JSON. In JavaScript, you can easily convert JSON string to JavaScript object and use it like any other JavaScript object.

To convert PHP array to JSON string use PHP function json_encode so your PHP code will look like this

<?php
    include 'db.php';
    $sql = $db->query("SELECT * FROM employee");
    $res = mysqli_fetch_assoc($sql);
    echo json_encode($res); // convert PHP associative array to JSON string
?>

Now you simply convert JSON string to JavaScript object with JSON.parse() or use advantage of jQuery's dataType:'json' parameter

$.ajax({
   url: 'ajax.php',
   method: 'POST',
   data: {id: name.val()},
   dataType: 'json', // convert JSON string to JavaScript object
   success: function(data){
      var payObject = data;
      alert(payObject["name"]);
   }
}};

0 Comment

NO COMMENTS

LEAVE A REPLY

Captcha image