I'm trying to send an array of data from PHP to ajax. I'm using echo json_encode to do it. When I do that, I try 'console.log(data)' to see the response data but it not show anything. How can I get it to display the data? I really don't know what I'm missing here. I have this script:
var scard = $('#cardid').val();
$.ajax({
type: 'GET',
url: 'cardapi.php?scard=' + scard,
success: function (data) {
console.log($.parseJSON(data));
console.log(data);
}
});
And here is my code for cardapi.php
if(isset($_GET["scard"])){
$scard = $_GET["scard"];
$data = array();
$sql = "SELECT * FROM training_record WHERE cardref_no='$scard'";
$q = sqlsrv_query($conn, $sql);
while($rw = sqlsrv_fetch_array($q, SQLSRV_FETCH_ASSOC)){
array_push($data,[
"employee_no" => $rw["employee_no"],
"dept_id" => $rw["dept_id"],
"name_th" => $rw["name_th"],
"surname_th" => $rw["surname_th"],
"signed_status" => 1,
]);
}
echo json_encode($data);
}
So I try to follow this echo json_encode() not working via ajax call
It still not show anything. Please tell me why?
Thank you.
You may try the following:
Always check the result from the sqlsrv_query() execution.
Always try to use parameterized statements. Function sqlsrv_query() does both statement preparation and statement execution, and can be used to execute parameterized queries.
Check the result from the json_encode() call.
Fix the typing errors ("signed_status" => 1, should be "signed_status" => 1 for example).
Sample script, based on your code:
<?php
if (isset($_GET["scard"])) {
$scard = $_GET["scard"];
$data = array();
$sql = "SELECT * FROM training_record WHERE cardref_no = ?";
$params = array($scard);
$q = sqlsrv_query($conn, $sql, $params);
if ($q === false) {
echo "Error (sqlsrv_query): ".print_r(sqlsrv_errors(), true);
exit;
}
while ($rw = sqlsrv_fetch_array($q, SQLSRV_FETCH_ASSOC)) {
$data[] = array(
"employee_no" => $rw["employee_no"],
"dept_id" => $rw["dept_id"],
"name_th" => $rw["name_th"],
"surname_th" => $rw["surname_th"],
"signed_status" => 1
);
}
$json = json_encode($data);
if ($json === false) {
echo json_last_error_msg();
exit;
}
echo $json;
}
?>
Related
I'm trying to pass an array with ajax with a post to a php page.
My code js is :
function funzione5(){
var aux2=document.getElementById('f1').value;
$.ajax({type: "POST",
url: "AddMeeting.php",
data: {
'aux':aux,
'aux2':aux2,
'k':k
},
success: {function(data){
console.log(data);
}
},
error: {function(){alert("Error");}}
});
$('#modalMeeting').modal('hide');
}
and the php page is :
<?php
if(strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest')
{
header("Location: Meetings.php");
exit();
}
if(!isset($_COOKIE["id"]))
{
$json_data = array(
'draw' => 0,
'recordsTotal' => 0,
'recordsFiltered' => 0,
'data' => [],
'error' => 'Laravel Error Handler',
);
$json = json_encode($json_data);
echo $json;
exit();
}
include("DB.php"); //dati configurazione del database
$cont = mysqli_real_escape_string($connessione, $_POST["k"]);
$title = mysqli_real_escape_string($connessione,
$_POST["aux[0]"]);
$date = mysqli_real_escape_string($connessione,
$_POST["aux[1]"]);
$place = mysqli_real_escape_string($connessione, $_POST["aux[2]"]);
$topic = mysqli_real_escape_string($connessione, $_POST["aux[3]"]);
$lat = mysqli_real_escape_string($connessione, $_POST["aux[4]"]);
$lng = mysqli_real_escape_string($connessione, $_POST["aux[5]"]);
for($i=6;$i<$cont;$i++)
{ $part_id+$i = mysqli_real_escape_string($connessione,
$_POST["aux[".$i."]"]); }
$card_id = mysqli_real_escape_string($connessione, $_POST["aux2"]);
$id2=$_COOKIE['id'];
echo mysqli_error($connessione);
$sql1=mysqli_query($connessione,"insert into meeting
(card_id,user_id,title,place,date,topic,lat,lng) values
('$card_id','$id2','$title','$place','$date','$topic','$lat','$lng');");
echo mysqli_error($connessione);
$json_data = array(
"result" => 1
);
$json = json_encode($json_data);
echo $json;
?>
Is it correct to pass an array in this way? I checked that in the function "funzione5" the values of the array are set correctly. What could be the problem? Can you explain me how to pass the array? I searched on the web but i didn't find anything.
Currently your params are being passed as "aux" and "aux2", not "aux[0]" as you have it set in PHP. If it's a simple array I suggest simply using a delimiter, so separate the inputs with whatever symbol and then explode it, it seems like that indeed could be done in your example.
I'm setting up a chatbot (dialogflow) with a PHP webhook
What I want to do is to take the user input to query a MySQL table and pass the result back to the dialogflow API
So far I succeeded with passing a text string back to the API, but I don't understand how to query the database and pass the result back to the dialogflow API
I'll appreciate your help with this
I've used the API format from the dialogflow docs here
This is what I have
<?php
$method = $_SERVER['REQUEST_METHOD'];
if($method == 'POST') {
$requestBody = file_get_contents('php://input');
$json = json_decode($requestBody);
$text = $json->result->parameters->cities;
$conn = mysqli_connect("xxx", "xxx", "xxx", "xxx");
$sql = "SELECT * FROM exampletable LIKE '%".$_POST["cities"]."%'";
$result = mysqli_query($conn, $sql);
$emparray = array();
while($row =mysqli_fetch_assoc($result)) {
$emparray[] = $row;
}
$speech = $emparray;
$response->speech = $speech;
$response->displayText = $speech;
$response->source = "webhook";
echo json_encode(array($response,$emparray));
else
{
echo "Method not allowed";
}
?>
Thankyou
whenever the webhook gets triggered you need to listen to actions from JSON responses,
from the action made the switch case of actions
index.php
<?php
require 'get_enews.php';
function processMessage($input) {
$action = $input["result"]["action"];
switch($action){
case 'getNews':
$param = $input["result"]["parameters"]["number"];
getNews($param);
break;
default :
sendMessage(array(
"source" => "RMC",
"speech" => "I am not able to understand. what do you want ?",
"displayText" => "I am not able to understand. what do you want ?",
"contextOut" => array()
));
}
}
function sendMessage($parameters) {
header('Content-Type: application/json');
$data = str_replace('\/','/',json_encode($parameters));
echo $data;
}
$input = json_decode(file_get_contents('php://input'), true);
if (isset($input["result"]["action"])) {
processMessage($input);
}
?>
get_enews.php
<?php
function getNews($param){
require 'config.php';
$getNews="";
$Query="SELECT link FROM public.news WHERE year='$param'";
$Result=pg_query($con,$Query);
if(isset($Result) && !empty($Result) && pg_num_rows($Result) > 0){
$row=pg_fetch_assoc($Result);
$getNews= "Here is details that you require - Link: " . $row["link"];
$arr=array(
"source" => "RMC",
"speech" => $getNews,
"displayText" => $getNews,
);
sendMessage($arr);
}else{
$arr=array(
"source" => "RMC",
"speech" => "No year matched in database.",
"displayText" => "No year matched in database.",
);
sendMessage($arr);
}
}
?>
So when the action gets caught it will get executed and goes in the getNews($param); function here I am getting year as a response from the user in my case and I am executing the query in the database and giving back a response from the database.
<?php
include_once '../includes/db_connect.php';
fetch_evt_values($conn, 7475, 2, 16);
function fetch_evt_values($conn, $p_frm_id, $p_evt_id, $p_usr_id) {
$p_rec_id = 0;
$l_rslt_msg = '';
$l_result = array(
'data' => array(),
'msg' => '0000'
);
$sql = 'BEGIN PHPEVT.EV_MOD.FETCH_EVT_VALUES(';
//$sql .= ':c_load_id,';
$sql .= ':c_frm_id,';
$sql .= ':c_evt_id,';
$sql .= ':c_rec_id,';
$sql .= ':c_usr_id,';
$sql .= ':c_rslt';
$sql .= '); END;';
if ($stmt = oci_parse($conn,$sql)) {
$l_results = oci_new_cursor($conn);
//oci_bind_by_name($stmt,':c_load_id',$p_load_id);
oci_bind_by_name($stmt,':c_frm_id',$p_frm_id);
oci_bind_by_name($stmt,':c_evt_id',$p_evt_id);
oci_bind_by_name($stmt,':c_rec_id',$p_rec_id);
oci_bind_by_name($stmt,':c_usr_id',$p_usr_id);
oci_bind_by_name($stmt,':c_rslt',$l_results,-1,OCI_B_CURSOR);
if(oci_execute($stmt)){ //Execute the prepared query.
oci_execute($l_results);
while($r = oci_fetch_array($l_results,OCI_ASSOC)) {
$l_evt_values = explode('|', $r['EVENT_VALUES']);
foreach($l_evt_values as $l_evt_value) {
list($l_ID, $l_value) = explode('#', $l_evt_value);
$l_values[] = array('ID' => $l_ID, 'VALUE' => $l_value);
}
$l_result['data'][] = array(
'LOAD_ID' => $r['LOAD_ID'],
'REC_ID' => $r['REC_ID'],
'TRAIT' => $l_values,
'G_MSG' => $r['G_MSG']
);
$l_rslt_msg = $r['G_MSG'];
}
} else {
//echo 'cannot get user';
$l_rslt_msg = '0005'; //PHP_MEMBER.FETCH_USER return error code
}
} else {
//echo 'connect fail';
$l_rslt_msg = '0006'; //Could not connect to database.
}
oci_close($conn);
echo json_encode($l_result);
}
?>
So on a webpage, when a user requests an event, a database call is made using this code to retrieve some values in the format :
"62#20000|65#15710|66#6|67#6|68#0|69#0|".
The PHP then breaks it apart by |, splits the ID#Value, puts everything into an array, then returns it as a JSON which is then parsed into a table. The latter works perfectly fine. But when this tries to fetch more than about 600 records or so, I get a 500 Internal Server Error, and I've figured it's something in this PHP that's handling the call.
I'm not convinced it's the database entirely, as a call for 3500 records with no further processing other than the JSON being returned is generally done in 5s or less.
Why would this code be failing at 500+ records? I've tried AJAX timeout of 0.
I just start to use php webservice.I want to take all data in 'urun' table just sending 'id' Here is my code and i dont know how to solve it.
if($_GET["function"] == "getUrun"){
if(isset($_GET["id"]) && $_GET["id"] != ""){
$id = $_GET["id"];
$kategoriid =$_GET["kategoriid"];
$urunadi =$_GET["urunadi"];
$urunfiyati =$_GET["urunfiyati"];
$aciklama =$_GET["aciklama"];
$where="";
$where = "id='".$id."' AND kategoriid='".$kategoriid."' AND urunadi='".$urunadi."' AND urunfiyati='".$urunfiyati."' AND aciklama='".$aciklama."'";
$result = mysql_query("SELECT * FROM urun WHERE ".$where."");
$rows = array();
if($r=mysql_fetch_assoc($result))
{
$rows[] = $result;
$data = json_encode($rows);
echo "{ \"status\":\"OK\", \"getUrun\": ".$data." }";
}else{
echo "{ \"status\":\"ERR: Something wrong hepsi\"}";}
}else{
echo "{ \"status\":\"ERR: Something wrongs hepsi\"}";}
}
It should be:
if ($result) {
$rows = array();
while ($r = mysql_fetch_assoc($result)) {
$rows[] = $r;
}
echo json_encode(array('status' => 'OK', 'getUrun' => $rows));
} else {
echo json_encode(array('status' => 'ERR: Something wrong hepsi'));
}
You need to get all the results in an array, and then encode the whole thing. You should also use json_encode for the containing object, don't try to create JSON by hand.
I have a php file that i connect to it with ajax and callback value is JSON
when i get data from php it dosnt show and when alert data i see Object
Where is my problem ?
PHP:
if(isset($_SERVER["HTTP_X_REQUESTED_WITH"])){
$query = mysql_query("select * from tab");
for ($i=0;$i<mysql_num_rows($query);$i++){
while($row = mysql_fetch_assoc($query)){
$title['t'][i] = $row['title'];
$title['d'][i] = $row['description'];
}
}
echo(json_encode($title));
exit();
?>
JS:
$('#button').click(function(){
$.ajax({
url : "test2.php",
data : $("#tab"),
type : "GET",
success : function(b){
b = eval('('+ b +')');
console.log((b['t']));
alert(b);
}
});
});
How can i get all of data from this JSON and show me corect it ?
Here's a full working example with single row fetch and multi row fetch, without using mysql_ syntax and using prepared statements to prevent sql injections.
And yes, DON'T use mysql specific syntax, like I mentioned here: I cant get the form data to go into database. What am I doing wrong?
function example()
{
var select = true;
var url = '../scripts/ajax.php';
$.ajax(
{
// Post select to url.
type : 'post',
url : url,
dataType : 'json', // expected returned data format.
data :
{
'select' : select // the variable you're posting.
},
success : function(data)
{
// This happens AFTER the PHP has returned an JSON array,
// as explained below.
var result1, result2, message;
for(var i = 0; i < data.length; i++)
{
// Parse through the JSON array which was returned.
// A proper error handling should be added here (check if
// everything went successful or not)
result1 = data[i].result1;
result2 = data[i].result2;
message = data[i].message;
// Do something with result and result2, or message.
// For example:
$('#content').html(result1);
// Or just alert / log the data.
alert(result1);
}
},
complete : function(data)
{
// do something, not critical.
}
});
}
Now we need to receive the posted variable in ajax.php:
$select = isset($_POST['select']) ? $_POST['select'] : false;
The ternary operator lets $select's value become false if It's not set.
Make sure you got access to your database here:
$db = $GLOBALS['db']; // An example of a PDO database connection
Now, check if $select is requested (true) and then perform some database requests, and return them with JSON:
if($select)
{
// Fetch data from the database.
// Return the data with a JSON array (see below).
}
else
{
$json[] = array
(
'message' => 'Not Requested'
);
}
echo json_encode($json);
flush();
How you fetch the data from the database is of course optional, you can use JSON to fetch a single row from the database or you can use it return multiple rows.
Let me give you an example of how you can return multiple rows with json (which you will iterate through in the javascript (the data)):
function selectMultipleRows($db, $query)
{
$array = array();
$stmt = $db->prepare($query);
$stmt->execute();
if($result = $stmt->fetchAll(PDO::FETCH_ASSOC))
{
foreach($result as $res)
{
foreach($res as $key=>$val)
{
$temp[$key] = utf8_encode($val);
}
array_push($array, $temp);
}
return $array;
}
return false;
}
Then you can do something like this:
if($select)
{
$array = array();
$i = 0;
$query = 'SELECT e.result1, e.result2 FROM exampleTable e ORDER BY e.id ASC;';
foreach(selectMultipleRows($db, $query) as $row)
{
$array[$i]["result1"] = $row['result1'];
$array[$i]["result2"] = $row['result2'];
$i++;
}
if(!(empty($array))) // If something was fetched
{
while(list($key, $value) = each($array))
{
$json[] = array
(
'result1' => $value["result1"],
'result2' => $value["result2"],
'message' => 'success'
);
}
}
else // Nothing found in database
{
$json[] = array
(
'message' => 'nothing found'
);
}
}
// ...
Or, if you want to KISS (Keep it simple stupid):
Init a basic function which select some values from the database and returns a single row:
function getSingleRow($db, $query)
{
$stmt = $db->prepare($query);
$stmt->execute();
// $stmt->execute(array(":id"=>$someValue)); another approach to execute.
$result = $stmt->fetch(PDO::FETCH_ASSOC);
if($result)
{
$array = (
'result1' => $result['result1'],
'result2' => $result['result2']
);
// An array is not needed for a single value.
return $array;
}
return false;
}
And then fetch the row (or the single value) and return it with JSON:
if($select)
{
// Assume that the previously defined query exists.
$results = getSingleRow($db, $query);
if($results !== false)
{
$json[] = array
(
'result1' => $results['result1'],
'result2' => $results['result2'],
'message' => 'success'
);
}
else // Nothing found in database
{
$json[] = array
(
'message' => 'nothing found'
);
}
}
// ...
And if you want to get the value of $("#tab") then you have to do something like $("#tab").val() or $("#tab").text().
I hope that helps.
I suggest to use either:
b = jQuery.parseJSON(data)
see more here
or
$.getJSON
instead of eval()