Passing variables between jQuery and PHP on Post - php

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.

Related

how to insert multiple rows inside database using PHP MySQL ajax using better technique for faster insert

here i'am trying to insert multiple rows at same time in my case more than 200-250 rows at same time but i got below error
Unknown: Input variables exceeded 1000. To increase the limit change max_input_vars in php.ini
but when i increased the max_input_vars = 3000 this solved problem was now iam able to insert but it is taking too much time.
i want to insert faster but need help
this is my php code
<?php
include "connection.php";
if (isset($_POST['close_val'])) {
$item_cid = $_POST["item_cid"];
$item_id = $_POST["item_id"];
$op_date = $_POST["op_date"];
$op_value = $_POST["op_value"];
$close_date = $_POST["close_date"];
$close_val = $_POST["close_val"];
// Converting the array to comma separated string
for ($count = 0; $count < count($item_id); $count++) {
$item_cid_clean = mysqli_real_escape_string($conn, $item_cid[$count]);
$item_id_clean = mysqli_real_escape_string($conn, $item_id[$count]);
$op_date_clean = mysqli_real_escape_string($conn, $op_date[$count]);
$op_value_clean = mysqli_real_escape_string($conn, $op_value[$count]);
$close_date_clean = mysqli_real_escape_string($conn, $close_date[$count]);
$close_val_clean = mysqli_real_escape_string($conn, $close_val[$count]);
$sql = "SELECT COUNT(*) AS cntuser from bar_opening_details WHERE `item_id` = '" . $item_id_clean . "' AND close_date='" . $close_date_clean . "' AND item_cid='" . $item_cid_clean . "' ";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_array($result);
$count1 = $row['cntuser'];
if ($count1 > 0) {
// update
$updatequery = "UPDATE bar_opening_details SET
`item_cid` = '" . $item_cid_clean . "',
`item_id` = '" . $item_id_clean . "',
`op_date` = '" . $op_date_clean . "',
`op_value` = '" . $op_value_clean . "',
`close_date` = '" . $close_date_clean . "',
`close_val` = '" . $close_val_clean . "'
WHERE close_date='" . $close_date_clean . "' and `item_id` = '" . $item_id_clean . "' ";
mysqli_query($conn, $updatequery);
} else {
$insertquery = "INSERT INTO bar_opening_details
(item_cid,
item_id,
op_date,
op_value,
close_date,
close_val) values ('" . $item_cid_clean . "', '" . $item_id_clean . "', '" . $op_date_clean . "', '" . $op_value_clean . "', '" . $close_date_clean . "', '" . $close_val_clean . "')";
mysqli_query($conn, $insertquery);
}
}
// insert
$return_arr = array('item_cid' => $item_cid, 'item_id' => $item_id, 'op_date' => $op_date, "close_val" => $count);
echo json_encode($return_arr);
mysqli_close($conn);
}
here is my ajax code. using this iam able to sent request to insert but it is takin to much time
<script>
$(document).ready(function() {
// submit button click
$("#submit").click(function() {
$('#loading').show();
var item_cid = [];
var item_id = [];
var op_date = [];
var op_value = [];
var close_date = [];
var close_val = [];
var Toast = Swal.mixin({
toast: true,
position: 'top-end',
showConfirmButton: false,
timer: 3000
});
// Initializing array with Checkbox checked values
$("input[name='item_cid[]']").each(function() {
item_cid.push(this.value);
});
$("input[name='item_id[]']").each(function() {
item_id.push(this.value);
});
$("input[name='op_date[]']").each(function() {
op_date.push(this.value);
});
$("input[name='op_value[]']").each(function() {
op_value.push(this.value);
});
$("input[name='close_date[]']").each(function() {
close_date.push(this.value);
});
$("input[name='close_val[]']").each(function() {
close_val.push(this.value);
});
$.ajax({
url: 'lib/cbentry.php',
type: 'post',
data: {
item_cid: item_cid,
item_id: item_id,
op_date: op_date,
op_value: op_value,
close_date: close_date,
close_val: close_val
dataType: 'JSON',
success: function(response) {
$('.details').show();
// selecting values from response Object
var name = response.close_val;
$('#loading').hide();
// var email = response.email;
// var lang = response.lang;
// var foundjquery = response.foundjquery;
Toast.fire({
icon: 'success',
title: 'Data Entered Successfully'
})
// setting values
$('#name').text(name);
// $('#email').text(email);
// $('#lang').text(lang);
// $('#foundjquery').text(foundjquery);
}
});
});
});
</script>
JSON
A simple 2-line fix to allow for unlimited items: Suggest you encode the array into JSON for POSTing, then use json_decode() to turn it back into an array when it arrives in PHP.
But, I have to ask... Are there really hundreds of new (or changed) rows? If only a few rows, consider shipping one row at a time via AJAX to PHP -- perhaps based on whether a value has changed after the mouse leaves "focus". A lot of little AJAX calls would have a lot of overhead (launching many PHP threads), but the task would be finished by the time you leave the web page. It would "feel" as if every thing was "instantaneous". (OK, if you have a thousand users doing this same thing at the same time, this technique could overload the server.)
Arrays
Here's another approach: Use "arrays". If the input names end in []:
<input type=text name=x[] ">
the will come in as an array in $x. If you have multiple of these, then the subscripts (0, 1, ...) will let you match them up.
$list = GetArray('list');
function GetArray($fn) {
// Input an array of things from
// echo "<input type=checkbox name=\"fn[]\" value=\"$out_fn\" $checked>\n";
// url has &fn[]=aaa&fn[]=ccc
$req = #$_REQUEST[$fn]; // Note: this must NOT end in []
$fns = empty($req) ? [] :
(is_array($req) ? $req :
explode(',', $req));
return $fns; // always an array
}
($_REQUEST includes $_POST; change it if you would prefer)
INSERT
As for the speed of a MySQL insert... A single INSERT with 100 rows will run 10 times as fast 100 1-line INSERTs. So, if there are really hundreds of new rows, I recommend "batching" the inserts.
If most of the rows are already in the table, then INSERT IGNORE is a 'simple' way to deal with that. But... If there is an AUTO_INCREMENT id on the table, the dups will "burn" ids.
IODKU is the optimal way to deal with rows that are either new or modified. It, too, can be batched. But, it also burns ids if the query is not including the original id where available.
(I can elaborate, you you elaborate.)

Ajax Autocomplete TextBox from PostgreSQL Not getting Data

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.

Updating database field in PHP when link is pressed

My page lists out all of the rows from a MySQL table and puts them inside separate divs as links.
while($row = mysqli_fetch_array($result))
{
echo "<a href='projects/" . $row['dir'] . "'><div>";
echo "<h2>" . $row['name'] . "</h2>";
echo "<p>Created: " . $row['date_created'] . "</p>";
echo "<p>Last opened: " . $row['date_last_opened'] . "</p>";
echo "<p>" . $row['description'] . "</p>";
echo "</div></a>";
}
When I click on a box (div), it opens that specific project. What I need, is to update the 'date_last_opened' field for a project to the current date when I click into one. The column for it in the table is of type 'date'.
Thanks to anyone that can help.
Simple method would be use of Jquery and AJAX:
First add click function to your link in while loop like this:
echo "<a href='projects/" . $row['dir'] . "' onclick='update(".$row['name'].")';><div>";
and in your JS file use Jquery Ajax:
function update(name){
var now = new Date();
var dateToInsert = now.format("dd/M/yy h:mm tt");//or whatever format you need
var projectName = name;
$.ajax({
type: "POST",
url: "update.php",
data: { date: dateToInsert, name: projectName}
})
.done(function( msg ) {
alert( "Data Saved: " + msg );
});
}
and your update.php:
if(isset($_POST['date']) && $_POST['name']){
$sql = "update yourTable set date ='".$_POST['date']."' where name= '".$_POST['name']."'";
//Rest of the code to execute query
}
else{
echo "AJAX call failed to send post variables";
}

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.

Update a Select Box on Parent Page from FancyBox2

I'm trying to submit a form in a fancybox where users can add a company to a select box that exists on the modals parent page. Im doing this by submitting the modal information to a script that adds the company to my database. Then I run a query to to get all the updated companies as a group of tags. Then I am trying to pass that group of tags to the parent page as a jquery update. Im not sure if this is the best approach or where I'm going wrong.
I am attempting to use this post as a guide:
Find element on site from a fancybox iframe
But I have two problems with my code.
One: The fancybox is not closing
Two: The select box on the parent page is not updating
I am not sure where I am going wrong with my success call. The code from the Modal page is:
$("#send-message").click(function(){
$(this).closest('form').submit(function(){
return false;
});
var frm = $(this).closest('form');
if($(frm).valid()){
$("#ajax-loading").show();
var data = $(frm).serialize();
$(frm).find('textarea,select,input').attr('disabled', 'disabled');
$.post(
"../forms/company_add.php",
data,
function(data) {
if (data.success) {
// data.redirect contains the string URL to redirect to
$('#companyselect', $(parent.document)).html(data.success);
parent.$.fancybox.close();
}
else {
$("#ajax-loading").hide();
$(frm).find('textarea,select,input').removeAttr('disabled');
$("#send_message_frm").append(data.error);
}
},
"json"
);
}
});
The Code from company_add.php returns all the options tags like such:
if ($_POST) {
// Collect POST data from form
$name = filter($_POST['name']);
$conmail = filter($_POST['conmail']);
$addy = filter($_POST['addy']);
$confax = filter($_POST['confax']);
$city = filter($_POST['city']);
$state = filter($_POST['state']);
$con = filter($_POST['con']);
$conphone = filter($_POST['phone']);
$zip = filter($_POST['zip']);
}
$search1 = mysql_query("SELECT man_name FROM manufacturers WHERE man_name = '$name'");
$outcome1 = mysql_fetch_row($search1);
$num_rows1 = mysql_num_rows($search1);
$imageid1 = $outcome1[0];
$imageid1 = filter($imageid1);
if ($num_rows1 > 0) {
echo json_encode(array(
"error" => '<div class="msg-error">A company by that name already exists.</div>'
));
} else {
$stmnt = mysql_query("INSERT INTO manufacturers (manufacturer_id, man_name, man_address, man_city, man_state,man_zip, man_contact, man_phone, man_fax, man_mail) VALUES ('NULL', '" . $name . "', '" . $addy . "' ,'" . $city . "', '" . $state . "' , '" . $zip . "' , '" . $con . "' , '" . $conphone . "' , '" . $confax . "', '" . $conmail . "' )");
//echo "Duplicate WAS found:" . $answer1;
mysql_query($answer1);
//}
$resp['status'] = 'success';
if (empty($error)) {
$nada = "SELECT man_name FROM manufacturers ORDER BY man_name ASC";
$resulter = mysql_query($nada);
$comp1 = '0';
//Spit out array of companys as select boxes
$select = '<option value="">--Select one--</option>';
while ($result59 = mysql_fetch_array($resulter))
$select .= '<option value="' . $result59['man_name'] . '">' . $result59['man_name'] . '</option>';
echo json_encode(array(
"success" =>$select
));
} else {
echo json_encode(array(
"error" => '<div class="msg-error">Error: Unable to add your company at this time</div>'
));
}
}
I am new to programming and very new to Jquery so I'm hoping someone can see where I'm going wrong. I am using fancybox 2 and php.
Have you checked error console for any JavaScript errors?
You can try this anyway:
parent.$('#companyselect').html(data.success);

Categories