Fetch API file upload failing while XHR works - javascript

I'm trying to asynchronously upload a file via javascript in the background. I'm updating our library to use fetch instead of XHR. The XHR request works correctly and the network tab shows the expected response which is currently just a var_dump($_FILES) and a var_dump($_POST).
When I make the same call with fetch for some reason the PHP stops running on the session creation.
I've isolated it down to the line:
$session = new Session;
Here is a cleaned up version of the XHR which returns both of those PHP arrays populated correctly
var request = {},
url = "../../lib/upload.php",
formData = new FormData;
formData.append(
"PHP_SESSION_UPLOAD_PROGRESS", phpSessionKey // upload session key var
);
formData.append(
"uploaded_file", this.file.baseFile // file object from an upload input
);
formData.append(
"pageid", 1234
);
request = new XMLHttpRequest();
request.open("POST", url, true);
request.onreadystatechange = function () {
if (request.readyState === 4 && request.status === 200) {
console.log(responseText);
}
}
request.send(formData);
Here is the comparable fetch, mind you I've looked at headers and everything else which all seem to be identical but I can not figure out why the fetch version exits on that session creation line.
let formData = new FormData(),
phpSessionKey = Uploader.pageid + "_" + this.file.name,
that = this;
formData.append(
"PHP_SESSION_UPLOAD_PROGRESS", phpSessionKey
);
formData.append(
"uploaded_file", this.file.baseFile
);
formData.append(
"pageid", Uploader.pageid
);
fetch('../lib/upload.php', {
method: 'POST',
body: formData
});
This fetch in the network tab returns nothing and by going in and comment then uncommenting lines I've narrowed the issue down to the session creation line in upload.php. I'm honestly just confused about why this is happening at this point, trying to bring out JS standards up has been pretty smooth sailing until now.
EDIT
Here is the session class in PHP:
class Session {
private $user_id;
private $last_login;
private $database;
public $user;
public $username;
public const MAX_LOGIN_AGE = 60 * 60 * 24; // 1 day
// Constructor which attaches pseudo magic methods to php sessions
public function __construct()
{
session_set_save_handler(
array($this, '_open'),
array($this, '_close'),
array($this, '_read'),
array($this, '_write'),
array($this, '_destroy'),
array($this, '_clean')
);
session_start();
$this->check_stored_login();
}
public function _open()
{
if ($session_db = db_connect(DB_DEV)) {
$this->database = $session_db;
return true;
}
return false;
}
public function _close()
{
// print "Session closed.\n";
return $this->database->close();
}
public function _read($id)
{
$id = $this->database->escape_string($id);
// print "Session read.\n";
// print "Sess_ID: $id\n";
$sql = "SELECT data
FROM sessions
WHERE id = '{$id}'";
if ($result = $this->database->query($sql)) {
if ($result->num_rows) {
$record = $result->fetch_assoc();
return $record['data'];
}
}
return '';
}
public function _write($id, $data)
{
$access = time();
$id = $this->database->escape_string($id);
$access = $this->database->escape_string($access);
$data = $this->database->escape_string($data);
// print "Session value written.\n";
// print "Sess_ID: $id\n";
// print "Data: $data\n\n";
$sql = "REPLACE
INTO sessions (`id`, `access`, `data`)
VALUES ('{$id}', '{$access}', '{$data}')";
$this->database->query($sql);
return true;
}
public function _destroy($id)
{
$id = $this->database->escape_string($id);
// print "Session destroy called.\n";
$sql = "DELETE
FROM sessions
WHERE id='{$id}'";
return $this->database->query($sql);
}
public function _clean($max)
{
$old = $time() - $max;
$this->database->escape_string($old);
$sql = "DELETE
FROM sessions
WHERE access < '{$old}'";
return $this->database->query($sql);
}
public function login($user)
{
if ($user) {
// prevent session fixation attacks
session_regenerate_id();
$this->user_id = $_SESSION['user_id'] = $user->id = $user->id;
$this->username = $_SESSION['username'] = $user->first_name;
$this->last_login = $_SESSION['last_login'] = time();
$this->user = $_SESSION['user'] = $user;
$_SESSION['search_text'] = '';
$_SESSION['search_product_id'] = '';
$args["last_login"] = date("Y-m-d H:m:s");
$user->merge_attributes($args);
$user->save();
}
}
public function is_logged_in()
{
if (!isset($this->user_id) || !$this->last_login_recent()) {
redirect_to(url_for('/index.php?logout'));
}
return true;
}
public function logout()
{
unset($_SESSION['user_id']);
unset($_SESSION['username']);
unset($_SESSION['last_login']);
unset($_SESSION['user']);
unset($this->user_id);
unset($this->username);
unset($this->last_login);
unset($this->user);
session_destroy();
return true;
}
private function check_stored_login()
{
if (isset($_SESSION['user_id'])) {
$this->user_id = $_SESSION['user_id'];
$this->username = $_SESSION['username'];
$this->last_login = $_SESSION['last_login'];
$this->user = $_SESSION['user'];
}
}
private function last_login_recent()
{
if (!isset($this->last_login)) {
return false;
} elseif ($this->last_login + self::MAX_LOGIN_AGE < time()) {
return false;
} else {
return true;
}
}
public function message($msg = '')
{
if (!empty($msg)) {
$_SESSION['message'] = $msg;
} else {
return $_SESSION['message'];
}
}
}
?>

