Response values overlapping in ajax - javascript

I am making an application where I need to have multiple Ajax requests. But the problem is that I am getting same response values for both Ajax requests.
In each request there needs to be a data named activityCode but doing that I keep getting the value of ScoreBoardResponse even in the heartbeat function too. If I rename anyone of the activityCode to any other name the problem gets sorted. But why does this happen?
Here is the following code:
JS
var allJoined = false;
var roomName = $('#room').val();
var playerNameSet = function () {
if(!allJoined) {
$.ajax({
type: "POST",
url: "gameEngine/app.php",
data: {
activityCode: 1,
room: roomName
},
success: function (ScoreBoardResponse) {
var obj = JSON.parse(ScoreBoardResponse);
var count = Object.keys(obj).length;
if (count == 1) {
playerOne_name.html(obj.p1_name);
setTimeout(playerNameSet, 3000);
}
else if (count == 2) {
playerOne_name.html(obj.p1_name);
playerTwo_name.html(obj.p2_name);
allJoined = true;
//Start the heartbeat to check if the other player is alive
setTimeout(startHeartbeat, 15000);
clearTimeout(playerNameSet);
}
},
error: function (error) {
console.log(error);
}
});
}
};
setTimeout(playerNameSet, 3000);
function startHeartbeat() {
$.ajax({
type: "POST",
url: "gameEngine/app.php",
data: {
activityCode: 2,
room: roomName
},
success: function(beat) {
console.log(beat);
},
error: function(error) {
console.log(error);
}
});
setTimeout(startHeartbeat, 15000);
}
PHP
.
.
.
elseif (isset($_POST['activityCode']) == 1 && isset($_POST['room'])) {
$response = $gameHandler->getPlayerOrder($_POST['room']);
echo $response;
}
elseif (isset($_POST['activityCode']) == 2 && isset($_POST['room'])) {
echo "request reached here";
}

isset() returns either true or false if the POST variable exists or not. It does not return the variable value, the you need to add another check in your condition :
elseif (isset($_POST['activityCode']) && $_POST['activityCode'] == 1 && isset($_POST['room'])) {
$response = $gameHandler->getPlayerOrder($_POST['room']);
echo $response;
}
elseif (isset($_POST['activityCode']) && $_POST['activityCode'] == 2 && isset($_POST['room'])) {
echo "request reached here";
}

Related

how to avoid the multiple execution of insert query

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"});
});

Error and Success Handling in JQuery Ajax PHP

