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.
Related
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;
}
?>
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.
I am trying to update values in the DB using values from a JSON file:
Code:
$jsonData = file_get_contents($jsonFile);
$data = json_decode($jsonData, true);
//check if hospital exist
$name = explode(' ',trim($data['organisationUnits']['organisationUnit']['name']));
// echo $name[0];
$query = Hospital::where('h_name', 'LIKE' , '%' . $data['organisationUnits']['organisationUnit']['name'] . '%')->first();
if($query){
// echo "\n yupo";
$h_id = $query->id;
$h_slug = $query->h_slug;
$nr_orgUnit = $query->nr_orgUnit;
// echo $nr_orgUnit;
$updateHospital = Hospital::find($h_id);
$updateHospital->h_name = $data["organisationUnits"]["organisationUnit"]["name"];
$updateHospital->h_short_name = $data["organisationUnits"]["organisationUnit"]["shortName"];
$updateHospital->h_code = $data["organisationUnits"]["organisationUnit"]["code"];
$updateHospital->h_opening_date = $data["organisationUnits"]["organisationUnit"]["openingDate"];
$updateHospital->h_closed_date = $data["organisationUnits"]["organisationUnit"]["closedDate"];
$updateHospital->h_active = $data["organisationUnits"]["organisationUnit"]["active"];
$updateHospital->h_comment = $data["organisationUnits"]["organisationUnit"]["comment"];
$updateHospital->h_geo_code = $data["organisationUnits"]["organisationUnit"]["geoCode"];
$updateHospital->h_last_updated = $data["organisationUnits"]["organisationUnit"]["lastUpdated"];
$updateHospital->save();
} else {
// echo 'error';
}
JSON DATA:
{"organisationUnits":{
"organisationUnit":{
"id":"01",
"uuid":{
},
"name":"Isagehe Dispensary",
"shortName":"Isagehe Dispensary ",
"code":"17-04-0118",
"openingDate":"1990-01-01",
"closedDate":{
},
"active":"true",
"comment":{
},
"geoCode":{
},
"lastUpdated":{
}
}
}
}
when i try to run the code, i get the following error:
Array to string conversion (SQL: update `ag_hospitals` set `h_closed_date` = , `h_active` = true, `h_comment` = , `h_geo_code` = , `h_last_updated` = where `id` = 41)"
where might i be wrong?
Note i have also tried updating the following way:
$updateHospital = Hospital::where('id', $h_id)->update([
'h_name' => $data['organisationUnits']['organisationUnit']['name'],
'h_short_name' => $data['organisationUnits']['organisationUnit']['shortName'],
'h_code' => $data['organisationUnits']['organisationUnit']['code'],
'h_opening_date' => $data['organisationUnits']['organisationUnit']['openingDate'],
'h_closed_date' => $data['organisationUnits']['organisationUnit']['closedDate'],
'h_active' => $data['organisationUnits']['organisationUnit']['active'],
'h_comment' => $data['organisationUnits']['organisationUnit']['comment'],
'h_geo_code' => $data['organisationUnits']['organisationUnit']['geoCode'],
'h_last_updated' => $data['organisationUnits']['organisationUnit']['lastUpdated']
]);
You need to define that Attribute in Model that store that JSON Data as Array.
Example:
protected $casts = [
'column_name' => 'array'
];
I have tried to add a php file as the source of data for a jquery calendar that uses json as below:
<script>
$(document).ready(function() {
$("#eventCalendarHumanDate").eventCalendar({
eventsjson: 'modules/events/json/event.humanDate.json.php',
jsonDateFormat: 'human'
});
});
</script>
The php file works when i echo variables only but when i connected to the database and looped, it fails and i get the error "error getting json" But running my code separately i get no error from the php file itself.
<?php
$hostname_app_conn = "localhost";
$database_app_conn = "xx";
$username_app_conn = "xx";
$password_app_conn = "";
$app_conn = mysql_pconnect($hostname_app_conn, $username_app_conn, $password_app_conn) or trigger_error(mysql_error(),E_USER_ERROR);
mysql_select_db($database_app_conn, $app_conn );
$query_rs_content = "SELECT * FROM `mod_events_events` WHERE `active`=1 ORDER BY `Id` LIMIT 365";
$rs_content = mysql_query($query_rs_content, $app_conn) or die(mysql_error());
$totalRows_rs_content = mysql_num_rows($rs_content);
header('Content-type: text/json');
echo '[';
$separator = "";
$days = 16;
$i = 1;
echo $separator;
while($row_rs_content = mysql_fetch_assoc($rs_content))
{
echo ' { "date": "'.$row_rs_content['eventday'].'", "type": "'.$row_rs_content['type'].'", "title": "'.$row_rs_content['Title'].'", "description": "'.$row_rs_content['teasertext'].'", "url": "" },';
}
$separator = ",";
echo ']';
?>
thanks in advance.
You should use the json_encode() function, something like this:
//more code above
$array = new array();
while($row_rs_content = mysql_fetch_assoc($rs_content))
{
$array[] = array(
'date' => $row_rs_content['eventday'],
'type' => $row_rs_content['type'],
'title' => $row_rs_content['Title'],
'description' => $row_rs_content['teasertext'],
'url' => '',
);
}
header('Content-type: application/json');
echo json_encode($array);
die();
Most likely you had some character not being escaped properly or something else that was causing it not to be a valid json array so Javascript is dying trying to parse it.
How this code works is every time a user visits the page, i scrape all of the data from the table and pass it through the below posts. If the user hasn't accessed that page before and the database is empty with their cookie_id, then it inserts the content, if it is found then it deletes the content from the database and inserts it again. The problem I am having though is that when the deletion occurs it deletes everything and seems to insert one value from $data1 instead of all the data from $data. Any ideas as to why this is happening?
Backend:
$cookie_id = $this->input->cookie("session_id");
$selected_size = $this->input->post('selected_size');
$product_id = $this->input->post('product_id');
$product_name = $this->input->post('product_name');
$product_color = $this->input->post('product_color');
$q1 = $this->db->query("SELECT * FROM default_cart_temp
WHERE cookie_id = '$cookie_id'
AND is_paid = 'No'");
if ($q1->num_rows() > 0) {
$this->db->where('cookie_id', $cookie_id);
$this->db->delete('default_cart_temp');
foreach($product_id as $key => $value) {
$data1 = array('selected_size' => $selected_size[$key],
'product_id' => $value,
'product_name' => $product_name[$key],
'product_color' => $product_color[$key],
'cookie_id' => $cookie_id,
'is_paid' => 'No');
} $this->db->insert('default_cart_temp', $data1);
echo json_encode(array('success' => true));
} else {
foreach($product_id as $key => $value) {
$data = array('selected_size' => $selected_size[$key],
'product_id' => $value,
'product_name' => $product_name[$key],
'product_color' => $product_color[$key],
'cookie_id' => $cookie_id,
'is_paid' => 'No');
} $this->db->insert('default_cart_temp', $data);
}
Frontend:
selected_size = $('.selected_size1').text();
arr1 = selected_size.split(".");
ss1 = arr1.slice(0, -1);
product_id = $('.product_id1').text();
arr2 = product_id.split(".");
ss2 = arr2.slice(0, -1);
product_name = $('.product_name1').text();
arr3 = product_name.split(".");
ss3 = arr3.slice(0, -1);
product_color = $('.product_color1').text();
arr4 = product_color.split(".");
ss4 = arr4.slice(0, -1);
$.ajax({
type: "POST",
dataType: "JSON",
url: "<?=base_url()?>index.php/products/products/new_instance",
data: { selected_size: ss1, product_id: ss2, product_name: ss3, product_color: ss4 },
json: {success: true},
success: function(data) {
if(data.success == true) {
alert("True");
}
}
});
In every foreach loop execution you are overriding $data and $data1 variables. You have to change them to arrays and add data like this $data[] = $subArray.