ajax not work and not show php data - javascript

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
}
}

Related

What is the best way to enter data obtained from a database in PHP into seperate html <div>'s?

I'm currently working on a Facebook like chat, with 3 different chat boxes that should work simultaneously. I can send and read messages from my database, but I'm having difficulty displaying this information in the right place. In chat.php I have this snippet of code:
$.ajax({
url: "fetch_user_chat_history.php",
method: "POST",
data: jQuery.param({receiver_id:receiver_id, num:num}),
success: function(data) {
$('$chat_history_'+receiver_id).html(data);
}
});
Now I am able to read the data from my database correctly in fetch_user_chat_history.php, but when I iterate over my messages I'm unable to output them correctly back to chat.php. Here is my fetch_user_chat_history.php:
<?php
include "opendb.php";
session_start();
$output1 = '';
$output2 = '';
$increment = 0;
$sender = $_SESSION['user_id'];
$receiver_id = $_POST['receiver_id'];
$chatboxnum = $_POST['num'];
$query = 'SELECT content, timestamp_chat, sender_id FROM messages WHERE (sender_id = '.$sender.' AND receiver_id = '.$receiver_id.' OR (sender_id = '.$receiver_id.' AND receiver_id = '.$sender.'))';
$statement = $db->prepare($query);
$statement->execute();
$result = $statement->fetchAll(PDO::FETCH_ASSOC);
switch ($chatboxnum) {
case 1:
foreach ($result as $row) {
if ($row['sender_id']==$sender) {
echo '<script>var para = document.createElement("div");';
echo 'para.innerHTML = '.$row["content"].';';
echo 'var att = document.createAttribute("class");';
echo 'att.value = "msg-send";';
echo 'para.setAttributeNode(att);';
echo 'document.getElementById("sendbox-1").appendChild(para);';
echo 'document.body.appendChild(para); </script>';
}
else {
echo "var element = document.getElementById('receivebox-1'); element.classList.add('msg-receive');";
}
$increment += 1;
}
break;
}
?>
None of my echo statements add anything to chat.php. I'm sure there's a very easy fix as I have done this before but I can't seem to get it working. I apologise for the long post.

Call PHP Function using AJAX [duplicate]

