Ajax Autocomplete TextBox from PostgreSQL Not getting Data - php

I am trying to us Ajax to call a php script which gets data from my PostgreSQL In php, my code is:
<?php
# Includes
require("database.inc.php");
require("json.inc.php");
# Retrive URL arguments
$table = $_REQUEST['table'];
$fields = isset($_REQUEST['fields']) ? $_REQUEST['fields'] : '*';
$parameters = isset($_REQUEST['parameters']) ? " where " . $_REQUEST['parameters'] : '';
$order = isset($_REQUEST['order']) ? " order by " . $_REQUEST['order'] : '';
$limit = isset($_REQUEST['limit']) ? " limit " . $_REQUEST['limit'] : '';
# Perform the query
$sql = "select " . $fields . " from " . $table . $parameters . $order . $limit;
$db = pgConnection();
$statement=$db->prepare( $sql );
$statement->execute();
# send JSON or JSONP results
sendJSON($statement);
?>
and here is my Ajax:
$.ajax({
url: "ws_geo_attributequery.php",
//table:'address',
//fields:'file_as_na',
type:'GET',
dataType: "jsonp",
data: {
'table:':'address',
'fields':'file_as_na',
id: 1
},
success: function(response){
var data = $(response).map(function(){
return {value: this.file_as_na, id: this.id};
}).get();
$('#name').autocomplete({
source: data,
minLength: 0,
select: function(event,ui){
$('input#id').val(ui.item.id);
}
});
}
});
I am not getting any result from my Db. I am sure the Problem in my ajax request.
I do appreciate any help.

Related

AJAX and PHP code not working

I am sending my form data through AJAX but for some reason my PHP script is not running. The test echo's Im using in my PHP script is not showing. The window.alert("success") does show but HIDE and SHOW form1 and form2 also does not work.
Here is the code:
$('#mainform').on('submit', function(event) {
//test for empty fields
//test for Bots
//insert data into DB
//pass t_code on to next form
//create a page number for tabs
event.preventDefault(); //stops form on submit
var a = document.forms["mainform"]["hidden"].value;
if (a === ""){
var formData = {};
$.each($("#mainform").serializeArray(), function (i, field) {
formData[field.name] = field.value;
});
$.ajax({
url: 'insert_tut_description.php',
data: formData,
method:'POST',
success: function(response) {
window.alert("success");
pnum = 1;
t_code = form.elements["t_code"].value;
$("#form1").hide();
$("#form2").show();
document.getElementById("pnum").innerHTML = pnum;
}
});
};
});
<?php
echo "php running";
require 'config/config.php';
$t_title = $conn->real_escape_string($_POST['t_title']);
$t_code = $conn->real_escape_string($_POST['t_code']);
$t_image = $conn->real_escape_string($_POST['t_image']);
$hidden = $conn->real_escape_string($_POST['hidden']);
$t_desc = $conn->real_escape_string($_POST['t_desc']);
$t_url = "something.php";
echo $t_title;
echo t_url;
if(empty($hidden)){
echo "hidden is empty";
$query = "INSERT into tutorial_list (title, description, t_code, t_url, image,) VALUES('" . $t_title . "','" . $t_desc . "','" . $t_code . "','" . $t_url . "','" . $t_image . "')";
$success = $conn->query($query);
if (!$success) {
die("Couldn't enter data: ".$conn->error);
} else {
$conn->close();
}
}
?>

Http Get and PHP