how can i handle error and success messages in Ajax? I have an ajax call where my datas are saved into a db. My php script first checked if a user have x amount. if he has less then x then he should fire a alert (amount < x) Else insert into db.
my php file:
...
.....
if ($wallet_amount < "100") {
$wa1 = 0;
echo $wa1;
} else {
$inito = $connection->prepare("INSERT INTO bs (title, start, end, userid, typ, code) VALUES (:title, :start, :end, :pid, :col, :code)");
$inito->bindValue(':pid', $pid, PDO::PARAM_INT);
$inito->bindValue(':title', $title, PDO::PARAM_STR);
$inito->bindValue(':start', $start, PDO::PARAM_STR);
$inito->bindValue(':end', $end, PDO::PARAM_STR);
$inito->bindValue(':col', $col, PDO::PARAM_STR);
$inito->bindValue(':code', $code, PDO::PARAM_INT);
$inito->execute();
exit();
}
My js file:
$.ajax({
url: 'add.php',
data: {
'title': $('#Name').val(),
'start': start,
'end': $('#End').val(),
'code': $('input[name="code"]:checked').val()
},
type: "POST",
error: function () {
alert('There was an error while adding events.');
}
});
My first try goes wrong. I write something like that:
success: function (response) {
if (response === 0) {
alert("Amount < X!");
} else if (response === 1) {
alert("Amount > X);
}
},
error: function () {
alert('There was an error while adding events.');
}
I guess in success block you have used a strict check ===, this checks the type and value both:
success: function (response) {
if (response === '0') { // update this
alert("Amount < X!");
} else if (response === '1') {
alert("Amount > X"); //<---quote is missing i guess it's just a typo.
}
},
error: function () {
alert('There was an error while adding events.');
}
Also i am not sure if this check } else if (response === '1') { would ever happen because i don't see if you get '1' in the response.
To make the code a little more cleaner, I would suggest you start by returning the values with json (even if it is only one variable)
So the PHP look like
php
/* ... */
echo json_encode(array('wal' => $wal));
/* ... */
Next, in your ajax code, you need to read it correctly. E.g.
ajax
success: function(response) {
var wal = response.wal
if (wal == 0) {
alert("Amount < X!");
} else if (wal == 1) {
alert("Amount > X);
} else {
// ...
}
}
Try that, and as Jai said, only check for the value, and not for the type (x == 0 instead of x === 0)
I would not use the content of your respone to switch your error and success cases. Think about different status codes like status code 200 or 204 on success and status code 400 on error for example. Than, you can also code a more type-safe application with explicit return values:
$.ajax({
statusCode: {
404: function() {
alert( "page not found" );
}
}
});

implode breaks Ajax call

So I'm making an Ajax call which will first check to see if that post ID has already been voted on.
Currently I'm just working on the PHP to first get the post id's, if it is empty set it or if it is not empty to append the ID.
Question here: Except when I use the implode or explode method it does not seem to make a call back to the javascript. Although if I was to refresh the page it does register the vote.
This is the PHP file. For user Id I've just set it to my admin id to start with.
function my_user_vote() {
$user_id = 1;
$pageVoted = $_REQUEST["post_id"];
$currentPosts = get_user_meta($user_id, 'pages_voted_on');
if (empty($currentPosts)) {
// Empty create single array
$postsVotedOn[] = $pageVoted;
} else {
$postsVotedOn = explode('|', $currentPosts);
$postsVotedOn[] = $pageVoted;
}
$boo = implode("|", $pageVoted);
update_user_meta( $user_id, 'pages_voted_on', $boo);
if ( !wp_verify_nonce( $_REQUEST['nonce'], "my_user_vote_nonce")) {
exit("No naughty business please");
}
$vote_count = get_post_meta($_REQUEST["post_id"], "votes", true);
$vote_count = ($vote_count == '') ? 0 : $vote_count;
$new_vote_count = $vote_count + 1;
$vote = update_post_meta($_REQUEST["post_id"], "votes", $new_vote_count);
if($vote === false) {
$result['type'] = "error";
$result['vote_count'] = $vote_count;
}
else {
$result['type'] = "success";
$result['vote_count'] = $new_vote_count;
}
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$result = json_encode($result);
echo $result;
}
else {
header("Location: ".$_SERVER["HTTP_REFERER"]);
}
die();
}
This is the javascript.
jQuery(document).ready( function() {
jQuery(".user_vote").click( function() {
post_id = jQuery(this).attr("data-post_id")
nonce = jQuery(this).attr("data-nonce")
jQuery.ajax({
type : "post",
dataType : "json",
url : myAjax.ajaxurl,
data : {action: "my_user_vote", post_id : post_id, nonce: nonce},
success: function(response) {
if(response.type == "success") {
jQuery(".vote_counter").html("Votes: " + response.vote_count);
jQuery(".voteUpButton").html('<div class="button btnGreen">Thank you!</div>');
alert("Cooommmon");
console.log(response.vote_count);
}
else {
alert("Your vote could not be added")
}
}
})
})
})
I just did a quick test with your code, and found a couple of issues that throw errors:
1. This line:
$currentPosts = get_user_meta($user_id, 'pages_voted_on');
should be
$currentPosts = get_user_meta($user_id, 'pages_voted_on', true);
2. And I believe this line:
$boo = implode("|", $pageVoted);
should be
$boo = implode("|", $postsVotedOn);
Explanation:
Without the true argument get_user_meta returns an array. And you can't explode an array.
http://codex.wordpress.org/Function_Reference/get_user_meta
$pageVoted is the id of the page to add, while $postsVotedOn is the actual list you want it appended to.

jQuery AJAX with PHP to upload contents to MYSQL DB

I am looking for a jQuery AJAX script alongside a PHP script that allows for the storage of information on a button click. The function defined within the jQuery should take three variables, all of which are defined pre-method call. I have the basis of operation complete but at the end of all operations - after the button is clicked and some time has passed - no data is added to the appropriate mysql database.
Here is my jQuery function "store"
<script type="text/javascript">
function store(ud, ld, tp) {
$.ajax({
url: 'http://www.exampledomain.com/folder/store.php',
type: 'POST',
data: 'ud='+ud+'&ld='+ld+'&tp='+tp
success : function() {
alert("WORKED!");
},
error : function() {
alert("DIDN'T WORK!");
},
complete : function() {
}
});
}
</script>
Here is the store.php file (very basic I know, I have also yet to secure this script via sanitizing user input)
<?php
require ('../mysqli_connect.php');
$errors = 0;
if(isset($_POST['ud']) && is_numeric($_POST['ud'])) {
$ud = $_POST['ud'];
} else {
++$errors;
}
if(isset($_POST['ld']) && is_numeric($_POST['ld'])) {
$ld = $_POST['ld'];
} else {
++$errors;
}
if(isset($_POST['tp'])) {
$tp = strip_tags(stripslashes($_POST['tp']));
} else {
++$errors;
}
if($errors == 0) {
$q = "INSERT INTO table_name (column_1, column_2, column_3, column_4) VALUES ('$ld', '$ud', NOW(), '$tp')";
mysqli_query($mysqli, $q);
} else {
echo 'There was a problem!';
}
?>
Assume that I have onclick="store(3, 3, A)" as an attribute for a certain element. How can I fix this? If I remove the onclick attribute how do I pass the necessary parameters to the jQuery function? I appreciate any and all help!
<-- EDIT -->
New jQuery & AJAX Script ...
<script type="text/javascript">
function store(ud, ld, tp) {
$.ajax({
url: 'http://www.exampledomain.com/folder/store.php',
type: 'POST',
data: 'ud='+ud+'&ld='+ld+'&tp='+tp,
error : function() {
alert("error");
},
success : function(data) {
alert(data);
},
complete : function() {
alert("complete");
}
});
}
$(function () {
$("a.rec").on("click", function () {
var $this = $(this),
ud = $this.data("ud"),
ld = $this.data("ld"),
tp = $this.data("tp");
store(ud, ld, tp);
});
});
</script>
Revised PHP
<?php
if($_SERVER['REQUEST_METHOD'] === "POST"){
require ('../mysqli_connect.php');
$errors = 0;
if(isset($_POST['ud'])) {
$ud = $_POST['ud'];
} else {
++$errors;
}
if(isset($_POST['ld'])) {
$ld = $_POST['ld'];
} else {
++$errors;
}
if(isset($_POST['tp'])) {
$tp = $_POST['tp'];
} else {
++$errors;
}
if($errors == 0) {
$q = "INSERT INTO table_name (column_1, column_2, column_3, column_4) VALUES ('$ld', '$ud', NOW(), '$tp')";
mysqli_query($mysqli, $q);
} else {
echo 'There was a problem!';
}
} else {
$url = 'http://www.exampledomain.com/error.php';
ob_end_clean();
header("Location: $url");
exit();
}
?>
Now for my HTML
<li>
<div class="sample classes">
<a class="rec" data-ud="13" data-ld="10" data-tp="SCI">
<input type="submit" title="Something" value="Something" />
</a>
</div>
</li>
However, when this button is clicked, it still does not do anything!
As you said onclick is something you are going to want to avoid. This is how you do it.
$(function () { //This function will be ran when the page loads
$(".button-class").on("click", function () { //This will run when any button is clicked
var $this = $(this),
ud = $this.data("ud"),
ld = $this.data("ld"),
tp = $this.data("tp");
store(ud, ld, tp);
});
});
HTML
<input type="button" class="button-class" data-ud="3" data-ld="3" data-tp="A"/>
I find it easier to use JSON and pass variables in an object to the server:
<script>
(function(){
var store = function (ud, lrid, type) {
var data = {
ud:ud,
lrid:lrid,
type:type
};
$.ajax({
url: 'http://www.exampledomain.com/folder/store.php',
type: 'POST',
data: data,
success : function(data) {
alert(data);
},
error : function() {
alert("DIDN'T WORK!");
},
complete : function() {
}
});
};
$('#btn').on('click', function(){
store(1,2,3);
});
}());
</script>
Use this script to test you are getting the variables on the server side:
<?php
# Put this in http://www.exampledomain.com/folder/store.php to test it works
if($_SERVER['REQUEST_METHOD'] === "POST"){
if(
isset($_POST['ud']) &&
isset($_POST['lrid']) &&
isset($_POST['type'])
)
{
$var = $_POST['ud'] . ", ".$_POST['ud'] . ", ".$_POST['type'] ." passed successfully via ajax!";
echo json_encode($var);
}
}
?>

javascript mutually exclusive CheckBox issue

I have a radio button that displays a list of records in a telerik grid. When the radio button is checked, it displays complete and incomplete records. However, the user wants a way of displaying only complete or incomplete records. I added two mutually exclusive checkboxes. The user can either check the complete or incomplete checkbox to display the data. It works fine on my local, but it does not work well on the server. The first time, the user has to click the checkbox two or three times before it can keeps the state. In addition, if complete is checked and the user checked incomplete next, the checkmark will go back to complete. The user has to do it a second times. What I am doing wrong here?
Here is the html for the checkbox
#Html.CheckBox("complete", SessionWrapper.currentEncounter.complete, new { id = "chkComplete", onclick = "chkInCompleteOption(1);this.form.submit();" }) <strong>Complete</strong>
#Html.CheckBox("Incomplete", SessionWrapper.currentEncounter.incomple, new { id = "chkInComplete", onclick = "chkInCompleteOption(2);this.form.submit();" }) <strong>Incomplete</strong>
//Here is the javascript
var completeCheck = '#SessionWrapper.currentEncounter.complete';
var inCompleteCheck = '#SessionWrapper.currentEncounter.incomplete';
function chkInCompleteOption(e) {
if (e == 1) {
var cc = $('#chkComplete').is(':checked');
var data = { "complete": cc, "inComplete": false };
var url = '#Url.Action("CompletedOption", "Orders")';
$.ajax({
url: url,
type: 'post',
dataType: 'text',
data: data,
success: function (data) {
testComplete();
return true;
},
error: function (error) {
alert("An error has occured.");
return false;
}
});
}
else if (e == 2) {
var inc = $('#chkInComplete').is(':checked')
var data = { "complete": false, "inComplete": inc };
var url = '#Url.Action("CompletedOption", "Orders")';
$.ajax({
url: url,
type: 'post',
dataType: 'text',
data: data,
success: function (data) {
testInComplete();
return true;
// $('#chkComplete').removeAttr("checked", "checked");
// $('#chkInComplete').attr("checked", "checked");
},
error: function (error) {
alert("An error has occured.");
return false;
}
});
}
}
function testInComplete() {
if (inCompleteCheck == true) {
inCompleteCheck = $('#chkInComplete').attr("checked", "checked");
document.getElementById('chkInComplete').checked = true;
} else {
$('#chkInComplete').removeAttr("checked");
}
}
function testComplete() {
if (inCompleteCheck == true) {
completed = $('#chkComplete').attr("checked", "checked");
document.getElementById('chkComplete').checked == true;
} else {
$('#chkComplete').removeAttr("checked");
}
}
//Setting the mutually exclusive value on the server side
public bool CompletedOption(bool complete, bool inComplete)
if (inComplete == true && complete == true)
{
return false;
}
if (complete == true)
{
SessionWrapper.currentEncounter.complete = true;
}
else if (SessionWrapper.currentEncounter.complete == true && (complete == null || inComplete == null))
{
SessionWrapper.currentEncounter.complete = true;
}
else
{
SessionWrapper.currentEncounter.complete = false;
}
if (inComplete == true)
{
SessionWrapper.currentEncounter.incomplete = true;
}
else if (SessionWrapper.currentEncounter.incomplete == true && (complete == null || inComplete == null))
{
SessionWrapper.currentEncounter.incomplete = true;
}
else
{
SessionWrapper.currentEncounter.incomplete = false;
}
return true;
}
I found the issue. The server side was being updated properly; however, the ajax was returning an error message every time it executed. The method on the server side was returning a Boolean when a string was expected. I've also set async and cache to false. I ran the application again, and it works.
//Change Method Signature from boolean to string
public string CompletedOption(bool complete, bool inComplete)
{
return "true";
}
ajax post
$.ajax({
url: url,
type: 'post',
dataType: 'text',
async: false, //Added
cache: false, //Added
data: data,
success: function (data) {
return data;
},
error: function (error) {
alert("An error has occured.");
return false;
}
});

Categories

Resources