How should I execute my php code using AJAX? - php

I've written the conditions down in JavaScript and if it's a down arrow then I want to update the database whereas currently it's not falling into the javascript condition and updating the database at server level. Any help will be appreciated.
Code:
<script language="javascript">
$(document).ready(function() {
totalgames=<?= $totalgames ?>;
//scoress = 0;
previous_s=0;
for(xx=totalgames; xx>=1; xx--){
score_ele = 'scores'+xx;
tdid_ele = 'tdid'+xx;
var tdd = document.getElementById(tdid_ele);
var scoress = document.getElementById(score_ele);
if(previous_s == 0){
tdd.innerHTML = "<img src='images/bullet.png'/>";
}else{
if(parseFloat(previous_s) > parseFloat(scoress.value)){
tdd.innerHTML = "<img src='images/arrow_up.png'/>";
}else if(parseFloat(previous_s) < parseFloat(scoress.value)){
tdd.innerHTML = "<img src='images/arrow_down.png'/>";
<?php
//Selecting from table teams
$sql_sel_amnt = "Select * from teams where t_name='".$t_name."'";
$result_sel = $db1->getResult($sql_sel_amnt);
$row_sel = mysql_fetch_assoc($result_sel);
//Selecting from table profitnloss
$sql_pnl = "Select * from profitnloss where t_name='".$t_name."' and username='".$abc."'";
$result_pnl = $db1->getResult($sql_pnl);
$row_pnl = mysql_fetch_assoc($result_pnl);
$transact_money = $row_pnl['pnl_amount'];
$pnl_results = $row_pnl['pnl'];
$profit = 0;
$loss = 0;
$transact_money = explode("|", $transact_money);
$pnl_results = explode("|", $pnl_results);
for($i=0; $i<count($transact_money); $i++){
if($pnl_results[$i]=='P'){
$profit = $profit + $transact_money[$i];
}else{
$loss = $loss + $transact_money[$i];
}//end if
}//end for..
$money_results_total = $profit - $loss;
$pnl_date = date("d-m-Y H:i:s");
$pnl_amount = $row_sel['c_amount'];//total amount lost
$t_amount = $money_results_total + $row_pnl['t_amount'] + $pnl_amount;
$noofplayers = mysql_num_rows($result_sel)-1;//total no of players
$company_share = 17;//charity percentage
$company_share_amnt = $company_share*$pnl_amount/100;
$pnl_amount_remaining = $pnl_amount - $company_share_amnt;
$charity = substr($row_sel['charity'], 0, 2);//charity percentage
$charity_amount = $charity*$pnl_amount_remaining/100;
$sharing_amount = $pnl_amount-$charity_amount-$company_share_amnt;
$pnl_profit = round($sharing_amount/$noofplayers, 2);
echo "noofplayers=> ".$noofplayers.", company_share=> ".$company_share.", company_share_amnt=> ".$company_share_amnt.", charity=> ".$charity."%, charity_amount=> ".$charity_amount.", sharing_amount=> ".$sharing_amount.", pnl_profit=> ".$pnl_profit;
$sql_updt_loss = "UPDATE profitnloss SET game_date = '".$serial_date."', pnl_date = CONCAT(pnl_date, '$pnl_date|'), pnl_amount = CONCAT(pnl_amount, '$pnl_amount|'), pnl = CONCAT(pnl, 'Loss|'), t_amount='".$t_amount."' where username='".$abc."' and t_name='".$t_name."'";
//echo $updt_pnl;
//$result_loss = $db1->getResult($sql_updt_loss);
$sql_updt_profit = "UPDATE profitnloss SET pnl_date = CONCAT(pnl_date, '$pnl_date|'), pnl_amount = CONCAT(pnl_amount, '$pnl_profit|'), pnl = CONCAT(pnl, 'Profit|') where username not like'".$abc."' and t_name='".$t_name."'";
//echo $updt_pnl;
//$result_profit = $db1->getResult($sql_updt_profit);
?>
}else if(parseFloat(previous_s) == parseFloat(scoress.value)){
tdd.innerHTML = "<img src='images/bullet.png'/>";
}//end if
}//end if 0..
previous_s = document.getElementById(score_ele).value;
}//end for
})//emd document ready..
</script>

