Do not display data output in ajax - javascript

I wrote the following code snippet for Ajax connections, but unfortunately the return value is not displayed in the output, but it does not give a special warning to understand the meaning. Please help.
js
$("#search").on('keyup', function(){var value = $(this).val();
$.ajax('feed.php',{
type: 'POST',
dataType: 'json',
data: {
keyword: value
},
success: function(data){
$("#pre").html(data);
}
});
});
feed.php
<?php
require_once('main.php');
$db = Db::getInstance();
$keyword = $_POST['keyword'];
$records = $db->query("SELECT * FROM dic_word WHERE word LIKE '%$keyword%'");
$out['html']= '';
foreach($records as $record){
$out['html'] .= $record['word'] . '<br>';
}
echo json_encode($out);
?>

js:
jQuery('#search').on('keyup', () => {
jQuery.ajax({
url: 'feed.php',
type: 'POST',
data: { keyword: jQuery(this).val() },
success: response => {
jQuery('#pre').html(response);
}
});
});
feed.php
<?php
require_once('main.php');
$database = Db::getInstance();
$keyword = $_POST['keyword'];
$records = $database->query("SELECT * FROM dic_word WHERE word LIKE '%$keyword%'");
$output = '';
foreach($records as $record){
$output .= $record['word'] . '<br />';
}
echo($output);
?>
PS: You don't need to use json output absolutly. But if there is coercion to using json output, the problem is 2 following items:
You don't set the output "Content-Type" to json: header('Content-Type: application/json');
You shouldn't pass the json object to html method in jQuery and should parsing it at first with JSON.parse(response) class, then with foreach, for or anything else process it

Related

How to use AJAX to call php file from javascript file

I want to call php file from javascript, and this php file will update id=1
like this way:
javascript:
if(lastTemp >= document.getElementById("TempSet").value){
var jsonData2 =$.ajax({
url: "setpp.php",
dataType: "json",
async: false
}).responseText;
var obj2 = JSON.parse(jsonData2);
console.log(obj2);
}
else {
}
php file:
<?php
$DATABASE_HOST = 'localhost';
$DATABASE_USER = 'use';
$DATABASE_PASS = 'pass';
$DATABASE_NAME = 'database';
// Try and connect using the info above.
$db = mysqli_connect($DATABASE_HOST, $DATABASE_USER, $DATABASE_PASS,
$DATABASE_NAME);
if (!$db){
die("Connection Failed: ". mysqli_connect_error());
}
$db_update = "UPDATE setpoint_control SET status='ON' WHERE id=1";
$result = mysqli_query($db, $db_update);
?>
<?php
$data = array();
if(mysqli_num_rows($result)>0){
while($row = mysqli_fetch_array($result)){
array_push($data, $row['status']);
}
}
echo json_encode($data);
?>
the code is executed and the status in database table is changed but I got error in console : SyntaxError: JSON.parse: unexpected character at line 4 column 2 of the JSON data
How can I solve this issue which I think I need to rewrite json_encode but I don't know how?
$.ajax({
type: 'post',
dataType: 'json',
cache: false,
url: 'setpp.php',
success: function (response) {
$.each(response, function(i, item) {
alert(item);
});
},
error: function () {
alert("error");
},
});
example php answer setpp.php
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_array($result)) {
array_push($data, $row['status']);
}
die(json_encode($data));
} else {
$answer = array(
'No Records'
);
die(json_encode($answer));
}
I think the problem is the value returned by setpp.php.
remember to die(), otherwise the php answer will not be correct

ajax get Excel form php