Related

AJAX not outputting correct thing

So I'm trying to call a php method from javascript so I can query a database and get the results into my js functionality. Currently, the 'console.log(output)' that is in my ajax is just outputting:
"array (size=1)
'action' => string 'getResults' (length=10)'"
Not really sure why it's doing this, it should be returning the query result which is just one entry from the database. Anyone have any idea? Any help is welcome! Thanks.
Part of my Javascript file:
function callPHP() {
$.ajax ({
type: "GET",
datatype: "application/json",
url: "BaseClass.php",
data: { action : 'getResults' },
//error: function(err){console.log(err)},
success: function(output) {
console.log(output);
//alert(output);
}
//error, function(err){console.log(err)}
});
}
callPHP();
BaseClass.php:
<?php
error_reporting(E_ALL); ini_set('display_errors', 1);
require("Conn.php");
require("MySQLDao.php");
$param=$_REQUEST['action'];
echo var_dump($_GET);
/*
$handle = fopen("php://input", "rb");
$param = '';
while (!feof($handle)) {
$param .= fread($handle, 8192);
}
fclose($handle);
*/
if (empty($param))
{
$returnValue["status"] = false;
$returnValue["title"] = "Error";
$returnValue["message"] = "No Data Recieved paige" .$param ."...";
echo json_encode($returnValue);
return;
}
else
{
$dao = new MySQLDao();
if ($dao->openConnection() == false)
{
$returnValue["status"] = false;
$returnValue["title"] = "Error";
$returnValue["message"] = "Connection Could Not Be Established Between Server And Database";
echo json_encode($returnValue);
}
else
{
//Decodes data, dont change
$body = json_decode($param, true);
$recieved = $body["data"];
//Gets the result of a query
//$result = $dao->MySQLDaoMethodName(parameters);
//Return the result of the query
//echo json_encode($result);
}
$dao->closeConnection();
return;
}
?>
Conn.php - this is all the connection info, * out for confidential reasons:*
<?php
error_reporting(E_ALL); ini_set('display_errors', 1);
class Conn
{
public static $dbhost = "***";
public static $dbname = "***";
public static $dbuser = "***";
public static $dbpass = "***";
}
?>
MySQLDao.php - this file holds the querys:
<?php
error_reporting(E_ALL); ini_set('display_errors', 1);
//Class for holding queries
class MySQLDao
{
var $dbhost = null;
var $dbuser = null;
var $dbpass = null;
var $mysqli = null;
var $dbname = null;
var $result = null;
//constructor
function __construct()
{
$this->dbhost = Conn::$dbhost;
$this->dbuser = Conn::$dbuser;
$this->dbpass = Conn::$dbpass;
$this->dbname = Conn::$dbname;
}
//Attempt a connection to the database
public function openConnection()
{
//Try and connect to the database
$this->mysqli = new mysqli($this->dbhost, $this->dbuser, $this->dbpass, $this->dbname);
//If the connection threw an error, report it
if (mysqli_connect_errno())
{
return false;
}
else
{
return true;
}
}
//Get method for retrieving the database conection
public function getConnection()
{
return $this->mysqli;
}
//Close the connection to the database
public function closeConnection()
{
//If there is a connection to the database then close it
if ($this->mysqli != null)
$this->mysqli->close();
}
//-----------------------------------QUERY METHODS-------------------------------------
public function getResults($data)
{
$sql = "SELECT room.room_description FROM room WHERE room.room_id = 1";
$result = $this->mysqli->query($sql);
//if (mysql_num_rows($result) == 1) {
// $obj = mysql_fetch_object($result, 'obResults');
//}
echo json_encode($result);
echo($result);
}
}
?>
I think you misunderstand how to ship data between javscript and php.
Your javascript should be posting with $.post() if you want to send an object or array of data.
Your php will recieve json from the javascript. You need to use php's json_decode function on it to make it useful to php.
If you want the output of your php script to be useful to javascript, you need to encode it with php's json_encode function before returning it to the calling script.
http://php.net/manual/en/function.json-decode.php
The output is for echo var_dump($_GET); I'm sure. I can tell because of the output format is a var_dump type. and the success part of your code does not have any output. I mean in this part else { //Decodes data, dont change ... the output has been commented out.
I noticed that you are using MySqli but some methods are MySql api like this part of the code
//if (mysql_num_rows($result) == 1) {
// $obj = mysql_fetch_object($result, 'obResults');
//}
I assume this code is not complete and in debugging phase as I can see many incomplete methods and function calls.
Also try to use prepared statements with place holders for security.
It is a good practice to use ob_clean() before API output as any extra character will destroy the output data and format. However, you will not see errors. There are useful tools for API testing like Browsers Rest Client extensions. The best way for debugging is always debugging tools and frameworks like x-debug.
Do following changes to your code. Hope this helps!
BaseClass.php:
<?php
error_reporting(E_ALL); ini_set('display_errors', 1);
require("Conn.php");
require("MySQLDao.php");
$param=$_REQUEST['action'];
// echo var_dump($_GET);
/*
$handle = fopen("php://input", "rb");
$param = '';
while (!feof($handle)) {
$param .= fread($handle, 8192);
}
fclose($handle);
*/
if (empty($param))
{
$returnValue["status"] = false;
$returnValue["title"] = "Error";
$returnValue["message"] = "No Data Recieved paige" .$param ."...";
ob_clean();
echo json_encode($returnValue);
exit();
}
else
{
$dao = new MySQLDao();
if ($dao->openConnection() == false)
{
$returnValue["status"] = false;
$returnValue["title"] = "Error";
$returnValue["message"] = "Connection Could Not Be Established Between Server And Database";
//Clean up before output
ob_clean();
echo json_encode($returnValue);
exit();
}
else
{
//Decodes data, dont change
$body = json_decode($param, true);
$recieved = $body["data"];
//Gets the result of a query
$result = $dao->getResults($recieved);
//Close connection as fast as possible
$dao->closeConnection();
//Return the result of the query
ob_clean();
echo json_encode($result);
exit();
}
}
?>
MySQLDao.php
<?php
error_reporting(E_ALL); ini_set('display_errors', 1);
//Class for holding queries
class MySQLDao
{
var $dbhost = null;
var $dbuser = null;
var $dbpass = null;
var $mysqli = null;
var $dbname = null;
var $result = null;
//constructor
function __construct()
{
$this->dbhost = Conn::$dbhost;
$this->dbuser = Conn::$dbuser;
$this->dbpass = Conn::$dbpass;
$this->dbname = Conn::$dbname;
}
//Attempt a connection to the database
public function openConnection()
{
//Try and connect to the database
$this->mysqli = new mysqli($this->dbhost, $this->dbuser, $this->dbpass, $this->dbname);
//If the connection threw an error, report it
if (mysqli_connect_errno())
{
return false;
}
else
{
return true;
}
}
//Get method for retrieving the database conection
public function getConnection()
{
return $this->mysqli;
}
//Close the connection to the database
public function closeConnection()
{
//If there is a connection to the database then close it
if ($this->mysqli != null)
$this->mysqli->close();
}
//-----------------------------------QUERY METHODS-------------------------------------
public function getResults($data)
{
$sql = "SELECT room.room_description FROM room WHERE room.room_id = ?";
$stsm = $this->mysqli->prepare($sql);
$stsm->bind_param('i',1);
$result = $stmt->execute();
if (mysqli_num_rows($result) == 1) {
$obj = mysqli_fetch_object($result, 'obResults');
return $obj;
}
return false;
}
}
?>

