I am making a call to php file, which is picking up data of 'name' and 'email' row-by-row and need to send it as a ajax response to my index.html file. I can fetch the row data but unable to know, how to send back the data as a reply to ajax request in json form.
PHP Code:
if ($result->num_rows > 0){
// output data of each row
while($row = $result->fetch_assoc()) {
echo "jname".$row["name"]."jemail".$row["email"];
}
}
else{
echo "0 results";
}
Instead of just echoing out the data as you are, store it in an array and use json_encode to return it as a json string.
$return = array();
if ($result->num_rows > 0){
$return['result'] = $result->num_rows.' results';
$return['rows'] = array();
// output data of each row
while($row = $result->fetch_assoc()) {
$return['rows'][] = array(
'jname' => $row['name'],
'jemail' => $row['email']
);
}
}
else{
$return['result'] = "0 results";
}
echo json_encode($return);
Put your result in array, and print it via json_encode()
$response = array();
if ($result->num_rows > 0){
// output data of each row
while($row = $result->fetch_assoc()) {
$response[] = array(
'jname' => $row['name'],
'jemail' => $row['email']
);
}
}
echo json_encode($response);
exit();
Related
This is my PHP code
<?php
require_once 'd:\xampp\htdocs\bpr\pdo_db.php';
$sql = "Select ID,FULL_NAMe,AGE from TRIAL";
$csv = get_csv_string($dbh, $sql);
echo "<script> var_csv='" . $csv . "' </script>";
function get_csv_string($dbh, $sql)
{
try
{
$result = $dbh->query($sql);
//return only the first row (we only need field names)
$row = $result->fetch(PDO::FETCH_ASSOC);
if ($row == null) {
return "No Data";
}
$f = fopen('php://memory', 'r+');
foreach ($row as $field => $value) {
if (fputcsv($f, $field) === false) {
return false;
}
}
//second query gets the data
$data = $dbh->query($sql);
$data->setFetchMode(PDO::FETCH_ASSOC);
foreach ($data as $row) {
if (fputcsv($f, $row) === false) {
return false;
}
} // end record loop
rewind($f);
$csv = stream_get_contents($f);
return rtrim($csv);
} catch (PDOExepction $e) {
return $e->getMessage();
}
return $csv;
}
I am getting following error!
Instead of fputcsv(), I made my own code. But issue if found when I save the CSV to a javascript variable. Is there any other way to convert the data to CSV and pass it on to javascript?
I will convert this csv to JSON at Client side using javascript
You're trying to output a header row to CSV with the field names.
This code fails because you're looping through the $row array and attempting to write one field header at a time.
foreach ($row as $field => $value) {
if (fputcsv($f, $field) === false) {
return false;
}
}
What you want is an array with the field names in it. You can use array_keys() for that, so your code becomes
if (fputcsv($f, array_keys($row)) === false) return false;
No loop required.
when one record then show data when multiple record come then not show data other site.
ajaxx.php
<?php
include 'database.php';
session_start();
$post = $_POST;
$search = $post['search'];
$searchType = $post['searchType'];
if ($searchType == 'all')
{$sql = "SELECT DISTINCT title FROM hadees WHERE title LIKE '$search%' AND (type='Bukhari' OR type='Muslim') ";}
else
{$sql = "SELECT DISTINCT title FROM hadees WHERE title LIKE '$search%' AND type='$searchType' ";}
$result = mysqli_query($db,$sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$row['title'];
echo json_encode($row);
}
} else
{ echo "Not Found Result" ; }
?>
when data record is one then append the data successfully when multiple record come then not show data and append not work
javascript code
function searchh()
{
var type = $("input[name='type']:checked").val();
var searchhh = $( ".myButton option:selected" ).text();
debugger;
$.ajax({
url: 'ajaxx.php',
type: "POST",
data: {'searchType':type, 'search':searchhh},
success: function (data) {
var duce = jQuery.parseJSON(data);
alert(duce.title);
}
});
}
I think your issue is in the while loop. You don't want to encode each row one-by-one, but as a whole like this.
$myResults = [];
while($row = $result->fetch_assoc()) {
$row['title'];
$myResults[] = $row;
}
echo json_encode($myResults);
You are producing invalid JSON by using echo json_encode($row); within a loop.
Try to craft an array of rows, and then display it.
if($result->num_rows > 0)
{
$output = array();
while($row = $result->fetch_assoc())
{
output[] = $row;
}
if($searchType == 'all')
{
echo json_encode($output);
}
else
{
echo json_encode(current($output)); // print just one
}
}
I'm a beginner in using PHP and Javascript, and I don't have any idea on how to store the data that I've gathered from MySQL which I placed in a multidimensional array in PHP to a 2D array in Javascript. Here's my working code in PHP:
<?php
function connecToDatabase(){
$host = "localhost";
$username = "root";
$password = "p#ssword";
$database = "flood_reports";
mysql_connect("$host", "$username", "$password") or die(mysql_error());
mysql_select_db("$database") or die(mysql_error());
}
function retrieveData(){
connecToDatabase();
$data = mysql_query('SELECT * FROM entries') or die(mysql_error());
$entries = array();
$index = 0;
while($info = mysql_fetch_array( $data ))
{
$entries[$index] = array('entry_id' => $info['entry_id'],
'location' => $info['location'],
'image_dir' => $info['image_dir'],
'longitude' => $info['longitude'],
'latitude' => $info['latitude'],
'level' => $info['level']);
$index++;
}
$json = json_encode($entries);
echo $json;
mysql_close();
}
retrieveData();
?>
on the end of your script add the following
<script type="text/javascript">
var jsvar = <?php echo $phpvar;?>
</script>
Replace
echo $json;
with
echo 'var fromPhp = ' . $json . ';';
You just need to put the data into a variable. This will make it available as fromPhp on the browser side.
This file is called by ajax request. And result coming here I want to place into two different in calling function.
<?php
//Some processing gives $text
$s=nl2br($text);
$data['x'] = $p;
$data['y'] = $q;
//Start from here
echo "<b>Positive count : $x with $p % </b>"; echo "</br>";
echo "<b>Negative count : $y with $q % </b>"; echo "</br>";
echo "</br>";
echo "Page content : ";
echo "</br>";
echo "</br>";
echo $s;
//End. This content should be place in <div1>. Want to send this as a json string
and
//Start from here
echo "First 5 post";
$result = mysqli_query($con,"select post from facebook_posts where p_id > (select MAX(p_id) - 5 from facebook_posts)");
while ($row = $result->fetch_array(MYSQLI_ASSOC))
{
echo $row['post'];
echo '<br/>';
}
//End. This content should be placed in <div2> Want to send this as a json string
If there is single variable then we can easily do it using :
$resultArray = array("resultOne" => $result1,"resultTwo" => $result2);
echo json_encode($resultArray);
at receiving end:
document.getElementById("myFirstDiv").innerHTML=xmlhttp.responseText.resultOne;
document.getElementById("mySecondDiv").innerHTML=xmlhttp.responseText.resultTwo;
But how above complex result could be place into to json variable?
You could use output buffering in PHP:
ob_start();
// Generate content for div 1...
$div1 = ob_get_clean();
ob_start();
// Generate content for div 2...
$div2 = ob_get_clean();
$result = array("div1" => $div1, "div2" => $div2);
echo json_encode($result);
filePHP.php
$query = $kon->prepare("SELECT * FROM t_kategori");
$query->execute();
while($row = $query->fetch(PDO::FETCH_ASSOC))
{
$json = array('id' => $row['id_kategori'], 'nama' => $row['nama_kategori']);
echo json_encode($json);
}
and index.php
$.post('filePHP.php', function(data){
console.log(data);
},'json');
but this not working, what would solve this problem?
Try this in PHP
$query = $kon->prepare("SELECT id_kategori,nama_kategori FROM t_kategori");
$query->execute();
$json=array();
while($row = $query->fetch(PDO::FETCH_ASSOC))
{
$arr=array('id'=>$row['id_kategori'],'nama'=>$row['nama_kategori']);
array_push($json,$arr);
}
echo json_encode($json);
Read array-push
try something like this , your code will echo json in wrong format whereas below code will give you json array.
$query = $kon->prepare("SELECT * FROM t_kategori");
$query->execute();
$json_arr =array();
while($row = $query->fetch(PDO::FETCH_ASSOC))
{
$temp_arr = array();
$temp_arr['id'] => $row['id_kategori'];
$temp_arr['nama'] => $row['nama_kategori'];
array_push($json_arr,$temp_arr);
}
echo json_encode($json_arr);