On my website, I'm using ajax to send data to an external php script, which queries a database and returns the result to the website. I ran into the problem, that I can only return strings with php, but I want to return an array of objects (which is valid json). My code looks like this at the moment:
php
$connection = mysqli_connect($adrs, $usr, $pw, $db);
if(mysqli_connect_errno()) {
die(mysqli_connect_error());
}
if($_GET["feed"] == "hausaufgaben") {
$query = "SELECT fach, aufgabe, datum FROM hausaufgaben WHERE fachgruppe != '";
if($_GET["fremdsprache"] == "latein") {
$query .= "französisch";
}
else {
$query .= "latein";
}
$query .= "' AND fachgruppe != '";
if($_GET["englisch"] == "koch") {
$query .= "schopper";
}
else {
$query .= "koch";
}
$query .= "' AND datum > '" . date("Y-m-d") . "' ORDER BY datum ASC;";
$result = mysqli_query($connection, $query);
$data = [];
while($row = mysqli_fetch_row($result)) {
$object = '{"fach": "' . $row[0] . '", "datum": "' . $row[2] . '", "aufgabe": "' . $row[1] . '"}';
array_push($data, json_decode($object));
}
echo $data;
}
ajax
$.ajax({
type: "GET",
url: "php/getFeed.php",
cache: false,
dataType: "json",
data: {feed: "hausaufgaben", fremdsprache: this.fremdsprache, englisch: this.englisch}
})
.done(function(data, textStatus, jqXHR) {
alert(typeof(data));
this.hausaufgaben = data;
})
.fail(function(jqXHR, textStatus, error) {
alert("error: " + error);
});
It always throws the error "Unexpected token A". I got it to return each single line in the array as string, but I can't use a string in my website. My problem is, that I can't echo an array of objects with php and get the array with ajax.
Instead of trying to build a json string yourself you can do it all much easier by building the $data array using PHP data structures and then using json_encode() to convert it all to a JSON string for sending to your javascript.
Reference json_encode and json_decode
Like this :-
$data = [];
while($row = mysqli_fetch_object($result)) {
$data[] = $row;
}
echo json_encode($data);
You will also have to change you javascript to process an array of objects rather than a string, but that should be easy

Passing variables between jQuery and PHP on Post

I have an $.ajax function that posts to a php page and gets some results.
function GetLicenseCount(SoftwareNameFK, SoftwareTypeFK,LicenseMethodFK,MinistryFK )
{
$.ajax({
type: "GET",
url: "modules/SoftwareLicenseAllocations/GetLicenseCount.php",
data: {SoftwareName : SoftwareNameFK, SoftwareType: SoftwareTypeFK, LicenseMethod: LicenseMethodFK, Ministry: MinistryFK},
dataType: "json",
success: function(result) {
var LicenseCount = document.getElementById("txtLicenseCount");
var idHidden = document.getElementById("txtId");
//get id value from string, by using split and getting the first part before the delimeter
var id = result.split(",")[0];
//get second part of result using string
LicenseCount.value = result.split(",")[1];
idHidden.value = id;
},
error: function(reason) {
console.log(reason);
alert("Failed to get License Count");
}
});
}
GetLicenseCount.php
<?php
//Local include path format
set_include_path('C:\PROJECTS\BRIAN\AMS\Web Application;C:\PROJECTS\BRIAN\AMS\Web Application\inc\pear;C:\PROJECTS\BRIAN\AMS\Web Application\js;');
//Search Screen
require_once('vars.php');
require_once('funcs.php');
//read the parameter passed through URL
$SoftwareName = $_GET['SoftwareName'];
$SoftwareType = $_GET['SoftwareType'];
$LicenseMethod = $_GET['LicenseMethod'];
$Ministry = $_GET['Ministry'];
//formulate query - get all active departments
$queryString = "SELECT DISTINCT id, LicenseCount"
. " FROM SoftwareLicenseAllocations WHERE"
. " SoftwareTypeFK =" . $SoftwareType
. " AND SoftwareNameFK = " . $SoftwareName
. " AND LicenseMethodFK=" . $LicenseMethod
. " AND MinistryFK=" . $Ministry;
// $queryString = "SELECT DISTINCT LicenseCount"
// . " FROM SoftwareLicenseAllocations WHERE"
// . " SoftwareTypeFK =" . 2
// . " AND SoftwareNameFK = " . 2
// . " AND LicenseMethodFK=" . 2
// . " AND MinistryFK=" . 1 ;
$sla = GetOpenItDataSet($queryString);
//loop on result set to refresh the department options list
while ($row = mysql_fetch_array($sla))
{
$LicenseCount = $row["LicenseCount"];
$id = $row['id'];
}//endWhile
$_SESSION['id'] = 22;
//echo $departmentArray;
echo json_encode($id . "," . $LicenseCount);
//$_POST["lcID"] = $id;
I am trying to get one of the values passed on in the original page.
i tried using $_Session on GetLicenseCount.php but the variable remains null.
Is is possible to pass a variable from jQuery to PHP? If so, how?
EDIT:
The problem is that GetLicenseCount is supposed to pass id, which it is doing, but I cannot use it in the original page via PHP, only via jQuery. When I come to use the $_SESSION['id'] through the original/previous php page it remains null.. The jQuery block is contained in another php page.