Call data back from AJAX

I have a script which saves canvas PNGs to a directory and I need the URL to save on the server.
When I submit, the image saves but the server remains empty. I am trying to return error messages but I am receiving nothing.
JAVASCRIPT:
function doodleSave() {
var drawing = document.getElementById("doodle-canvas");
var drawingString = drawing.toDataURL("image/png");
var postData = "canvasData="+drawingString;
var ajax = new XMLHttpRequest();
ajax.open("POST", 'http://www.website.com/php/doodleSave.php', true);
ajax.onreadystatechange= function() {
if (ajax.readyState === 4) //If it ran smoothly
{$("#doodle-submit-button").html("...");}
};
ajax.send(postData);
ajax.success(function(data) {
{$("#doodle-submit-button").html(""+data+"");}
});
}
PHP:
<?php
session_start();
if (isset($GLOBALS["HTTP_RAW_POST_DATA"])) {
$rawImage = $GLOBALS['HTTP_RAW_POST_DATA'];
$removeHeaders = substr($rawImage, strpos($rawImage, ",")+1);
$url = md5(uniqid(rand(), true));
$decode = base64_decode($removeHeaders);
$fopen = fopen('../images/external/doodles/'.$url.'.png', 'wb');
fwrite($fopen, $decode);
fclose($fopen);
//ADD POST TO DATABASE WITH USER'S ID
/* AUTOMATED VARIABLES */
$unique_user_id = $_SESSION['unique_user_id'];
$unique_post_id = md5(uniqid(rand(), true));
$timestamp = time();
$nature = "doodle";
$imageUrl = 'images/external/doodles/'.$url;
try
{
$stmt = $pdo->prepare("INSERT INTO `(table name)` (unique_user_id, unique_post_id, nature, image_url, timestamp) VALUES(:unique_user_id, :unique_post_id, :nature, :image_url, :timestamp)");
$stmt->bindParam(":unique_user_id",$profile_unique_user_id);
$stmt->bindParam(":unique_post_id",$unique_post_id);
$stmt->bindParam(":nature",$nature);
$stmt->bindParam(":image_url",$imageUrl);
$stmt->bindParam(":timestamp",$timestamp);
if($stmt->execute())
{
echo "uploaded";
}
else
{
echo "Could not upload";
}
}
catch(PDOException $e){
echo $e->getMessage();
}
}
?>

