Change variable in external php file using ajax - php

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');

Related

making php on-input search but jquery $.ajax and $.post not working

i am trying to make a live search box using ajax using the following code but its not working. When i echo "hello"; from the php file and remove everything else it just echos it out on the screen and does not work, no errors or return values, leading me to believe it has to do with my jquery code but i am not sure.
jquery:
$("#search").keyup(function(){
var value = $("#search").val();
$.post(walldb.php, {value: value}, function(data){
console.log(data);
})
});
heres the php:
<?php
$arr = [];
$searchq = "%{$_POST['value']}%";
$stmt = $pdo->prepare("SELECT * FROM walldb WHERE wallname LIKE :s");
$stmt->bindParam(':s',$searchq);
$result=$stmt->execute();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$mlink = $row['mainlink'];
$tlink = $row['thumbnail'];
$dlink = $row['download'];
$info = $row['info'];
$val = $row['wallname'];
$arr[] = '<li>' . "" . "<span>" . "$val" . "</span><img class='searchbutton1 s1' src='/images/info.png'>" . '<br>' . "<a id='wall1.download' href=" . "$dlink" . "><img class='searchbutton2' src='/images/download.png'></a>" . '<br>' . "<ul class='searchmenu menu1'><p>" . "$info" . "</p>
</ul>" . '</li>';
}
$final = '<ul>' . implode('', $arr) . '</ul>';
echo $final; //just echos everything on the screen :(
?>
html:
<form action= "" method= "post">
<img id="glass" src="/images/search.png" type= "submit" name="submit-search"><input id="search" name="search-input" type="search" placeholder="Search By Name" autocomplete="off"><img id="cancle" src="/images/cancle.png">
</form>
i would also appreciate some help on making the whole thing work making it search on input since i am very new to pdo/php.
i fixed this issue by using generic javascript XMLHttpRequest, jquery never worked for me and i have no idea why. I would love to receive some insight as to why my below solution works and the jquery version does not (i am using the latest version of jquery).
javascript:
$("#search").keyup(function () {
var http = new XMLHttpRequest();
var value = $("#search").val();
http.open("POST", 'walldb.php', true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.onload = function () {
if (this.status == 200) {
$("#result").html(this.responseText);
}
}
http.send("value=" + value);
});
php:
<?php
$arr = [];
$searchq = "%{$_POST['value']}%";
$stmt = $pdo->prepare("SELECT * FROM walldb WHERE wallname LIKE :searchq");
$stmt->bindParam(':searchq',$searchq);
$result=$stmt->execute();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$mlink = $row['mainlink'];
$tlink = $row['thumbnail'];
$dlink = $row['download'];
$info = $row['info'];
$val = $row['wallname'];
$arr[] = '<li>' . "" . "<span>" . "$val" . "</span><img class='searchbutton1 s1' src='/images/info.png'>" . '<br>' . "<a id='wall1.download' href=" . "$dlink" . "><img class='searchbutton2' src='/images/download.png'></a>" . '<br>' . "<ul class='searchmenu menu1'><p>" . "$info" . "</p>
</ul>" . '</li>';
}
$final = '<ul>' . implode('', $arr) . '</ul>';
if (isset($_POST['value'])) { //added this
echo $final;
}
?>
Try to correct that:
$stmt = $pdo->prepare('SELECT * FROM walldb WHERE wallname LIKE ?');
$stmt->execute([$searchq]);
to
$searchq = '%' .$_POST['value']. '%'; //edited
$stmt = $pdo->prepare('SELECT * FROM walldb WHERE wallname LIKE ?');
$stmt->bind_param('s', $searchq);
$stmt->execute();
while($row= $stmt->fetch_assoc()){
Or PDO
$searchq = '%' .$_POST['value']. '%'; //edited
$stmt= $pdo->prepare('SELECT * FROM walldb WHERE wallname LIKE :searchq');
$stmt->bindParam(':searchq', $searchq, PDO::PARAM_STR);
$stmt->execute();
while($row= $stmt->fetch_assoc()){

Select2 return "({"ok": 1, "total": 7, "rows": })" and display loading failed

When I'm using select2 with my database on localhost. It works correctly.
But when I'm using with database on server, eg 10.0.0.1 it doesn't work.
Here's my select2 script :
$('#slDrug').select2({
placeholder: 'ค้นหาเวชภัณฑ์',
minimumInputLength: 1,
allowClear: true,
language: "th",
ajax: {
url: 'ajax/drugSearch.php',
dataType: 'JSON',
type: 'GET',
quietMillis: 100,
data: function (term, page) {
return {
query: term,
start: page,
stop: 20
};
}, results: function (data, page) {
var more = (page * 10) < data.total;
return { results: data.rows, more: more };
}
}, id: function(data) {
return { id: data.code }
}, formatResult: function(data) {
return '[ ' + data.code + ' ] ' + data.name + ' ความแรง : ' + data.strength + ' หน่วยนับ : ' + data.units;
}, formatSelection: function(data) {
return data.code + ' ' + data.name + ' ' + data.strength;
}
});
And here's my php code :
<?php
require_once('../require/medoo.min.php');
// Select connectinfo from database
$localDB = new medoo();
$getHosInfo = $localDB->select("sys_config","*");
foreach($getHosInfo as $g){
$host = $g['host'];
$user = $g['user'];
$pass = $g['password'];
$dbname = $g['dbname'];
}
header('Content-type: text/html; charset=utf-8');
$dsn = 'mysql:host='.$host.'; dbname='.$dbname.'; charset=utf8';
try {
$conn = new PDO( $dsn, $user, $pass);
$conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
} catch ( PDOException $e ) {
echo 'Connection failed: ' . $e->getMessage();
}
$query = $_GET['query'];
$callback = $_GET['callback'];
$start = $_GET['start'];
$stop = $_GET['stop'];
$start = empty($start) ? 1 : $start;
$stop = empty($stop) ? 10 : $stop;
$start = ($start - 1) * $stop;
$sql_total = 'select count(*) as total from drugitems where name like "%' . $query . '%"';
$st = $conn->prepare($sql_total);
$st->execute();
$rows_total = $st->fetch();
$sql_rows = 'select icode, name, strength,units,unitcost,unitprice,did,antibiotic,fp_drug
from drugitems
where name like "%' . $query . '%" limit ' . $start . ', ' . $stop;
$st = $conn->prepare($sql_rows);
$st->execute();
$rows_result = $st->fetchAll();
$data = array();
foreach($rows_result as $r)
{
$obj = new stdClass();
$obj->code = $r['icode'];
$obj->name = $r['name'];
$obj->strength = $r['strength'];
$obj->did = $r['did'];
$obj->unitprice = $r['unitprice'];
$obj->unitcost = $r['unitcost'];
$obj->units = $r['units'];
$obj->antibiotic = $r['antibiotic'];
$obj->fp_drug = $r['fp_drug'];
$data[] = $obj;
}
$json = '{"ok": 1, "total": ' . $rows_total['total'] . ', "rows": ' . json_encode($data) . '}';
echo $callback . '(' . $json . ')';
?>

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.

Only displaying the last record of the array PHP

I have this Function:
function getLow() {
global $db_prefix, $min;
//get latest week with all entered scores
$lastCompletedWeek = getLastCompletedWeek();
$sql = "select u.userID, u.teamName ";
$sql .= "from " . $db_prefix . "users u ";
$query = mysql_query($sql);
while ($result = mysql_fetch_array($query)) {
for($i = 1; $i <= $lastCompletedWeek; $i++) {
$userScore = getLowScore($i, $result['userID']);
$win[][week] = $i;
$win[][user] = $result['userID'];
$win[][teamName] = $result['teamName'];
$win[][score] = $userScore;
}
$count = count($win);
$lowest = 0;
$min[score] = PHP_INT_MAX;
$min[user] = $result['userID'];
$min[teamName] = $result['teamName'];
for($i = 0; $i < $count; $i++) {
if($win[$i + 1]['user'] == $result['userID']) {
if($win[$i + 3]['score'] < $min[score]) {
$min[score] = $win[$i + 3]['score'];
$lowest = $i;
}
}
}
unset($win[$lowest]);
unset($win[$lowest + 1]);
unset($win[$lowest + 2]);
unset($win[$lowest + 3]);
$win = array_values($win);
//print_r ($min);
//echo $min[teamName] . ' ' . $min[score] . ' ';
}
}
when I call it from another .php file like this:
getLow($min);
I only get the last record....why?
Here is the getLowScores functio as well.
function getLowScore($week, $userID) {
global $db_prefix, $user;
$score = 0;
//get array of games
$games = array();
$sql = "select * from " . $db_prefix . "schedule where weekNum = " . $week . " order by gameTimeEastern, gameID";
$query = mysql_query($sql);
while ($result = mysql_fetch_array($query)) {
$games[$result['gameID']]['gameID'] = $result['gameID'];
$games[$result['gameID']]['homeID'] = $result['homeID'];
$games[$result['gameID']]['visitorID'] = $result['visitorID'];
$games[$result['gameID']]['tie'] = 1;
if (($result['homeScore'] + (($result['visitorSpread'] * -1))) > ($result['visitorScore'] + (($result['homeSpread'] * -1)))) {
$games[$result['gameID']]['winnerID'] = $result['homeID'];
}
if (($result['visitorScore'] + (($result['homeSpread'] * -1))) > ($result['homeScore'] + (($result['visitorSpread'] * -1)))) {
$games[$result['gameID']]['winnerID'] = $result['visitorID'];
}
if (($result['visitorScore'] + ($result['homeSpread'] * -1)) == ($result['homeScore'] + ($result['visitorSpread'] * -1))) {
$games[$result['gameID']]['winnerID'] = $result['tie'];
}
}
//loop through player picks & calculate score
$sql = "select p.userID, p.gameID, p.pickID, p.points, u.paid ";
$sql .= "from " . $db_prefix . "picks p ";
$sql .= "inner join " . $db_prefix . "users u on p.userID = u.userID ";
$sql .= "inner join " . $db_prefix . "schedule s on p.gameID = s.gameID ";
$sql .= "where s.weekNum = " . $week . " and u.userID = " . $userID . " ";
$sql .= "order by u.lastname, u.firstname, s.gameTimeEastern";
$query = mysql_query($sql);
while ($result = mysql_fetch_array($query)) {
if (!empty($games[$result['gameID']]['winnerID']) && $result['pickID'] == $games[$result['gameID']]['winnerID']) {
//player has picked the winning team
$score++;
}
if ($result['tie'] == $games[$result['gameID']]['winnerID']) {
//player has picked the winning team
$score++;
}
}
return $score;
}
Thanks in advance for helping!! This is driving me crazy?
Maybe not the answer, but this code is very broken:
$win[][week] = $i;
$win[][user] = $result['userID'];
$win[][teamName] = $result['teamName'];
$win[][score] = $userScore;
First, that adds four new rows to $win, a new one every time you use the [], which I very much doubt is your intent.
Second, those should be quoted, so it is ["week"], not [week]. Turn on PHP warnings and follow them.
I think you want:
$win[] = array(
"week" => $i,
"user" => $result['userID'],
"teamName" => $result['teamName'],
"score" => $userScore,
);
You can make warnings appear with:
error_reporting(E_ALL);
ini_set("display_errors",1);

Categories