The way you should execute you PHP-code using ajax is by moving the server side code to a separate file which you call apon in the ajax-request, the url.
One example is using jQuery.
$.ajax({
type: "POST",
url: "some.php",
data: { name: "John", location: "Boston" }
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
This documentation is located here
You send the information needed to execute the PHP-code in the data. These are then accessed by $_POST or $_GET depending on which type you chose.
If you're not intending to use jQuery, you can look here: Getting Started with AJAX - Updating Form via PHP.
Here are some good practices using ajax

Related

How to put object into string and print

I have a script that takes variables from an html form and sends them to a php script. I query new data based on these numbers and format them into a string to be sent back to the script. The problem is that my php variables aren't printing and I think it is because they are objects. Here is my code:
//GET VENDOR PO NUMBER AND APPEND ONCHANGE OF # OF EXISTING POS
$('#numvendpo').mouseover(function(){
var countpre = $(this).val();
var p = $('#pro').val();
var c = $('#custponumhold').val();
var v = $('#vendorid').val();
var cp = (parseInt(countpre)+1);
var data_String;
data_String = 'p='+p+'&c='+c+'&v='+v+'&cp='+cp;
$.post('ft-final-v-po-num.php',data_String,function(data){
var data = jQuery.parseJSON(data);
$('#vendponum').val(data);
});
});
I then post the values to this php script:
<?php
require "../inc/dbinfo.inc";
$p = $_POST['p'];
$c =$_POST['c'];
$v = $_POST['v'];
$cp = $_POST['cp'];
if ($c == 'null') { //cant use (!$customerpo) because $customerpo is passing the string of 'null' instead of the actual null value
$c = NULL; //so we change that to the actual null value
}
$getprojectnum = "SELECT ProjectNumber FROM tblProjects WHERE PROJECTNOID = '$p'"; //check
$getcustomerpo = "SELECT SequentialPONum FROM tblCustomerPOs WHERE CustomerPOID = '$c'"; //check
$getvendornum = "SELECT VendorNumber FROM tblVendors WHERE VENDORID = '$v'"; //check
$acpnhold = $conn->query($getprojectnum);
$accphold = $conn->query($getcustomerpo);
$acvnhold = $conn->query($getvendornum);
$acpn = mysqli_fetch_object($acpn);
$accp = mysqli_fetch_object($accp);
$acvn = mysqli_fetch_object($acvn);
if($c){
$string = $acpn.'-'.$accp.'-'.$acvn.'-'.$cp;
echo json_encode($string);
exit();
}elseif(!$c){
$string = $acpn.'-'.$acvn.'-'.$cp;
echo json_encode($string);
exit();
}else{
echo json_encode('Error');
exit();
}
?>
The response on my webpage is ---2 instead of (ex: 18000-1-2-2). As mentioned earlier I think it is because they are objects but I am not quite sure. Any advice is appreciated.
Your problem is with this bit:
$acpn = mysqli_fetch_object($acpn);
$accp = mysqli_fetch_object($accp);
$acvn = mysqli_fetch_object($acvn);
From the php docs:
object mysqli_fetch_object ( mysqli_result $result [, string $class_name = "stdClass" [, array $params ]] )
Your $acpn $accp and $acvn are not result objects. They are not even defined before you use them in those calls.
This should get the single column from each query result:
$acpn = $acpnhold->fetch_row()[0];
$accp = $accphold->fetch_row()[0];
$acvn = $acvnhold->fetch_row()[0];
Bear in mind you still have a major SQL Injection vulnerability with the original query calls.
Try like this code below:
$.ajax({
type: 'POST',
url: 'ft-final-v-po-num.php',
data: {
'p': p,
'c': c,
'v': v,
'cp': cp
},
success: function(msg){
var data = jQuery.parseJSON(data);
$('#vendponum').val(data);
}
});

Getting correct value of num_rows back AJAX/JSON

I have a notification system that out puts the right value of 1 and updates the div accordingly when a user posts one on my wall.
{
"num":1,
"notification_id":"640",
"notification_content":"Lucy Botham posted a status on your wall",
"notification_throughurl":"singlepoststreamitem.php?streamitem_id=515",
"notification_triggeredby":"85",
"notification_status":"1"
}
But if a user posts twice it does nothing and doesn't update at all.
{
"num":1,
"notification_id":"641",
"notification_content":"Lucy Botham posted a status on your wall",
"notification_throughurl":"singlepoststreamitem.php?streamitem_id=516",
"notification_triggeredby":"85",
"notification_status":"1"
}
{
"num":1,
"notification_id":"642",
"notification_content":"Lucy Botham posted a status on your wall",
"notification_throughurl":"singlepoststreamitem.php?streamitem_id=517",
"notification_triggeredby":"85",
"notification_status":"1"
}
CLIENT SIDE
$user1_id=mysqli_real_escape_string($mysqli,$_SESSION['id']);
$call="select MAX(notification_id) AS notification_id ,notification_status,notification_targetuser,notification_triggeredby,notification_throughurl from notifications WHERE notification_targetuser='$user1_id' AND notification_status='1'";
$chant=mysqli_query($mysqli,$call) or die(mysqli_error($mysqli));
while($notification=mysqli_fetch_array($chant)){
?>
<script type="text/javascript">
var notification_id="<?php echo $notification['notification_id']?>";
var notification_targetuser="<?php echo $notification['notification_targetuser']?>";
var notification_triggeredby="<?php echo $notification['notification_triggeredby']?>";
function loadIt() {
$.ajax({
type: "GET",
url: "viewajax.php?notification_id="+notification_id+"&notification_targetuser="+notification_targetuser+"&notification_triggeredby="+notification_triggeredby,
dataType:"json",
success: function(data){
if(data.notification_stream=1){
$("#notif_ui"+notification_id).prepend('<div class="notif_text"><div id="notif_actual_text-" class="notif_actual_text"><img border="1" src="userimages/cropped'+data['notification_triggeredby']+'.jpg" onerror=this.src="userimages/no_profile_img.jpeg" width="40" height="40" ><br />'+data['notification_content']+' <br />'+data['notification_time']+'<br/></div></div></div><hr/>');
i = parseInt($("#mes").text()); $("#mes").text((i+data.num));
if(!data.notification_id.length) {
//no results...
return;
}
notification_id = data.notification_id;
}
}
});
}
setInterval(loadIt, 10000);
</script>
<? } ?>
SERVER SIDE
$json = array();
$com=mysqli_query($mysqli,"SELECT * from notifications WHERE notification_targetuser='$idw' AND notification_triggeredby='$ide' AND notification_status='1' ORDER BY notification_id")or die($mysqli);
while($row = mysqli_fetch_assoc($com)){
$num = mysqli_num_rows($com);
if($num){
$json['num'] = 1;
}else{
$json['num'] = 0;
}
$json['notification_id'] = $row['notification_id'];
$json['notification_content'] = $row['notification_content'];
$json['notification_throughurl'] = $row['notification_throughurl'];
$json['notification_triggeredby'] = $row['notification_triggeredby'];
$json['notification_status'] = $row['notification_status'];
echo json_encode($json);
}}
$sql = "UPDATE notifications SET notification_status = '2' WHERE notification_targetuser='$idw'";
$go = mysqli_query($mysqli,$sql) or die(mysqli_error($mysqli));
You're echoing the JSON results inside a loop, so if the loop executes more than once, the final result is not valid JSON data. It's just multiple chunks of JSON.
while($row = mysqli_fetch_assoc($com)){
$id = $row['notification_id'];
$num = mysqli_num_rows($com);
if($num){
$json['num'] = 1;
}else{
$json['num'] = 0;
}
$json[$id]['notification_id'] = $row['notification_id'];
$json[$id]['notification_content'] = $row['notification_content'];
$json[$id]['notification_throughurl'] = $row['notification_throughurl'];
$json[$id]['notification_triggeredby'] = $row['notification_triggeredby'];
$json[$id]['notification_status'] = $row['notification_status'];
}
echo json_encode($json);
Then you'll need to adjust your Javascript to expect an array instead of a flat object.

saving data from csv to php and mysql

I am trying to import all the data from csv to the database.
Below code is ajax request that is sent to a php file.
$('#upload_location_csv').click(function(e){
e.preventDefault();
var queryDict = {};
location.search.substr(1).split("&").forEach(function(item) {queryDict[item.split("=")[0]] = item.split("=")[1]});
fi = document.getElementById("csv_file_input").files[0];
reader = new FileReader;
reader.onload = function(){
csv_data = reader.result;
$.ajax({
type:"post",
url:ajax_root_path+'fend.php',
data:{
location_id:queryDict['id'],
csv_data:csv_data,
perform_action:"save_delivery_csv_data"
},
success:function(resObj){
window.location.reload();
},
error:function(resObj){
}
});
};
reader.readAsText(fi);
});
This is the action that is performed, where here is, save_delivery_csv_data .
When I click on import csv, the page reloads and no request is sent to fend.php.
case 'save_delivery_csv_data':
{
$location_id = $param_array['location_id'];
$csv_data = $param_array['csv_data'];
$csv_data_rows = explode("\n",$csv_data);
unset($csv_data_rows[0]);
$csv_data_rows = array_values($csv_data_rows);
debug($csv_data_rows);
$csv_data_array = array();
foreach ($csv_data_rows as $csv_row_key => $csv_row_value)
{
$csv_row_value_array = explode(",",$csv_row_value);
debug($csv_row_value_array);
if(count($csv_row_value_array) == 5)
{
/*$csv_data_array[$csv_row_key] = array();
$csv_data_array[$csv_row_key]['locality_id'] = $csv_row_value_array[0];
$csv_data_array[$csv_row_key]['locality_name'] = $csv_row_value_array[1];
$csv_data_array[$csv_row_key]['minimum_order_amount'] = $csv_row_value_array[2];
$csv_data_array[$csv_row_key]['delivery_time'] = $csv_row_value_array[3];
$csv_data_array[$csv_row_key]['delivery_charge'] = $csv_row_value_array[4];*/
//debug($csv_row_value_array);
if(isset_empty($csv_row_value_array[3]))
{
//debug($csv_row_value_array);
$locality_id = $csv_row_value_array[0];
$location_outletValues = array();
$location_outletValues['cloud_site_id'] = $cloud_site_id;
$location_outletValues['location_id'] = $location_id;
$location_outletValues['locality_id'] = $locality_id;
$location_outletValues['minimum_order'] = $csv_row_value_array[2];
$location_outletValues['delivery_time'] = $csv_row_value_array[3];
$location_outletValues['delivery_charge'] = $csv_row_value_array[4];
$sql = "SELECT outlet_locality_id FROM ".PLATFORM_OUTLET_LOCALITIES."
WHERE location_id='".$location_id."' AND locality_id='".$locality_id."'";
$outlet_locality_array = $DB->query($sql);
//debug($outlet_locality_array);
if(count($outlet_locality_array) > 0)
{
$condition_array = array();
$condition_array['outlet_locality_id'] = $outlet_locality_array[0]->outlet_locality_id;
//debug($condition_array);
debug($location_outletValues);
$DB->update(PLATFORM_OUTLET_LOCALITIES,$location_outletValues,$condition_array);
}
else
{
$DB->insert(PLATFORM_OUTLET_LOCALITIES,$location_outletValues);
}
}
}
}
break;
//debug($csv_data_array);
}
What am I missing out here?? I also tried debugging variables values, but no request was sent to fend.php, whereas other request on the same page are being successfully sent.

PHP/Jquery auto check data then do insert

For example, I have the following data
Name Date
Aplha 10/05/1988
Bravo 10/04/1999
Charlie 10/08/1990
I'm trying to make a auto check data (database) for every minute,
and compare it with the current Date on the computer, if its the same, I can insert message like happy birthday.
Someone can provide reference or solution to this, would be appreciated.
its like notification but in this case it will send message automatic
edited note - nvm i got it..updated script
my js
$(function()
{
setInterval(function() {
$.ajax({
url: "dooBday.php",
success: function (data) {
$("#feedback").html(data);
}
});
}, 1000 * 60);
});
my dooBday function
$tgl=date("d/m");
$tglInt=date("d/m");
$tglInt=preg_replace( '~\D~', '', $tglInt);
$tglInt=intval($tglInt);
// Database Object
$tablename = "Phonebook_New";
$tablename2 = "USER_ID";
$xo=0;
$xx=0;
$VinDB = new VinDB();
// Get Data
$query2 = "SELECT * FROM ".$tablename2." WHERE UserID='".getMultiUserID()."'";
$result2 = $VinDB->query($query2);
if ($VinDB->num_rows($result2) != 0)
{
$line2 = $VinDB->fetch_array($result2);
if($line2["bdaySts"]==1 and strlen(trim($line2["bdayMsg"])) > 0){
// Get Data--------------------------------
$query = "SELECT * FROM ".$tablename." WHERE User_ID='".getMultiUserID()."' AND bdaySent='x'";
$result = $VinDB->query($query);
if ($VinDB->num_rows($result) != 0)
{
while ($line = $VinDB->fetch_array($result))
{
if(!empty($line["Ultah"])){
$tglNew=substr($line["Ultah"], 0, -5);
if($tgl==$tglNew){
$datex = date('Y/m/d');
$timex = date('H:i:s');
$schedule= date($datex . '-' . $timex);
//doo Update Contact Sent--------------------
$sqlquery[$xo]="UPDATE ".$tablename." SET bdaySent='Sent' where User_ID='".getMultiUserID()."' and nomor='".$line["nomor"]."'";
$xo++;
// doo Send Message----------------------------
$inuquery[$xx] = "INSERT INTO Schedule ";
$inuquery[$xx] .= "(message,phone_number,Schedule,Status,User_ID) ";
$inuquery[$xx] .= "VALUES ('".$line2['bdayMsg']."','".$line['PhoneNumber']."','".$schedule."','Processing','";
if (isset($_SESSION['user_id2']))
{
$inuquery[$xx] .= $_SESSION['user_id2']."')";
} else {
$inuquery[$xx] .= "Unknown')";
}
$xx++;
}}
}//end while
}// end if
}
}//end send bday
for($i=0;$i<$xo;$i++){
$result = $VinDB->query($sqlquery[$i]);
$result2 = $VinDB->query($inuquery[$i]);
}
I think you want to wish users. If I am right. You can do it like this.
put this code on your page where you would like to check every minute
setInterval(function() {
$.ajax({
url: "ajx.php",
success: function (data) {
$("#feedback").html(data);
}
});
}, 1000 * 60);
And this will be your ajax.php file
<?php
// Name Date
// Aplha 10/05/1988
// Bravo 10/04/1999
// Charlie 10/08/1990
$alphaDob = '02/04/1988';
$exp = explode('/', $alphaDob);
$userDate = $exp[0];
$userMonth = $exp[1];
$currentDate = date('Y-m-d');
$exp = explode('-', $currentDate);
$currentDate = $exp[2];
$currentMonth = $exp[1];
if($currentMonth == $userMonth && $currentDate == $userDate) {
echo 'Happy Birthday';
}
For good performance use Ajax-Long-Polling function, example can be found here Long-Polling Example

Adobe Flash send file to PHP

I have flash file that sends file to php but I cannot debug it. e.g. var_dump($_FILE) shows nothing! However when I run script it does work and upload file to server.
This is part of action script.
listener.onSelect = function (selectedFile, bytesTotal) {
browse._visible = false;
uploadBtn._visible = true;
var _loc3 = new Date();
sendTimeFLASH = _loc3.getTime();
sendTime = sendTimeFLASH;
totalId = flashimgID + ":" + selectedFile.name;
flash.external.ExternalInterface.call("funName", totalId);
statusArea.text = details.text = "";
txt_mc.statusArea.text = txt_mc.statusArea.text + selectedFile.name;
videoFile_name = selectedFile.name;
var _loc4 = imageFile.size;
d = _loc4 / 1000;
txt.text = selectedFile.name + "(" + Math.round(d) + "Kb): now click Upload to proceed";
var _loc1 = new LoadVars();
_loc1.imgPHP = flashimgID;
_loc1.imgName = selectedFile.name;
_loc1.timePHP = sendTime;
_loc1.sendAndLoad("page.php", _loc1, "POST");
imageFile.upload("page.php?id=" + flashimgID);
};
file is not sent in $_FILES from flash, but as a byte array.
save it like this:
$data = file('php://stdin');
if(file_put_contents('/path/to/file',$data)){
echo 1;
}else{
echo 0;
}

Categories