Call to undefined method mysqli_stmt::get_result() on line 43 [duplicate]

This question already has answers here:
Call to undefined method mysqli_stmt::get_result
(10 answers)
Closed 6 years ago.
I have a small problem. When I try to login on a script I worked on I can not login. I hope you guys can help me out. For some reason I get this MySQL error:
Call to undefined method mysqli_stmt::get_result() in
home/[username]/public_html/inc/session.php on line 43
The code for session.php:
<?php
class Session {
private $self_file = 'session.php';
private $mysqli = false;
public function __construct($m) { $this->mysqli = $m; }
public function isLogged() {
if(!isset($_SESSION['invento_logged']) || !is_array($_SESSION['invento_logged']))
return false;
if(!isset($_SESSION['invento_logged']['u']) || !isset($_SESSION['invento_logged']['p']))
return false;
$u = $_SESSION['invento_logged']['u'];
$p = $_SESSION['invento_logged']['p'];
$prepared = $this->prepare("SELECT count(*) as c FROM invento_users WHERE username=? && password=?", 'isLogged()');
$this->bind_param($prepared->bind_param('ss', $u, $p), 'isLogged()');
$this->execute($prepared, 'isLogged()');
$result = $prepared->get_result();
$row = $result->fetch_object();
if($row->c == 1)
return true;
return false;
}
public function refresh_password($pass) {
$_SESSION['invento_logged']['p'] = md5($pass);
return true;
}
public function login($u, $p) {
$p = md5($p);
$prepared = $this->prepare("SELECT count(*) as c FROM invento_users WHERE username=? && password=?", 'isLogged()');
$this->bind_param($prepared->bind_param('ss', $u, $p), 'login()');
$this->execute($prepared, 'login()');
$result = $prepared->get_result();
$row = $result->fetch_object();
if($row->c != 1)
return false;
$_SESSION['invento_logged']['u'] = $u;
$_SESSION['invento_logged']['p'] = $p;
return true;
}
public function logout() {
if(isset($_SESSION['invento_logged']))
$_SESSION['invento_logged'] = false;
unset($_SESSION);
session_destroy();
return true;
}
public function get_user_id() {
$username = $_SESSION['invento_logged']['u'];
$prepared = $this->prepare("SELECT id FROM invento_users WHERE username=?", 'get_user_id()');
$this->bind_param($prepared->bind_param('s', $username), 'get_user_id()');
$this->execute($prepared, 'get_user_id()');
$result = $prepared->get_result();
$row = $result->fetch_object();
return $row->id;
}
public function get_user_name_by_id($id) {
$prepared = $this->prepare("SELECT username FROM invento_users WHERE id=?", 'get_user_name_by_id()');
$this->bind_param($prepared->bind_param('i', $id), 'get_user_name_by_id()');
$this->execute($prepared, 'get_user_name_by_id()');
$result = $prepared->get_result();
$row = $result->fetch_object();
return $row->username;
}
public function get_user_role() {
$id = $this->get_user_id();
$prepared = $this->prepare("SELECT role FROM invento_users WHERE id=?", 'get_user_role()');
$this->bind_param($prepared->bind_param('i', $id), 'get_user_role()');
$this->execute($prepared, 'get_user_role()');
$result = $prepared->get_result();
$row = $result->fetch_object();
return $row->role;
}
/***
* Private functions
*
***/
private function prepare($query, $func) {
$prepared = $this->mysqli->prepare($query);
if(!$prepared)
die("Couldn't prepare query. inc/{$this->self_file} - $func");
return $prepared;
}
private function bind_param($param, $func) {
if(!$param)
die("Couldn't bind parameters. inc/{$this->self_file} - $func");
return $param;
}
private function execute($prepared, $func) {
$exec = $prepared->execute();
if(!$exec)
die("Couldn't execute query. inc/{$this->self_file} - $func");
return $exec;
}
private function query($query, $func) {
$q = $this->mysqli->query($query);
if(!$q)
die("Couldn't run query. inc/{$this->self_file} - $func");
return $q;
}
public function __destruct() {
if(is_resource($this->mysqli) && get_resource_type($this->mysqli) == 'mysql link')
$this->mysqli->close();
}
}
$_session = new Session($mysqli);
and the code for config.php:
<?php
session_start();
/************ You can edit details starting from here ************/
$dbhost = '(I've filled this in'; // Write your MySQL host here.
$dbuser = 'I've filled this in'; // Write your MySQL User here.
$dbpass = 'I've filled this in'; // Write your MySQL Password here.
$dbname = 'I've filled this in'; // Write the MySQL Database where you want to install
/************ DON'T EDIT NOTHING BELOW ************/
if(!isset($noredir) && $dbhost == 'localhost' && $dbuser == 'MYSQL USERNAME' && $dbpass == 'MYSQL PASSWORD')
header('Location:install.php');
if(!isset($noredir)) {
$mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
if($mysqli->connect_errno)
die('<h2>Something went wrong while trying to connect to your MySQL Database. Error No. ' . $mysql->connect_errno.'<h2>');
// Check existance of random table to test installed system
$tables = array('users','categories','items','logs','settings');
$rn = rand(0,4);
$res = $mysqli->query("SHOW TABLES LIKE '%invento_{$tables[$rn]}%'");
if($res->num_rows == 0)
header('Location:install.php');
}
I hope you guys can help me out.
Thanks in advance,
Bram
I think it's because of the version of PHP that you are using.
As mentioned in php documentation mysqli_stmt::get_result, this method is supported since PHP 5.3.0.
And it is stated in the user notes section that:
This method requires the mysqlnd driver. Othervise you will get this error: Call to undefined method mysqli_stmt::get_result()
Instead of this function, try using bind_result function.
Helpful link
http://php.net/manual/en/mysqli-stmt.get-result.php

