Mayuri Srijani Mayuri Srijani - 2 months ago 10
Ajax Question

Array to string conversion while ajax call from javascript

here i want to fill jqgrid with my data so i have made ajax call to retrive data from mysql database . now i want to sent data from php to javascript ajax call but it gives me error like Array to string conversion in line no 25

getGrid.php

<?php
session_start();
#$q = intval($_GET['q']);
// include('conn/conn.php');

$con = mysqli_connect('demoexample','root','','example');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}

mysqli_select_db($con,"example");
$sql="SELECT * FROM tbldummy ";
$result = mysqli_query($con,$sql) or die(mysqli_error($con));
$cat= mysqli_fetch_array($result);

$name = $cat['name'];
$sdate = $cat['sdate'];
$stock = $cat['stock'];
$ship = $cat['ship'];
echo $name;
echo $sdate;
echo $stock;
echo $ship;

//error -> echo $cat;
echo jason_encode($cat);
mysqli_close($con);
?>


jqgrid.html

<script type="text/javascript">

$.ajax({
url: 'getGridData.php',
type: 'POST',
// data: ({name:name,sdate:sdate,stock:stock,ship:ship}),
dataType: 'json',
cache: 'false',
success: function(data){
alert(JSON.stringify(data));
json = JSON.parse(data);
console.log(data);
console.log(json);
}
});
</script>

Answer

As I can see, you must use json_encode instead of jason_encode :)

And in this part of code

echo $name;
echo $sdate;
echo $stock;
echo $ship;

echo jason_encode($cat);

Use only

echo json_encode($cat);

After this, you can get fields of JSON in jQuery like

 cat = JSON.parse(data);
 console.log(cat.name);
Comments