This question already has answers here:
Make jQuery AJAX Call to Specific PHP Functions
(3 answers)
Closed 6 years ago.
I've read all the topics about my question but cannot solve my problem. I want to get php function result using jQuery AJAX.
function fetch_select(){
val_name = $('#name').val();
$.ajax({
type: 'POST',
url: 'include/get_db.inc.php',
data: {
name: val_name,
},
success: function (response) {
document.getElementById('higtchart_medie_gen').innerHTML=response;
columnChart( JSON.parse(response));
}
});
}
function columnChart(data_v){
if(data_v.length >0){
$(function () {
$('#higtchart_medie_gen').highcharts({
chart: {
type: 'column'
},
......
#name is id for select tag.
My code for get_db.inc.php is:
<?php
function test_name () {
$ret = [];
if(isset($_POST['name'])){
$name = $_POST['name'];
$sql = "SELECT
......
WHERE ID = $name ";
$result = $conn->query($sql);
if($result->num_rows > 0){
while($row = $result->fetch_assoc()) {
$ret [] = [$row['NAME'] . ' ' . $row['LASTN'], floatval($row['AVGG'])];
}
}
}
if(count($ret) >1) echo json_encode($ret);
else echo 'Not working';
}
?>
How can I call test_name function from Ajax code?
Thank you very much!
You do almost correct but only one mistake is you forget to invoke the function. What you do is just send the data to this file.
So, to fixed this. Just add test_name() to your get_db.inc.php
<?php
function test_name () {
$ret = [];
if(isset($_POST['name'])){
$name = $_POST['name'];
$sql = "SELECT
......
WHERE ID = $name ";
$result = $conn->query($sql);
if($result->num_rows > 0){
while($row = $result->fetch_assoc()) {
$ret [] = [$row['NAME'] . ' ' . $row['LASTN'],floatval($row['AVGG'])];
}
}
}
if(count($ret) >1) echo json_encode($ret);
else echo 'Not working';
}
test_name()
?>
Also it will be better to check isset outside the function.
function test_name ($name) {
$ret = [];
$sql = "SELECT
......
WHERE ID = $name ";
$result = $conn->query($sql);
if($result->num_rows > 0){
while($row = $result->fetch_assoc()) {
$ret [] = [$row['NAME'] . ' ' . $row['LASTN'],floatval($row['AVGG'])];
}
}
if(count($ret) >1) echo json_encode($ret);
else echo 'Not working';
}
if(isset($_POST['name'])){
test_name($_POST['name'])
}
This will make your function to be pure. It will easier to debug later and it will not invoke if you don't have $_POST['name'].

HTML, AJAX, PHP - Send a html input array through ajax to a php page

I have seen many similar questions however I have tried them and none of them worked.
I have a form in which the user can enter an unspecified amount of inputs. These inputs are selects and the user can add them when required. I am using ajax to add in more selects as required.
I am then trying to post this array to a php page using ajax, eventually to insert into a database
This is my html:
<strong>Allergens:</strong><br><div id="allergens">
<select name="allId[]" id="allId">
<option value="">No allergens</option>
<?php
$sql = ("SELECT AllergenId, LookupValue From ALLERGENS");
$result = $conn->query($sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
echo "<option value=".$row["AllergenId"].">".$row["LookupValue"]."</option>";
}
}
?>
</select><button type="button" class="addRemove" onClick="addAllergen()">+</button><br></div><br>
Here is what I insert to add in more selects:
<div id="newSelect">
<select name="allId[]" id="allId">
<?php
$sql = ("SELECT AllergenId, LookupValue From ALLERGENS");
$result = $conn->query($sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
echo "<option value=".$row["AllergenId"].">".$row["LookupValue"]."</option>";
}
}
?>
</select><button type="button" class="addRemove" onClick="removeNew()">-</button><br></div>
This is my ajax:
function addIng() {
if (confirm("Are you sure you want to submit?")) {
var toPost ={};
$form = $("#ingForm");
toPost.allId = [];
var allId = document.querySelectorAll("#ingForm input[name='allId[]']");
for (i = 0; i < allId.length; i++) {
toPost.allId.push(allId[i].value);
}
$.ajax({
type: "POST",
url: "../PHP/addIngredient.php",
data: toPost,
success: function(data) {
$("#addIngResult").html(data);
}
});
}
}
And then how can I set up my php so I can just call $_POST["allId"] and put it into an array?
On addIngredient.php page you will get the post value in $_POST['toPost'] variable as this is what writing in ajax

How to use php with sql query in javascript

var phpCode = '<?php
$sql = "SELECT Name,Surname,id_room FROM timatable.professors WHERE p.id_professor = '".mysqli_real_escape_string($_POST['hiddenProfId'])."'";
$resutl = mysqli_query($db,$sql);
if ($result == 1 ) {
$row = mysqli_fetch_array($result);
$professorName = $row['Name'];
$professorSurname = $row['Surname'];
} else echo "Error";
?>';
alert(phpCode);
this is my code. how to make it work ????
Try this.
First initialize, variables to null.
$professorName = "";
$professorSurname = "";
This is because, if php code enters else part, you will not get any error in javascript part.
<?php
$sql = "SELECT Name,Surname,id_room FROM timatable.professors WHERE p.id_professor = '".mysqli_real_escape_string($_POST['hiddenProfId'])."'";
$resutl = mysqli_query($db,$sql);
if ($result == 1 ) {
$row = mysqli_fetch_array($result);
$professorName = $row['Name'];
$professorSurname = $row['Surname'];
} else echo "Error";
?>
<script>
var professorName = "<?php echo $professorName ?>";
var professorSurname = "<?php echo $professorSurname ?>";
alert(professorName);
alert(professorSurname);
</script>
PHP is a server-side language. So it is processed on a server. Therefore you cannot have a PHP code in javascript.
If you want to have javascript managed some editing in database, you can use AJAX to do it without reloading the page.

Ajax call to retrieve data of database by php of all customers

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();

Categories

Resources