Change variable in external php file using ajax

i've encountered a problem changing php variable that is respobsible for showing content
here's my JS code:
$(document).ready(function(){
var ajax = 1;
var button;
$('.tagbtn').click(function(){
button = $(this);
$(this).siblings("ul").slideToggle('slow', function(){
$('.selection').click(function(){
var number = $(this).children('h1').html();
button.html(number);
$(this).parent('ul').slideUp('slow');
var data = 'number=' + number;
$.ajax({
type:'POST',
//url: 'ajax-realizacje.html',
url: 'aktualnosci.class.php',
async: true,
data: data,
success: function(){
limit_page = number;
}
});
});
});
});
});
limit_page is the variable from the external file, which i am trying to change
and here's my php function that loads the content:
function LoadArticles($pages = 0, $page = 0) {
$start = ($pages - $page) * $this->limit_page;
$q = "SELECT p.*, d.title, d.title_url, d.content, d.content_short, d.tagi FROM " . $this->table . " p ";
$q .= "LEFT JOIN " . $this->tableDescription . " d ON p.id=d.parent_id ";
$q .= "WHERE d.language_id=? AND p.active=1 AND d.active=1 ";
$q .= "ORDER BY p.date_add DESC, p.id DESC ";
$q .= "LIMIT ?,? ";
$params = array(
array(dbStatement::INTEGER, _ID),
array(dbStatement::INTEGER, $start),
array(dbStatement::INTEGER, $this->limit_page)
);
$statement = $this->db->query($q, $params);
$articles = array();
while ($row = $statement->fetch_assoc()) {
$row['content'] = strip_tags($row['content']);
$row['url'] = BASE_URL . '/' . $this->modul . '/' . $row['title_url'] . '.html';
$row['photo'] = $this->getPhotoUrl($row['photo']);
$row['date_add_org'] = $row['date_add'];
if (!empty($row['tagi'])) {
$row['tagi_url'] = explode('|', str_replace(' ', '-', $row['tagi']));
$row['tagi'] = explode('|', $row['tagi']);
}
$row['date_add'] = date("j", strtotime($row['date_add_org'])) . " " . miesiac2(date("n", strtotime($row['date_add_org']))) . " " . date("Y", strtotime($row['date_add_org'])) . "r";
$articles[] = $row;
}
return $articles;
}
the problem is that ajax doesn't seem to change that php variable
would appreciate your help
if it's just a text on a file you can read it by using:
$this->limit_page = file_get_contents('path/to/file');

Jquery security regarding mysql injection

