I have use ajax to get a code from the database.
In my database shows my answer Nmap –T4 –F 10.15.0.0/24
and when ajax get that it shows Nmap �T4 �F 10.15.0.0/24 in my console.
I have use decodeEntities() for that but it is not working. I have put my coe below.
$.post('functions.php', {answer: answer, ID: ID, action: action, email: email, TestName:TestName}, function(response)
{
var data = decodeEntities(response);
console.log(data);
});
function decodeEntities(encodedString) {
var textArea = document.createElement('textarea');
textArea.innerHTML = encodedString;
return textArea.value;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
function category_array($con,$quiz_category){
$final_array = array();
foreach ($quiz_category as $row) {
$category = find_categoryname($row);
//print_r($category); die();
$query ="SELECT * FROM `$row` WHERE `ID` IN(18,205,166)";
$query_result = mysqli_query($con,$query);
if(mysqli_num_rows($query_result)) {
while($row = mysqli_fetch_assoc($query_result)){
$row["question_category"] = $category;
$final_array[] = utf8_converter($row);
//print_r($row); die();
}
}
//$final_array[] = $result_array;
}
return $final_array;
}
function utf8_converter($array){
array_walk_recursive($array, function(&$item, $key){
if(!mb_detect_encoding($item, 'utf-8', true)){
$item = utf8_encode($item);
}
});
return $array;
}
Related
This is the output I get from ajax request to php pdo:
[{"sys_id":"1","task":"qwe","task_date":"11\/30\/2017 8:49 PM","task_person":"qwe","task_status":"0"},{"sys_id":"2","task":"asd","task_date":"11\/30\/2017 9:54 PM","task_person":"asd","task_status":"0"}]null
As shown there is an excess null value which I cant figure out where it is coming from my code is:
function selecttask(action) {
$.ajax({
type: 'POST',
url: '../include/demo.php',
dataType: "json",
data: {
action: action
},
success: function(data) {
}
}).done(function(data) {
});
}
selecttask("selectall");
My demo.php is:
<?php
include_once("crud.php");
//include_once("../config/config.php");
//$con = new connect_pdo();
$crud = new Crud();
$action = $_POST['action'];
$data = $_POST['data'];
switch (strtolower($action)):
case("selectall"):
$table = "list_tbl";
$selectall = $crud->selectall($table);
echo json_encode($selectall, JSON_UNESCAPED_UNICODE);
break;
case("add"):
$table = "list_tbl";
$insert = $crud->insert($table,$data);
echo json_encode($insert, JSON_UNESCAPED_UNICODE);
break;
endswitch;
?>
Then crud is:
<?php
include_once("../config/config.php");
class Crud extends connect_pdo {
public $_con;
function __construct() {
parent::__construct();
$this->_con = $this->dbh();
}
public function selectall($table_name) {
$queryselectall = "Select * from {$table_name}";
$selectall = $this->_con->prepare($queryselectall);
if ($selectall->execute()) {
if ($selectall->rowCount() > 0) {
$result = $selectall->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($result, JSON_UNESCAPED_UNICODE);
}else{
echo array('error'=> TRUE, 'message'=> 'No result found.');
}
}
}
public function insert($table_name, $res) {
parse_str($res, $data);
$limit = count($data);
$ctr = 0;
$columns = "";
$values = "";
foreach ($data as $key => $value) {
$ctr++;
$columns.= "{$key}";
$values .= ":{$key}";
if ($ctr < $limit) {
$columns.= ",";
$values .= ",";
}
}
$query = "INSERT INTO {$table_name} ({$columns})VALUES({$values})";
try {
$create = $this->_con->prepare($query);
foreach ($data as $key => $value) {
$keys = ":{$key}";
$create->bindValue($keys, $value, PDO::PARAM_STR);
}
if ($create->execute()) {
$lastinserted_id = $this->_con->lastInsertId();
echo array('error' => FALSE, 'message' => 'Data added successfully.', 'lastinserted_id' => $lastinserted_id, 'query' => $query);
} else {
echo array('error' => TRUE, 'message' => 'Execution failed, please contact system support!');
}
} catch (Exception $ex) {
echo array('error' => TRUE, 'message' => $ex);
}
}
}
?>
From the above code I cant determine where the null is coming from.
Did I miss something that is why null is coming as result of ajax request
Probably a better architecture for your Crud class to handle DB interactions by running the queries and returning the results as an array (or throwing an exception if anything exceptional happens). Then your demo.php script can just get the array from the Crud class method and handle the output (json encoding, response output).
i was doing long polling , but it can see in my network chrome my long polling in status pending that means is waiting for new data and changes the database , but when I try to insert one item to my database then , but when I try to insert one value show keep that long polling in real time i cant see real time updatings .. how can I fix it?
pusher controller codeigiter
public function pusher() {
header('Content-Type: application/json');
$user_id = $this->session->log['id'];
set_time_limit(0);
while (true) {
$firstCall = false;
if (isset($_GET['timestamp'])) {
$last_ajax_call = $_GET['timestamp'];
} else {
$last_ajax_call = time();
$firstCall = true;
}
clearstatcache();
$notificationsCount = $this->notification->checkForNotifications($last_ajax_call, $user_id);
$newData = (int) $notificationsCount > 0 ? true : false;
$notifications = [];
if ($newData) {
$dataSet = $this->notification->getNotifications($user_id, $last_ajax_call);
foreach($dataSet as $data) {
$notifications[] = $data;
$finalNotificationTime = $data['timestamp'];
}
$result = array('notifications' => $notifications, 'timestamp' => $finalNotificationTime);
$json = json_encode($result);
echo $json;
break;
} else {
if ($firstCall) {
$dataSet = $this->notification->getUnreadNotifications($user_id);
foreach($dataSet as $data) {
$notifications[] = $data;
}
$result = array('notifications' => $notifications, 'timestamp' => $last_ajax_call);
$json = json_encode($result);
echo $json;
break;
}
sleep(1);
session_write_close();
continue;
}
}
exit();
}
ajax
function check_notifications(timestamp) {
var queryString = {
'timestamp': timestamp
};
$.ajax({
type: 'GET',
url: URL_GET_NOTIFICATION,
data: queryString,
success: function (data) {
// put result data into "obj"
for (var i in data.notifications) {
notify(data.notifications[i].message, data.notifications[i].type, data.notifications[i].timestamp);
}
check_notifications(data.timestamp);
}
});
}
check_notifications();
I have created a javascript file that contains js to trigger an event onchange of a drop down list. The JS is below:
// /public/js/custom.js
jQuery(function($) {
$("#parent").change(function(event){
event.preventDefault();
var parentID = $('#parent').val();
var id = $('#id').val();
$.post("/menu/GetMenuChildren", {pID: parentID, thisID: id },
function(data){
if(data.response === true){
var $el = $("#Position");
$el.empty(); // remove old options
$.each(data.newOptions, function(key, value) {
$el.append($("<option></option>")
.attr("value", value).text(key));
});
} else {
// print error message
alert("something went wrong in Post");
}
}, 'json');
alert("After Post");
});
});
In my Controller.php I have an function GetMenuChildrenAction as shown below:
public function GetMenuChildrenAction()
{
$request = $this->getRequest();
$response = $this->getResponse();
if ($request->isPost())
{
$post_data = $request->getPost();
$parent_id = $post_data['pID'];
$id = $post_data['thisID'];
//$this->form->get('Position')->SetOptionValues(
$newOptions = $this->getMenuTable()->GetPositionsByID($parent_id, $id);
if(isset($newOptions))
{
$response->setContent(\Zend\Json\Json::encode(array('response' => true, 'newOptions' => $newOptions)));
}
else
{
$response->setContent(\Zend\Json\Json::encode(array('response' => false)));
}
}
return $response;
}
In the MenuTable.php there is a Method GetPositionsByID as shown below:
public function GetPositionsByID($parentID, $id)
{
if($parentID == 0)
{
$menu = $this->getMenu($this->id);
$parentID = $menu->parent_id;
}
if(isset($parentID))
{
$sql = "Select ID,Label from Menu Where parent_ID = " . $parentID . " and id > 1 and id <> " . $id . " Order by Position,Label";
try
{
$statement = $this->adapter->query($sql);
}
catch(Exception $e) {
console.log('Caught exception: ', $e->getMessage(), "\n");
}
$res = $statement->execute();
$rows = array();
$i = 0;
foreach ($res as $row) {
$i = $i + 1;
$rows[$i] = array (
$i => $row['Label']
);
}
return $rows;
}
return array();
}
It all seems to be hooked up correctly, when I debug the code, I get the this line:
$statement = $this->adapter->query($sql);
and then nothing happens. If I replace all the code in the GetPositionsByID method, and simply return an array like the following:
return array('1' => 'one', '2' => 'two');
it works great, however i want to get the data from the DB. Does anyone know why the execute would fail on this line?
$statement = $this->adapter->query($sql);
Thanks in advance
The issue was that the adapter was null.
Here is the php code.In this code station name and ids and random passengers are produced.
<?php
include_once('RestUtils.php');
include_once('Passengers.php');
class Station implements JsonSerializable
{
private $id;
private $name;
private $passengers;
public function __construct($id, $name)
{
$this->setId($id);
$this->setName($name);
$this->passengers = array();
}
//getters and setters
public function jsonSerialize()
{
$data = array();
$data['id'] = $this->id;
$data['name'] = $this->name;
$data['passengers'] = $this->passengers;
return $data;
}
}
$stations = generateStations();
$data = RestUtils::processRequest();
switch($data->getMethod())
{
// Get item
case 'get':
if(isset($data->getRequestVars()['stationId']))
{
// Prepare information for a specific station
$station = getStationWithId($stations, $data->getRequestVars()
['stationId']);
if($station != null)
{
echo RestUtils::sendResponse(200, json_encode($station),
'application/json');
}
else
{
echo RestUtils::sendResponse(404, 'Station not found!');
}
}
else
{
// Prepare station list
echo RestUtils::sendResponse(200, json_encode($stations),
'application/json');
}
break;
}
function generateStations()
{
$stations = array();
for($i = 1; $i <= 5; $i++)
{
$stations[] = new Station($i, 'İstasyon ' . $i);
$passengerIds = array();
foreach(generatePassengers() as $j)
{
$passengerIds[] = $j->getId();
}
$stations[$i - 1]->setPassengers($passengerIds);
}
return $stations;
}
function generatePassengers()
{
$passengers = array();
$numberOfPassengers = rand(0, 20);
for($i = 0; $i < $numberOfPassengers; $i++)
{
$from = rand(0, 5);
$to = rand(0, 5);
$arrivalTime = rand(0, 100);
$waitingTime = rand(0, 100);
$passengers[] = new Passenger($i, $from, $to, $arrivalTime, $waitingTime);
}
return $passengers;
}
function getStationWithId($stations, $id)
{
foreach ($stations as $i)
{
if($i->getId() == $id)
{
return $i;
}
}
return null;
}
?>
I want to fill the combobox with the produced station name and station ids when the page is loaded using document ready function.After that when the user selects a station with name and id, he can see how many passengers are there in that station and the ids of the passengers also should be returned from Station.php.
Normally I have had this select options in html code, it just showing the stations not doing anything when choosing any of them.
<select name="selectStation" id="selectStation" ></select>
I tried the following;
$(document).ready(function() {
$.getJSON("Stations.php", function(jsonData){
$.each(jsonData, function(key,value) {
$('#selectStation')
.append($("<option></option>")
.attr("value",key)
.text(value));
});
});
});
I got the combobox values as object Object.Why does this happen?
How can fill the combobox when the page is loaded, according to Stations.php.Thanks.Any response will be appreciated.
Okay, here's some sample code that will do what I think you want.
Note: You still have to add an Event Listener to handle the change event of the select-box. I'll leave that to you.
File 1: ajaxAfterLoad.html
<!DOCTYPE html>
<html>
<head>
<script src="script/AjaxRequest.js"></script>
<script>
function byId(e){return document.getElementById(e);}
function newEl(tag){return document.createElement(tag);}
function newTxt(txt){return document.createTextNode(txt);}
window.addEventListener('load', mInit, false);
function mInit()
{
AjaxRequest.get( { 'url':'makeJSON.php', 'onSuccess': onAjaxRequestDone } );
}
function makeSelectElementFromJSON(elemId, jsonText)
{
var srcData = JSON.parse(jsonText);
var result = newEl('select');
result.setAttribute('id', elemId);
var i, curOpt;
for (i=0; i<srcData.length; i++)
{
curOpt = newEl('option');
curOpt.setAttribute('value', srcData[i].value);
curOpt.appendChild( newTxt( srcData[i].text ) );
result.appendChild(curOpt);
}
return result;
}
function onAjaxRequestDone(req)
{
var span = newEl('span');
span.innerHTML = req.responseText;
byId('rawOutput').innerHTML = req.responseText;
byId('ajaxOutput').appendChild( makeSelectElementFromJSON('jsonSelectBox1', req.responseText) );
}
</script>
<style>
</style>
</head>
<body>
<h2>Below will be loaded by ajax</h2>
<div id='rawOutput'></div>
<div id='ajaxOutput'></div>
</body>
</html>
File 2: makeJSON.php
<?php
$resultList = null;
for ($i=0; $i<10; $i++)
{
$curItem = null;
$curItem->value = $i;
$curItem->text = "Item " . ($i+1);
$resultList[] = $curItem;
}
printf("%s", json_encode($resultList) );
?>
File 3: AjaxRequest.js
Download this file from http://ajaxtoolbox.com/request/source.php
I have a function A which loads the data from db if the user has liked the image. I have another function B which loads the count for the total number of likes for the image. Both these functions return response using JSON.
If I call them individually, everything works fine, but if I call function B in function A, I get no JSON response and nothing happens although firebug does show two JSON arrays being outputted.
What is wrong with the code?
Function A:
public function loadLikes() {
//sql query
try
{
$query = $this->_db->prepare($sql);
$params = array(':imageid' => $imageid, ':author' => $author);
$query->execute($params);
//calling function B
$this->countLikes($imageid);
if ($query->rowCount() > 0) {
while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
if ($row['like'] == '1') {
$response = json_encode(array('like' => true));
echo $response;
return TRUE;
}
elseif ($row['like'] == '2') {
$response = json_encode(array('unlike' => true));
echo $response;
return TRUE;
}
else {
$error = "Invalid";
$response = json_encode(array('like' => false, 'text' => $error));
echo $response;
return FALSE;
}
}
}
else {
$response = json_encode(array('unlike' => true));
echo $response;
return FALSE;
}
}
catch(PDOException $ex)
{
echo json_encode(array('like' => false, 'text' => $ex));
return FALSE;
}
}
Function B:
public function countLikes($i) {
//sql query
try
{
$query = $this->_db->prepare($sql);
$params = array(':imageid' => $i);
$query->execute($params);
if ($query->rowCount() > 0) {
$count = $query->fetchColumn();
$response = json_encode(array('count' => $count));
echo $response;
return TRUE;
}
}
catch(PDOException $ex)
{
return FALSE;
}
}
jQuery:
$.ajax({
type: "POST",
url: url,
data: postData,
dataType: "json",
success: function(data){
$(".count-like").show(600).text(data.count);
if(data.like) {
$("a#alike").attr('class', 'starred');
}
else if (data.unlike) {
$("a#alike").attr('class', 'unlike');
}
else {
alert(data.text);
}
}
});
If you invoke both functions, then each will output a JSON array. This will result in a HTTP response with following content:
{"like":1}{"count":2}
Both arrays would be valid separately. But if concatenated like this, it's no longer valid JSON.
Instead of outputting the json serialization with echo you should collect it in a temporary variable, merge the two arrays, and then output the combined array with a single:
echo json_encode(array_merge($countArray, $likeArray));
Example adaptions of your code
Function B should become:
public function countLikes($i) {
//sql query
try
{
$query = $this->_db->prepare($sql);
$params = array(':imageid' => $i);
$query->execute($params);
if ($query->rowCount() > 0) {
$count = $query->fetchColumn();
/* JUST RETURN HERE */
return (array('count' => $count));
}
}
catch(PDOException $ex)
{
/* INSTEAD OF FALSE use an empty array,
which is interpreted as false in boolean context*/
return array();
}
}
Then when you call the function:
//calling function B
$countArray = $this->countLikes($imageid);
This will always be an array. Which you then can use in the output code:
$response = json_encode(array('like' => true) + $countArray);
(It's still inadvisable to have an echo right there. But too much code, too little context to propose a nicer rewrite. And if it works, ..)