how to avoid the multiple execution of insert query - javascript

I am working with OT system.i have some problem regrading OT hours request program.this program send the department employee OT hours in to the admin panel notification and OT hours save in the database.my problem is when send OT request each person create the separate OT notification .I want send the single notification set of the department people.
$(document).on('click', '.overtime_send', function() {
temp = 0;
$('#employee_table tbody tr').each(function(row, tr) {
var emp_no = $(tr).find('td:eq(0)').text();
var ot_hours = $(tr).find('input').val();
//ot_array.push([emp_no,ot_hours]);
$.ajax({
url: 'otrequset_action.php',
type: 'POST',
data: { action:'add_ot',emp_no : emp_no, ot_hours:ot_hours},
dataType:"json",
success:function(data)
{
if(data.success)
{
swal("Good job!", "OverTime Request Send Successfully!", "success");
temp = 1;
dataTable.ajax.reload();
}
}
});
});
alert(temp);//if data.success block execute but alert still get value as 0
if (temp == 1) {
$.ajax({
url: 'otrequset_action.php',
type: 'POST',
data: { action:'add_comment'},
dataType:"json",
success:function(data)
{
if(data.success)
{
dataTable.ajax.reload();
}
}
});
}
i all ready got some solution .i get create the temp variable and OT request process successful it assign temp = 1 and after the each loop i try to insert notification data into the database.but if data.success success but alert(temp); not get value as 1 .how do i solve this question.
back end code
if($_POST["action"] == 'add_ot')
{
$today = date("Y-m-d");
$department = $_SESSION["dept_Id"];
$state = 5 ;
$emp_no = $_POST["emp_no"];
$ot_hours = $_POST["ot_hours"];
if($ot_hours != '00:00'){
$data = array(
':today' => $today,
':department' => $department,
':emp_no' => $emp_no,
':ot_hours' => $ot_hours,
':state' => $state
);
$query = "
INSERT INTO otresquest
(emp_id,date,ot_hour,dept_Id,overtime_status)
VALUES (:emp_no, :today, :ot_hours,:department,:state)
";
$statement = $connect->prepare($query);
if($statement->execute($data))
{
$output = array(
'success' => 'OT request has been Sent succesfully',
);
}
}
echo json_encode($output);
}
if($_POST["action"] == 'add_comment')
{
$today = date("Y-m-d");
$department = $_SESSION["dept_Id"];
$comment_status = 0 ;
$data = array(
':today' => $today,
':department' => $department,
':state' => $comment_status
);
$query = "
INSERT INTO comments
(dept_Id,date,comment_status)
VALUES (:department,:today,:state)
";
$statement = $connect->prepare($query);
$statement->execute($data);
}

**This might be solve your problem**
(document).on('click', '.overtime_send', function() {
temp = 0;
$('#employee_table tbody tr').each(function(row, tr) {
var emp_no = $(tr).find('td:eq(0)').text();
var ot_hours = $(tr).find('input').val();
//ot_array.push([emp_no,ot_hours]);
$.ajax({
url: 'otrequset_action.php',
type: 'POST',
data: { action:'add_ot',emp_no : emp_no, ot_hours:ot_hours},
dataType:"json",
success:function(data)
{
swal("Good job!", "OverTime Request Send Successfully!", "success");
temp++;
dataTable.ajax.reload();
if (temp == 1) {
$.ajax({
url: 'otrequset_action.php',
type: 'POST',
data: { action:'add_comment'},
dataType:"json",
success:function(data)
{
if(data.success)
{
dataTable.ajax.reload();
}
}
});
}
}
});
});
swal({title: "No data entering?",text: "Not set the overtime hours !",type: "warning"});
});

Related

AJAX query post data coming through empty/NULL

I need a sanity check here. I'm posting data through an AJAX call but for some reason it comes through as null.
javascript:
var data = {};
data['pkStudyYears'] = id;
data['years'] = [];
data['years']['pkStudyYears'] = id;
data['years']['fkStudyID'] = $('#fkStudyID').val();
data['action'] = action;
data['years']['intStartYr'] = $('#startYearBox').val();
data['years']['intEndYr'] = $('#endYearBox').val();
console.log(data['years']);
var posturl = '<?php echo site_url('manage/climate_indicators/updateStudyYears');?>'
$.when($.ajax({
type: "POST",
url: posturl,
data: data,
dataType: 'json'
}))
.done(function(result) {
console.log(result.status);
if (result.status === 'failed') {
console.log(result.errors);
}
});
php (updateStudyYears)
$postData = $this->input->post(NULL, true);
$yearArray = $postData['years'];
if(empty($yearArray)) {
echo json_encode(array('status'=>'failed', 'errors'=>'Years are empty'));
exit();
}
I keep getting a failed result with the error "Years are empty". I can't figure out what I'm missing!

Ajax request to php with empty POST data

I am new to javascript and I have problem with an ajax POST to php.
I am trying tosend javascript variables to php via an ajax POST but it doesn't work.
The ajax post is sent but it sends empty POST. I got alert "Error occured ! 202" when trying to save data to bdd.
Thanks in advance for helping me.
here are my javascript and php codes :
<script type="text/javascript">
function save_marker(mId, vId)
{
//Save new marker using jQuery Ajax
var myData = { 'markerId' : mId, 'vendorId' : vId }; //post variables
console.log(myData);
jQuery.ajax({
type: "POST",
url: "https://marchad.fr/wp-content/plugins/wc-multivendor-marketplace/includes/map_process.php",
data: myData,
cache: false,
dataType: "json",
contentType : "application/json; charset=utf-8",
success: function(dataResult){
var stringified = JSON.stringify(dataResult);
var dataResult = JSON.parse(stringified);
if(dataResult.statusCode==200){
alert("ok"+dataResult);
}
else if(dataResult.statusCode==201){
alert("Error occured !");
} else if(dataResult.statusCode==202){
alert("Error occured ! 202");
} else if(dataResult.statusCode==203){
alert("Error occured ! 203");
}
},
error:function (xhr, ajaxOptions, thrownError){
alert('Ooops, something happened: ' + ajaxOptions + ' ' +thrownError);
}
});
}
</script>
<?php
global $WCFM, $WCFMmp, $wpdb;
$mId = filter_var($_POST["markerId"], FILTER_SANITIZE_STRING);
$vId = filter_var($_POST["vendorId"], FILTER_SANITIZE_STRING);
################ Save & delete markers #################
if( isset($mId) && isset($vId) ) //run only if there's a post data
{
if( !empty($mId) && !empty($vId) ){
//make sure request is comming from Ajax
$xhr = $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest';
if (!$xhr){
header('HTTP/1.1 500 Error: Request must come from Ajax!');
exit();
}
$results = $wpdb->query("INSERT INTO markers_users (id, mark_id, user_id, user_actif) VALUES ('', $mId , $vId , 'oui')");
if (!$results) {
echo json_encode(array("statusCode"=>201));
} else {
echo json_encode(array("statusCode"=>200));
}
} else {
echo json_encode(array("statusCode"=>202));
}
} else {
echo json_encode(array("statusCode"=>203));
}
?>
Your problem is here:
var myData = { 'markerId' : mId, 'vendorId' : vId };
The field names don't need to be in quotes
Change it to this and try again:
var myData = { markerId : mId, vendorId : vId };
try this
data: JSON.stringfy(myData)
ok so the solution is :
<script type="text/javascript">
function save_marker(mId, vId)
{
//Save new marker using jQuery Ajax
var myData = { markerId : mId, vendorId : vId }; //post variables
console.log(myData);
jQuery.ajax({
type: "POST",
url: "https://marchad.fr/wp-content/plugins/wc-multivendor-marketplace/includes/map_process.php?markerId="+ mId +"&vendorId="+ vId,
data: myData,
cache: false,
dataType: "json",
contentType : "application/json; charset=utf-8",
success: function(dataResult){
var stringified = JSON.stringify(dataResult);
var dataResult = JSON.parse(stringified);
if(dataResult.statusCode==200){
alert("ok"+dataResult);
}
else if(dataResult.statusCode==201){
alert("Error occured !"+dataResult.statusCode+dataResult.mId+dataResult.vId+dataResult.rawData+dataResult.rawDataMid+dataResult.rawDataVid+dataResult.datamId+dataResult.datavId);
} else if(dataResult.statusCode==202){
alert("Error occured ! 202"+dataResult.statusCode+dataResult.mId+dataResult.vId+dataResult.rawData+dataResult.rawDataMid+dataResult.rawDataVid);
} else if(dataResult.statusCode==203){
alert("Error occured ! 203"+dataResult.statusCode+dataResult.mId+dataResult.vId+dataResult.rawData+dataResult.rawDataMid+dataResult.rawDataVid);
}
},
error:function (xhr, ajaxOptions, thrownError){
alert('Ooops, something happened: ' + ajaxOptions + ' ' +thrownError);
}
});
}
</script>
<?php
//mysqli
$mysqli = new mysqli($db_host, $db_username, $db_password, $db_name);
if (mysqli_connect_errno())
{
die('Erreur de connexion : ' . $mysqli->connect_errno);
}
$rawData = file_get_contents("php://input");
$data = array();
parse_str($rawData, $data);
$mId = $data['markerId'];
$vId = $data['vendorId'];
################ Save & delete markers #################
if( isset($mId) && isset($vId) ) //run only if there's a post data
{
if( !empty($mId) && !empty($vId) ) //run only if there's a post data
{
$results = $mysqli->query("INSERT INTO markers_users (id, mark_id, user_id, user_actif) VALUES ('', $mId , $vId , 'oui')");
if (!$results) {
echo json_encode(array("statusCode"=>201, "mId"=>$mId, "vId"=>$vId, 'rawData' => $rawData, 'rawDataMid' => $rawData["markerId"], 'rawDataVid' => $rawData["vendorId"], "datamId"=> $data['markerId'], "datavId"=> $data['vendorId']));
} else {
echo json_encode(array("statusCode"=>200));
}
} else {
echo json_encode(array("statusCode"=>202));
}
} else {
echo json_encode(array("statusCode"=>203));
}
?>

submit form to check something with ajax and jquery

I am making a form to check a security code. In fact, I am new to ajax and jquery, so I tried what I can, but my code doesn't work. Can anybody help me?
php file :
<?php
include('/includes/db-connect.php');
if( isset($_POST["seccode"]) ){
$result=mysqli_query($con,"SELECT * FROM `certificate_acheived_tbl` WHERE `cert_check_code` = ".$seccode.")";
if( mysql_num_rows($result) == 1) {
echo "<script>alert('s')";
}
}
?>
js file:
$(function() {
$(".btn btn-success").click(function() {
var ID = $(this).attr('id');
$.ajax({
type: "POST",
url: "cert-check-ajax.php",
data: 'certcode='+ ID,
success: function() {
$('#someHiddenDiv').show();
console.log();
}
});
});
});
your code is bad... (sometimes mine too)
One first mistake : data: 'certcode='+ ID, in jQuery
and isset($_POST["seccode"]) in PHP 'certcode' != 'seccode'
so a better code.. ?
jQuery (I allways use JSON, it's more easy)
$(function () {
$(".btn btn-success").click(function() {
var
Call_Args = {
certcode: $(this).attr('id')
};
$.ajax({
url: 'cert-check-ajax.php',
type: 'POST',
data: Call_Args,
cache: false,
dataType: 'json',
success: function (data) {
console.log( data.acceptCod ); // or data['acceptCod'] if you want
$('#someHiddenDiv').show();
// ...
}
}); //$.ajax
}); // btn btn-success").click
});
PHP (with utf8 insurance, and good header / JSON encode response )
<?php
mb_internal_encoding("UTF-8");
include('/includes/db-connect.php');
$T_Repons['acceptCod'] = "bad";
if (isSet($_POST['certcode'])) {
$sql = "SELECT * FROM `certificate_acheived_tbl` ";
$sql .= "WHERE `cert_check_code` = ".$_POST['certcode'].")";
$result = mysqli_query($con, $sql);
$T_Repons['acceptCod'] = (mysql_num_rows($result) == 1) ? "ok" : "bad";
}
header('Content-type: application/json');
echo json_encode($T_Repons);
exit(0);
?>
you can use it
$(function() {
$(".btn btn-success").click(function() {
var ID = $(this).attr('id');
$.ajax({
type: "POST",
url: "cert-check-ajax.php",
data: {'seccode': ID}
}).done(function(data) {
$('#someHiddenDiv').show();
console.log(data);
});
});
});

Magento insert data into database through ajax

I'm new to ajax so I'm not sure if i'm approaching this correctly, basically I have a variable in javascript that need to be inserted into the database, this is what I have so far...
onInit: function() {
window.fcWidget.on('widget:loaded', function() {
window.fcWidget.user.get().then(function(resp) {
var status = resp && resp.status,
data = resp && resp.data;
if (status === 200) {
if (data.restoreId) {
// Update restoreId in database
$.ajax({
type: "POST",
url: "insert.php",
data: data.restoreId,
success: function(data) { alert("Success"); },
failure: function(data) { alert("Failure"); }
})
}
}
});
});
}
I have placed the file "insert.php" in the same folder but it seem like it doesn't get called at all...
This is what insert.php looks like
<?php
if(Mage::getSingleton('customer/session')->isLoggedIn()){
if(isset($_POST['data.restoreId']){
$restoreId =$_POST['data.restoreId'];
}
$first = Mage::getSingleton('customer/session')->getCustomer()->getFirstname();
$last = Mage::getSingleton('customer/session')->getCustomer()->getLastname();
$fullName = $first . "." . $last;
//get resource model
$resource = Mage::getSingleton('core/resource');
//retrieve write connection
$writeConnection = $resource->getConnection('core_write');
//read connection
$readConnection = $resource->getConnection('core_read');
$exId = $fullName;
$resId = $restoreId;
$testQuery = "SELECT `externalId` FROM `freshchat_user` WHERE `restoreId` = '$fullName'";
$result = $readConnection->fetchAll($testQuery);
if(count($result) == '0'){
$query = "INSERT INTO `freshchat_user`(`externalId`, `restoreId`) VALUES ('$exId','$resId')";
$writeConnection->query($query);
}else{
//echo "nope";
}
}
?>
I checked the network tab but insert.php doesn't seem to be called at all, what is wrong with my code?
//Please put your insert.php file in root path(Magento installation path) and change below line in your javascript code.
url: "www.yourwebsite.com/insert.php",

Post to php file, and retrieve data with javascript

So i have a php file, that prints data from a table encoded on JSON format.
This is the php file:
<?php
include "db.php";
$id=$_POST['id'];
$data=array();
$q=mysqli_query($con,"select * from `sitios` where `id_sitio`='$id'");
while ($row=mysqli_fetch_object($q)){
$data[]=$row;
}
if($q)
echo "success";
else
echo "error";
}
echo json_encode($data);
?>
This is the javascript script:
$(document).ready(function() {
var id = decodeURI(getUrlVars()["id"]);
var dataString = "id=" + id;
$.ajax({
type: "POST",
url: "http://pedrofidalgo.pt/bilapoint/listar_sitio_single.php",
data: dataString,
crossDomain: true,
cache: false,
success: function(data) {
if (data == "success") {
$.getJSON(url, function(result) {
console.log(result);
$.each(result, function(i, field) {
var id = field.id_sitio;
var nome = field.nome;
var descricao = field.descricao;
var img = field.img;
var morada = field.morada;
var coordenada_x = field.coordenada_x;
var coordenada_y = field.coordenada_y;
document.getElementById("titulo").innerHTML = nome;
document.getElementById("desc").innerHTML = descricao;
document.getElementById("morada").innerHTML = morada;
});
});
} else if (data == "error") {
alert("error");
}
}
});
});
So basically i a have where i have all items from the database select (list_all.php), and then when i click on a single item, the ID of that item is passed on the URL, and i retrieve it on the otherside with javascript. I dont use GET because this is with phonegapp, so i use a .js file called getURI.js.
First, the function gets the ID that was passed. Then it posts to the PHP file, and the PHP file will get the ID, and make the query for that single item on the database. Is successed, i wanted to store all that data on variables. But for some reason, im getting an error on the console saying
POST http://192.168.1.241:3000/proxy/http%3A%2F%2Fpedrofidalgo.pt%2Fbilapoint%2Flistar_sitio_single.php 500 (Internal Server Error)
THe server is responding correctly because others scripts on the app are working.
In PHP
<?php
include "db.php";
$id=$_POST['id'];
$data=array();
$q=mysqli_query($con,"select * from `sitios` where `id_sitio`='$id'");
while ($row=mysqli_fetch_object($q)){
$data[]=$row;
}
if($q)
echo json_encode(array('status' => true, 'data' => $data));
else
echo json_encode(array('status' => false, 'data' => $data));
?>
In Jquery
$(document).ready(function() {
var id = decodeURI(getUrlVars()["id"]);
var dataString = "id=" + id;
$.ajax({
type: "POST",
url: "http://pedrofidalgo.pt/bilapoint/listar_sitio_single.php",
data: dataString,
crossDomain: true,
cache: false,
success: function(data) {
data = JSON.parse(data);
if (data['status']) {
$.each(data['data'], function(i, field) {
var id = field.id_sitio;
var nome = field.nome;
var descricao = field.descricao;
var img = field.img;
var morada = field.morada;
var coordenada_x = field.coordenada_x;
var coordenada_y = field.coordenada_y;
document.getElementById("titulo").innerHTML = nome;
document.getElementById("desc").innerHTML = descricao;
document.getElementById("morada").innerHTML = morada;
});
} else {
alert("error");
}
}
});
});

Categories

Resources