I know its probably unconventional but I want to know if the below code is secure or not.
First piece of code is htee jquery object creation plus the call to the retrieve_data function:
var dataset = [
{
query_column: "articles.id,articles.category_id,articles.text,articles.slug article_slug,site_categories.title,site_categories.slug site_categories_slug",
table_name: 'articles',
query_join: 'LEFT JOIN site_categories ON site_categories.Id = ' + category,
query_filter: ['articles.category_id LIKE ', '%' + category + '%'],
query_limit: 'LIMIT ' + limit,
unique_column_switch: '1'
}
];
retrieve_data(dataset, function (data) {
Next is the retrieve_data function itself:
function retrieve_data(dataset, callback) {
$.ajax(
{
type: "POST",
url: "<?php echo ROOT_URL; ?>php/content/retrieve_data.php",
data: {json: JSON.stringify(dataset)},
success: function (data) {
var data = $.parseJSON(data);
callback(data);
}
});
}
Finally the php that retrieves the data and prints it out for the return to jquery:
mb_internal_encoding("UTF-8");
session_start();
include '../../config.php';
include ROOT_DIR . "php/dbconnection/dbconnection.php";
include ROOT_DIR . 'php/authentication/encryption.php';
$encrypt_decrypt = new encryption();
$json = json_decode($_POST['json']);
$array = array();
/*
* THIS IS TO BUILD A STRING OF DIFFERENT QUERIES TO BE PERFORMED UPON UPDATE BEING PRESSED
* PARAMS:
* data_value:::::::::::: THE VALUE USED TO FIND THE ROW
* table_name:::::::::::: TABLE NAME
* unique_column::::::::: UNIQUE DATA ELEMENT THAT LINKS ALL THE TABLES TOGETHER
* query_end::::::::::::: END OF QUERY (EXTRA WHERE CLAUSES, ORDER BY, LIMIT, ETC)
* query_column:::::::::: COLUMNS THAT ARE GOING TO BE CALLED, DEFAULTS TO * IF USING JOINS THEN THIS MUST BE SPECIFIED I.E. TABLE1.*, TABLE2.*, ETC
* query_join:::::::::::: SET ANY JOINS HERE
* unique_column_switch:: IF SET TO 1 DISABLES USE OF A UNIQUE COLUMN AND USES QUERY END EXCLUSIVELY
*/
foreach($json as $item){
$table_name = $mysqli->real_escape_string($item->table_name);
$unique_column = $mysqli->real_escape_string($item->unique_column);
$data_value = $mysqli->real_escape_string($item->data_value);
$query_column = $mysqli->real_escape_string($item->query_column);
$query_join = $mysqli->real_escape_string($item->query_join);
$query_filter = $item->query_filter;
$query_order = $mysqli->real_escape_string($item->query_order);
$query_limit = $mysqli->real_escape_string($item->query_limit);
$unique_column_switch = $mysqli->real_escape_string($item->unique_column_switch);
$query_filter_safe = array();
foreach($query_filter as $key1 => $val1){
array_push($query_filter_safe, ($key1 % 2) ? "'" . $mysqli->real_escape_string($val1) . "'" : $mysqli->real_escape_string($val1));
}
if(empty($unique_column) && $unique_column_switch != '1'){
$query1 = $mysqli->query("SHOW KEYS FROM `$table_name` WHERE Key_name = 'PRIMARY'");
$fetch1 = $query1->fetch_array(MYSQLI_ASSOC);
$unique_set = $fetch1['Column_name'] . " = '" . $data_value . "'";
$unique_column = $fetch1['Column_name'];
} else{
$unique_set = ($unique_column_switch != '1') ? "`" . $table_name . "`.`" . $unique_column . "` = '" . $data_value . "'" : '';
}
$unique_column = (empty($unique_column)) ? '' : $unique_column;
$where = (empty($unique_set) && empty($query_filter)) ? '' : 'WHERE';
$select_items = (empty($query_column)) ? '*' : $query_column;
$query2 = "SELECT " . $select_items . " FROM " . $table_name . " " . $query_join . " " . $where . " " . $unique_set . " " . join(' ', $query_filter_safe) . " " . $query_order . " " . $query_limit;
//echo $query2;
$query2 = $mysqli->query($query2);
for($x = 0; $fetch2 = $query2->fetch_array(MYSQLI_ASSOC); $x++){
$fetch2 = $encrypt_decrypt->decrypt_val($fetch2, $table_name, $mysqli);
foreach($fetch2 as $column => $value){
($unique_column == $column) ? $array[$table_name][$x]['INDEX_VALUE'] = $value : $array[$table_name][$x][$column] = $value;
}
}
}
echo json_encode($array);
EDIT 12/5 12:00PM EST
I have rewritten what I was trying to do. Thanks again for pointers everyone! #MonkeyZeus and #Carth were extremely useful.
include '../../config.php';
include ROOT_DIR . "php/dbconnection/dbconnection_pdo.php";
$query = "SELECT * FROM site_users WHERE username = :username";
$query = $pdo->prepare($query);
$query->execute(array('username' => $_POST['username']));
$result = $query->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($result);
Going back to jquery:
function article_box_basic(category, limit, max_char_count, location) {
$.ajax(
{
type: "POST",
url: "<?php echo ROOT_URL; ?>php/content/article_box_basic.php",
data: {username: 'moltmans'},
success: function (data) {
var data = $.parseJSON(data);
Do something here with data
This is emphatically not a "secure" approach. Validation and control on the client side should be treated as an inherently insecure convenience for generating a request not a means of enforcing true security. Your server side code should be validating the request parameters within the context of who your user is and what they're doing. Since a user can set "dataset" to whatever they want it doesn't matter if the category variable is itself prone to injection based on its usage in the rest of the statement.
By exposing your schema on the client side like this you're revealing valuable information that there's no need to expose.

Categories