I am tryinh to get excel form php through ajax call when i load url of specific php gives me the output but when the same php is called via ajax with some ajax value nothing shows up.. am not sure what to do
ajax:
var fromdate= $("#fromdate").val();
var ToDate= $("#ToDate").val();
var Year= $('#Year').val();
var Category=$('#Category_1').val();
$.ajax({
url: "http://localhost/demo.php",
type: "post",
data: {
fromdate:fromdate,ToDate:ToDate,Year:Year,Category:Category
},
success: function(responsecon) {
window.open('http://YOUR_URL','_blank' );
}
});
PHP:
<?php
$conn=mysqli_connect('localhost','root','0000','xxxxx');
$filename = "users_export";
$fromdate = mysqli_real_escape_string($mysqli,trim($_POST["fromdate"]));
$ToDate = mysqli_real_escape_string($mysqli,trim($_POST["ToDate"]));
$Year = mysqli_real_escape_string($mysqli,trim($_POST["Year"]));
$Category = mysqli_real_escape_string($mysqli,trim($_POST["Category"]));
$sql = "Select * from xxxxxxxxxxx where category='$Category'";
$result = mysqli_query($conn,$sql) or die("Couldn't execute query:<br>" . mysqli_error(). "<br>" . mysqli_errno());
$file_ending = "xls";
header("Content-Type: application/xls");
header("Content-Disposition: attachment; filename=$filename.xls");
header("Pragma: no-cache");
header("Expires: 0");
$sep = "\t";
$names = mysqli_fetch_fields($result) ;
foreach($names as $name){
}
print ("dasd" . $sep."dasd1" . $sep);
print("\n");
while($row = mysqli_fetch_row($result)) {
$schema_insert = "";
for($j=0; $j<mysqli_num_fields($result);$j++) {
if(!isset($row[$j]))
$schema_insert .= "NULL".$sep;
elseif ($row[$j] != "")
$schema_insert .= "$row[$j]".$sep;
else
$schema_insert .= "".$sep;
}
$schema_insert = str_replace($sep."$", "", $schema_insert);
$schema_insert = preg_replace("/\r\n|\n\r|\n|\r/", " ", $schema_insert);
$schema_insert .= "\t";
print(trim($schema_insert));
print "\n";
}
?>
Basically there are two problems in your jQuery ajax request:
Sice you are specifying a content-type in your PHP script you have to tell jQuery what to expect from your ajax request using dataType: application/xls in your ajax object.
This is why you don't get any response, because it fails and you have not specified an error callback function to handle the error.
Moreover, in case of success you have to print somehow the content returned from the PHP script with something like $("#selector").html(responsecon);
Here is the updated ajax request:
$.ajax({
url: "http://localhost/demo.php",
type: "post",
dataType: "application/xls", // Tell what content-type to expect from server
data: {
fromdate:fromdate,
ToDate:ToDate,
Year:Year,
Category:Category
},
success: function(responsecon) {
window.open('http://YOUR_URL','_blank' );
$(#"some-container").html(responsecon); // Print the content
},
error: function() {
alert("error");
}
});

How to pass multiple variables from a php file to ajax and use them?

I have read many answers on stack overflow but I can't find an apt answer. I want to send multiple variables from php file to a javascript file. I want to use those variables later separately. So please explain with a simple example of how to get the variables from php file and how to use them separately later.
This is my js.
<script>
function here(card_numb) {
alert("pk!");
$.ajax({
url: 'details.php',
type: "GET",
dataType: 'json',
data: ({
card_number: card_numb
}),
success: function(data) {
console.log('card_number:'+data.card_number+'book_issued:'+data.book_isued);
}
});
}
I'm getting the alert 'pk!'. But $.ajax ain't working.
This is details.php
<?php
if(isset($_GET['card_number'])){
$card_number = $_GET['card_number'];
$query = "Select * from users where card_number = '".$card_number."'";
$query_run = mysqli_query($link,$query);
$row_numb =#mysqli_num_rows($query_run);
if($row_numb == 0){
echo "<div class='bdiv1'>No such number found!</div>";
} else{
$row=mysqli_fetch_assoc($query_run);
$book1 = $row['user_name'];
$arr = array('isued_book' => $book1,'card_number' => $card_number);
echo json_encode($arr);
exit();
}
}
?>
Thank you!
somthing.js - ur jspage
<script>
function here(card_numb) {
$.ajax({
url: 'details.php',
type: 'GET',
dataType: 'json',
data: {
card_number: card_numb
},
success: function(data) {
console.log('card_number:'+data.card_number+'book_issued:'+data.isued_book);
}
});
}
success: function(result){
console.log('variable1:'+result.var1+'variable2:'+result.var2+'variable3:'+result.var3);
} });
details.php
<?php
if(isset($_GET['card_number'])){
$card_number = $_GET['card_number'];
$query = "Select * from users where card_number = ".$card_number;
$query_run = mysqli_query($link,$query);
$row_numb =#mysqli_num_rows($query_run);
if(!$query_run){
echo "<div class='bdiv1'>No such number found!</div>";
} else {
$row=mysqli_fetch_assoc($query_run);
$book1 = $row['user_name'];
$arr = array('isued_book' => $book1,'card_number' => $card_number);
echo json_encode($arr);
exit();
}
if the currect value get in $row you can get the result in console

How can I return an array object to a jquery $.ajax call?

I am trying to return an array object to my Jquery ajax call, but it seems to return as a String with Array length =1
PHP code:
$results = mysqli_query($link, $sql);
if ($results->num_rows > 0) {
while ($row = $results->fetch_assoc()) {
$array = array($row['eventDate'], $row['time'] ,['data' => $row['time']]) ;
echo json_encode($array) ;
}
} else {
echo "0 results";
}
Response in Developer tools shows:
["12_03_2015","0:00:00",{"data":"0:00:00"}]["12_03_2015","0:00:00",{"data":"0:00:00"}]["12_03_2015","0:00:00",{"data":"0:00:00"}]
My Ajax Call:
function trend(data){
$.ajax({
url: "trendData.php",
cache: true,
type: "POST",
data: {arr:data},
success: function (data) {
originalData=[];
originalData.push(data)
trender(data)
}
});
}
In the Preview window for Network, it shows an Array:
I cannot get an array of , in this example, 3 objects and get the array.length of 3
Any help will be much appreciated.
You should collect all your data and return it as one json result and add a correct http-header (suggested by #Flosculus) so that the json format will be recognized:
$results = mysqli_query($link, $sql);
$data = array();
if ($results->num_rows > 0) {
while ($row = $results->fetch_assoc()) {
$data[] = array($row['eventDate'], $row['time'] ,['data' => $row['time']]) ;
}
header('Content-Type: application/json');
echo json_encode($data) ;
} else {
echo "0 results";
}
I think you have to use JSON.parse(), if you're using jquery so your js script will look like
$.ajax({
url: "trendData.php",
cache: true,
type: "POST",
data: {arr:data},
success: function (data) {
var data = JSON.parse(data);
//see length of array
console.log(data.length);
}
});

Textbox and AJAX data from mySQL

Hello I have a textbox and when I type something in it should update the page with the mySQL data via AJAX.
So Im trying to get live updated database results whenever you type something in the textbox. The goal is to get a textbox that is getting data from the mySQL database.
I have written the code so far, hopefully someone can advise me in this mather, thank you.
$select = 'SELECT *';
$from = ' FROM overboekingen';
$where2 = ' WHERE naam_klant LIKE % . $val . % ';
$opts = (isset($_POST['filterOpts']) ? $_POST['filterOpts'] : FALSE);
$val = (isset($_POST['txt']) ? $_POST['txt'] : FALSE);
if (is_array($opts) || $val) {
$where = ' WHERE FALSE';
if (in_array("naam_klant", $val)){
$where2.val;
}
}
else {
$where = false;
}
$sql = $select . $from . $where;
$statement = $pdo->prepare($sql);
$statement->execute();
$results = $statement->fetchAll(PDO::FETCH_ASSOC);
$json = json_encode($results);
echo($json);
?>
AJAX
function updateEmployeesText(val){
$.ajax({
type: "POST",
url: "submit.php",
dataType : 'json',
cache: false,
data: {text: val},
success: function(records){
$('#employees tbody').html(makeTable(records));
}
});
}
You must define the PHP $val variable before.
The correct sytax:
$where2 = " WHERE naam_klant LIKE %$val% ";

Categories