Http Get and PHP - 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

Related

ajax success doesnt alert anything

I have an AJAX request and if get id succeeds I would like to alert the data.
If I print_r my PHP function I get the correct result.
My ajax:
$.ajax({
type: "GET",
url: "getQuestions.php",
datatype: "json",
data:{
compid: id[4].innerHTML
},
success: function(response){
alert(response);
}
});
My getQuestions.php:
<?php
include "functions.php";
getQuestions($_GET['compid']);
My function getQuestions($compid) in functions.php:
function getQuestions($compid){
$int=intval($compid);
$vastus=array();
$conn = dbconnect();
$sql="SELECT * FROM bet_question WHERE compid = $int";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
array_push($vastus,$row);
}
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
return json_encode($vastus);
}
If I do print_r(getQuestions("some valid id")) in getQuestion.php I get valid result and if I do var_dump($_GET['compid']) in getQuestion I'll get the correct id from ajax request.
If I check if the request is sent using inspect elements I get that request is sent with correct params, but the response is empty.
Instead of return you need to use echo and it should be updated as
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
array_push($vastus,$row);
}
echo json_encode($vastus);
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
exit;
You don't have to return the data, use echo instead, and set content type:
function getQuestions( $compid ) {
$int=intval($compid);
$vastus=array();
$conn = dbconnect();
$sql="SELECT * FROM bet_question WHERE compid = $int";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
array_push($vastus,$row);
}
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
#header( 'Content-Type: application/json' );
echo json_encode( $vastus );
exit;
}
Hope it helps

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.

Fetch php response using angularjs

I'm using angularjs for my app and php to fetch data from server...
The php file gets all the needed variables but when i'm trying to see the answer using angular I only get [object Object], [object Object] and so on...
Any ideas?
Thanks!
Angular code:
app.controller('FormController', ['$scope', '$http', function($scope, $http){
$scope.submit = function() {
var data = {
'days': $scope.days,
'age_18': $scope.age_18,
'age_13_17': $scope.age_13_17,
'age_8_12': $scope.age_8_12,
'age_3_7': $scope.age_3_7,
'water': true,
'outside': true
}
$http.post('php/get_data.php', data)
.success(function(data, status, headers, config) {
alert(data);
})
}
}])
Php Code:
<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
$conn = new mysqli("localhost", "nathan", "nathan", "nathan");
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
$age_18 = $request->age_18;
$age_13_17 = $request->age_13_17;
$age_8_12 = $request->age_8_12;
$age_3_7 = $request->age_3_7;
$days = $request->days;
$water = $request->water;
$outside = $request->outside;
$result = $conn->query("SELECT id, modal_name, name,('$age_18'*18_rating + '$age_13_17'*13_17_rating
+ '$age_8_12'*8_12_rating + '$age_3_7'*3_7_rating) as total
FROM parks
WHERE (water_park LIKE '$water' OR water_park LIKE 0)
and (outside_orlando LIKE '$outside' OR outside_orlando LIKE 0)
ORDER BY total DESC");
$outp = "[";
while($rs = $result->fetch_array(MYSQLI_ASSOC)) {
if ($outp != "[") {$outp .= ",";}
$outp .= '{"name":"' . $rs["name"] . '",';
$outp .= '"modal_name":"' . $rs["modal_name"] . '",';
$outp .= '"id":"' . $rs["id"] . '"}';
}
$outp .="]";
$conn->close();
echo($outp);
?>
The output you get is an array of objects.
Try the following :
$http.post('php/get_data.php', data)
.success(function(data, status, headers, config) {
for (var j = 0; j < data.length; j++) {
alert(data[j].name);
}
})
Please check this and tell me if it is working for you:
$http.post('php/get_data.php', JSON.stringify(data))
.success(function(data, status, headers, config) {
alert(data);
})

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.

ajax success function not returning json decoded data

I have searched stackoverflow for similar questions but nothing helped. This is my ajax call to adding.php file. I called this on jquery keyup event. When I inspect in browser I see php file returning response. However, the data in response never reaches success function of ajax.
$.ajax({
url: "anding.php",
type: "POST",
dataType: 'json',
data: JSON.stringify({mycol:mycol,mycolval:mycolval,string:string}),
contentType: 'application/json',
success: function(data){
alert(data);
var output = data.substring(0, data.indexOf('arventures'));
last = data.substring(data.indexOf('arventures') + 10);
last--;
$('.remove').remove();
$('.main_tr').after(output);
if (output == '' || output == null) {
$('.message').html('No results found.');
}
else {
$('#row1').addClass('highlight');
}//highlight row1 by default
}
});
This is my php file which returns the response. I have pasted the entire code because I dont know which part is causing the issue.
adding.php
<?php
include 'connection.php';
$postdata = json_decode(file_get_contents("php://input"), true);
//var_dump($postdata);exit;
//var_dump($postdata);
$query = "SELECT COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_name = '".$table_name."'
AND table_schema = '".$mysql_database."'";
$result = mysqli_query($con,$query);
$results = array();
while ($line = mysqli_fetch_assoc($result)) {
$results[] = $line;
}
$query = null;
foreach ($results as $r) {//search in order.1st search in column 1 then column 2...so on
$append = " SELECT * from " . $table_name . " WHERE " . $r['COLUMN_NAME'] . " like '" . $postdata['string'] . "%'";
$query = $query . $append;
for($i=1;$i<=(count($postdata['mycol']))-1;$i++)
{
$append1=" AND " .$postdata['mycol'][$i]. " like '" . $postdata['mycolval'][$i] . "%'";
$query = $query . $append1;
}
$query=$query." UNION";
}
$query = substr($query, 0, -6);
$result2 = mysqli_query($con, $query);
$pos = strrpos($postdata['string'], '%');
$str_count = substr_count($postdata['string'], '%');
$results2 = array();
$results3 =array();
while ($line = mysqli_fetch_assoc($result2)) {
if (strpos($postdata['string'], '%') !== false || strpos($postdata['string'], '_') !== false) {// highlight in star search
$str = preg_replace('/[^a-zA-Z0-9-]/', '', $postdata['string']);
$line = preg_replace("|^($str)|Ui", "<span class='highlights'>$1</span>", $line);
} else {
$string=$postdata['string'];
$line = preg_replace("|^($string)|Ui", "<span class='highlights'>$1</span>", $line); //highlight in normal search
}
$results2[] = $line;
}
$result2 -> data_seek(0);
while ($line1 = mysqli_fetch_assoc($result2)) {
$results3[] = $line1;
}
for ($i=1;$i<=count($results2);$i++) {
echo "<tr id='row".$i."' class='remove table_row'>";
$j=0;
foreach($results as $r1){
if($j==0){
echo "<td class='index_field' dB_id='".$results3[$i-1][$r1['COLUMN_NAME']]."'>".$results2[$i-1][$r1['COLUMN_NAME']]."</td>";
} else {
echo "<td>".$results2[$i-1][$r1['COLUMN_NAME']]."</td>";
}
$j++;
}
echo "</tr>";
}
echo 'arventures' . $i;
mysqli_close($con);
Your ajax call never reaches the success function because you have specified dataType as JSON. Either remove dataType or return JSON instead of normal HTML.

Categories