how I can do a ajax jquery http request with javascript and php on serversite?

hi i have a webapplication with html,css and javascript. I use Bootstrap and jQuery. I have a client and a server site.
On my Client site I have a index.html:
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.js"></script>
<script src="js/script.js"></script>
</head>
<body>
<button type="button" id="add">Mitarbeiter hinzufügen</button>
<div id="TableContent"></div>
</body>
</html>
here my js:
$(document).ready(function() {
// Fill table with data from server on first load
$.ajax({
type: "GET",
url: "../server/server.php",
data: {
method: "all"
},
success: function(content) {
// Create table content from server data
var table = $.makeTable($.parseJSON(content));
// Append table data to table element in index.html
$(table).appendTo("#TableContent");
}
});
my php:
<?php
// partly from
// gonzalo123.wordpress.com/2010/01/09/building-a-simple-http-client-with-php-a-rest-client
class Request
{
public $url_elements;
public $methode;
public $parameters;
public function __construct()
{
$this->methode = $_SERVER['REQUEST_METHOD'];
$this->url_elements = explode('/', $_SERVER['PATH_INFO']);
// get GET/DELETE or POST/PUT parameters
$parameters = array();
if (isset($_SERVER['QUERY_STRING'])) { // get GET/DELETE parameters
parse_str($_SERVER['QUERY_STRING'], $parameters);
}
$body = file_get_contents("php://input"); // get POST/PUT request body
parse_str($body, $postvars);
foreach ($postvars as $field => $value) {
$parameters[$field] = $value; // overwrite GET/DELETE parameteres
}
$this->parameters = $parameters;
}
}
class RequestHandler
{
public function getAction($request)
{
$data = $request->parameters;
// It's only an example code of how to return data from server
// You need to read information about users from a file data.json
switch ($request->parameters['method']) {
case 'all':
// Create an object of a standard class and add custom
// variables like Id, Vorname, Nachname and so on
$person1 = new stdClass;
$person1->Id = 1;
$person1->Vorname = "Max";
$person1->Nachname = "Mustermann";
$person1->Geburtstag = "11.11.1980";
$person1->Abteilung = "Personal";
$person2 = new stdClass;
$person2->Id = 2;
$person2->Vorname = "Sabine";
$person2->Nachname = "Musterfrau";
$person2->Geburtstag = "05.12.1989";
$person2->Abteilung = "Finanzen";
// Add person in array
$persons = array();
array_push($persons, $person1);
array_push($persons, $person2);
// Encode array to json string and return to client
return json_encode($persons);
break;
case 'single_user':
break;
default: // do nothing, this is not a supported action
break;
}
return json_encode($data);
}
public function deleteAction($request)
{
$data = $request->parameters;
return json_encode($data);
}
public function postAction($request)
{
$data = $request->parameters;
return json_encode($data);
}
public function putAction($request)
{
$data = $request->parameters;
return json_encode($data);
}
}
$request = new Request();
$handler = new RequestHandler();
// tricky: construct call methode depending on HTTP-request-method, e.g. "postAction"
$action = strtolower($request->methode) . 'Action';
$result = $handler->$action($request);
print_r($result);
Check if PATH_INFO is set as this triggers a PHP notice causing invalid json string response. You can also use error_reporting(E_ALL & ~E_NOTICE); to hide notices. See http://php.net/manual/en/function.error-reporting.php
<?php
// partly from
// gonzalo123.wordpress.com/2010/01/09/building-a-simple-http-client-with-php-a-rest-client
class Request
{
public $url_elements;
public $methode;
public $parameters;
public function __construct()
{
$this->methode = $_SERVER['REQUEST_METHOD'];
if(isset($_SERVER['PATH_INFO'])) $this->url_elements = explode('/', $_SERVER['PATH_INFO']);
else $this->url_elements = array();
// get GET/DELETE or POST/PUT parameters
$parameters = array();
if (isset($_SERVER['QUERY_STRING'])) { // get GET/DELETE parameters
parse_str($_SERVER['QUERY_STRING'], $parameters);
}
$body = file_get_contents("php://input"); // get POST/PUT request body
parse_str($body, $postvars);
foreach ($postvars as $field => $value) {
$parameters[$field] = $value; // overwrite GET/DELETE parameteres
}
$this->parameters = $parameters;
}
}
Your script should look like this:
$(document).ready(function() {
$.ajax({
type: "GET",
url: "../server/server.php",// adjust this to be a valid relative URL or an absolute URL
data: {
method: "all"
},
dataType: "json",
success: function(content) {
var table = $.makeTable($.parseJSON(content));
$(table).appendTo("#TableContent");
}
});
});

print variable in the alert

i have this model function for counting the number of users
public function get_employee_list($role_id) {
$qStr = "SELECT
count(admins.id)
FROM
admins
WHERE
admin_role=".$role_id;
$query = $this->db->query($qStr);
return $query->row_array();
}
and my controller function is like this
public function delete_employee_role_ajax($role_id) {
$objResponse = new xajaxResponse();
$response = $this->employee_model->get_employee_list($role_id);
//print_r($response);
if($response) {
$objResponse->script( "bootbox.alert('$response +users are associated with this role and it cannot be deleted')" );
}
else {
$response = $this->employee_model->delete_employee_role($role_id);
$objResponse->script( "window.location.reload()" );
}
return $objRespons
}
i want to print the value of $response.
You could try encoding it as a JSON structure:
$encodedResponse = json_encode($response);
$objResponse->script("bootbox.alert('$encodedResponse +users are associated...')" );

Categories

Resources