Uncaught SyntaxError: redeclaration of let varibale On Jquery Load - javascript

error in console
I am using window.history.pushstate to redirect without page refresh ...to refresh page I write
$("body").load("")
but I am getting error that variable are getting redeclared
is there any way to fix this error
Uncaught SyntaxError: redeclaration of let seconddeclared
http://localhost/testwebsite/test.php?name=java&qno=1 line 2 > injectedScript:1
b http://localhost/testwebsite/test.php?name=java&qno=1 line 2 > injectedScript:2
He http://localhost/testwebsite/test.php?name=java&qno=1 line 2 > injectedScript:2
append http://localhost/testwebsite/test.php?name=java&qno=1 line 2 > injectedScript:2
-----------function ------
function backq(testname,question,totalquestions){
if (question === 1) {
// location.replace(`?name=${testname}&qno=${++questionno}`);
window.history.pushState('question', 'title', `?name=${testname}&qno=${totalquestions}`);
$("#body").load("");
}
else {
// location.replace(`?name=${testname}&qno=${1}`);
window.history.pushState('question', 'title', `?name=${testname}&qno=${--question}`);
$("#body").load("");
}
}
=====let second declared variable=====
<script>
let seconddeclared = 0;
if (seconddeclared === 0) {
var seconds = <?php echo $atdr['remainingtime'] ?>;
}
++seconddeclared;
console.log("second declared " + seconddeclared)
var timee = setInterval(() => {
if (seconds == 0) {
$.ajax({
type: "POST",
url: "./ajax/updatetime.php",
data: {
testname: `<?php echo $testname ?>`,
rollno: <?php echo $sessionrollno ?>,
seconds: seconds
},
success: function(response) {
clearInterval(timee)
window.history.pushState('', '', '?name=<?php echo $testname; ?>&submit=b326b5062b2f0e69046810717534cb09');
$("html").load("")
}
});
} else {
var date = new Date(null);
seconds = Number(seconds).toString();
date.setSeconds(seconds);
if (seconds > 3600) {
$("#timer").text(date.toISOString().substr(11, 8));
} else {
$("#timer").text(date.toISOString().substr(14, 5));
}
$.ajax({
type: "POST",
url: "./ajax/updatetime.php",
data: {
testname: `<?php echo $testname ?>`,
rollno: <?php echo $sessionrollno ?>,
seconds: seconds
},
success: function(response) {}
});
}
--seconds;
}, 1000)
</script>

Related

How do I stop others from post requesting my php

I have a page called index.php. This contains a form which the user submits. Upon submission, it verifies the input from verify-input.php and returns some key information back to index.php. From there, index.php post requests scanner.php ~100 times. This is all done without refreshing index.php.
My question is, how do I stop other websites or other people from post requesting verify-input.php and scanner.php? I only want people to be able to call these files on my website (essentially, I don't want others using my verify-input.php and scanner.php API's for their own gain.
I've added the code below for these files, but I don't think it matters too much. I'm fairly good in PHP but I am terrible at javascript.
index.php
<script type="text/javascript" src="https://code.jquery.com/jquery-1.9.1.min.js"></script>
<div class="display-error" style="display: none"></div>
<form>
<label for="fname">Fruit (only correct input is: banana)</label><br>
<input type="text" id="fruit-name" name="fruit" value="banana"><br>
<button type="submit" id="submit" value="Submit">Submit</button>
</form>
<div id="results">
</div>
<script type="text/javascript">
$(document).ready(function() {
$('#submit').click(function(e) {
e.preventDefault();
$("#submit").attr("disabled", true);
$("#submit").html("Verifying Username");
var fruitName = $("#fruit-name").val();
$.ajax({
type: "POST",
url: "verify-input.php",
dataType: "json",
data: {
fruitName: fruitName
},
success: function(data) {
if (data.code == 200) {
$("#submit").html("Running Scan");
(async function() {
var fruitID = data.fruitId;
var min = 1;
while (min < 60) {
await scan(fruitID, min, min + 30);
min = min + 30;
}
$("#submit").html("Submit");
$("#submit").attr("disabled", false);
})();
} else {
$("#submit").html("Submit");
$("#submit").attr("disabled", false);
$(".display-error").html("<ul>" + data.msg + "</ul>");
$(".display-error").css("display", "block");
}
}
});
});
});
function scan(vFruitId, min, max) {
return $.ajax({
type: "POST",
url: "scanner.php",
dataType: "json",
data: {
vFruitId: vFruitId,
min: min,
max: max
},
success: function(data) {
data.forEach((item, idx) => {
$("#results").append(`
<div class="fruit-item" data-item="${idx}">
<div class="f-calories">calories: ${item.sweetness}</div>
<div class="f-sweetness">sweeteness: ${item.calories}</div>
<div class="f-bitterness">bitterness: ${item.bitterness}</div>
</div><br>
`);
})
}
});
}
</script>
verify-input.php
<?php
if (isset($_POST['fruitName'])) {
echo(is_valid($_POST['fruitName']));
}
function is_valid($fruit) {
// Verify post data is valid and correct
$names = ['Banana cake', 'Banana pancake', 'Banana bread'];
$colors = ['Yellow', 'Blue', 'Green', 'Purple', 'Black'];
sleep(2);
if ($fruit == "banana") {
$result['code'] = 200;
$result['fruitId'] = rand(1, 9999999);
$result['msg'] = "YAY SUCCESS";
$json = json_encode($result);
return $json;
}
$result['code'] = 400;
$result['msg'] = "ERROR! The correct fruit is banana";
$json = json_encode($result);
return $json;
}
scanner.php
<?php
ini_set('max_execution_time', '300');
define('MAX_SCAN', 30);
if (isset($_POST['vFruitId']) &&
isset($_POST['min']) &&
isset($_POST['max'])) {
$result = roomscanner($_POST['vFruitId'], $_POST['min'], $_POST['max']);
$json = json_encode($result);
file_put_contents("result.txt", $json);
echo($json);
}
function roomscanner($fruitId, $min, $max) {
$result = [];
$i = $min;
while ($i < $max) {
if ($i % 3 == 0) {
$curr['sweetness'] = rand(20, 29);
$curr['calories'] = rand(30, 39);
$curr['bitterness'] = rand(30, 39);
$result[] = $curr;
}
sleep(rand(0, 1));
$i++;
}
return $result;
}

Js on click triggers a php update, it also triggers on load

this works for me on delete button, but this works when I go to this page also, on load of page it triggers status update i dont want that to change unless i click delete
Is it because it is php inside js or what?
var deleted_question = 0;
$(document).on("click", "button[id=removequestion]", function(data) {
var total_question_nr = <?php echo count($questions);?>;
var test_status = <?php echo $test->status; ?>;
if (test_status == 1) {
if ((total_question_nr - deleted_question) == 1) {
var result = confirm("#lang('general.if_questions_zero_test')");
console.log(total_question_nr - deleted_question);
if ((total_question_nr - deleted_question) == 0) {
var status = <?php echo $test->update(['status' => 0]); ?>;
}
} else {
var result = confirm("#lang('general.are_you_sure_want_to_delete_question')?");
}
} else {
var result = confirm("#lang('general.are_you_sure_want_to_delete_question')?");
}
if (result) {
var questionid = $(this).val();
$.ajax({
method: "POST",
url: "{{ url('/questions/delete-question') }}",
data: {
_token: "{{ csrf_token() }}",
question_id: questionid,
},
success: function(response) {
$("button[id=removequestion][value=" + questionid + "]").parent().parent().fadeOut('slow');
deleted_question++;
if ((total_question_nr - deleted_question) == 0) {
$('#publish-col').find('a').each(function() {
$(this).addClass("disabled");
});
}
},
error: function() {
console.log("error");
}
});
}
});

Ajax still executing even an error found

Good day programmers! I'am trying to submit a form then validate it using jquery with 2 ajax events. I am using ajax(timeconflict.php) for validating if there is conflict with the user's time input. but even tho it returns an error, the other ajax event is still executing(reserveroom.php). sorry for my grammar, here's my code
$('#submitreserve').click(function(){
var error=false;
var inputtimeerror = false;
var conflict = false;
var message="";
var to="";
var from="";
var fromH="";
var fromM="";
var toH="";
var toM="";
var now = new Date();
if($("#datetimepicker").val()=="" || $("#trtitle").val()=="" || $("#from").val()=="" || $("#to").val()=="")
{
error = true;
message ="Please Fill all required Fields!";
}
if($("#from").val()!="" && $("#to").val()!="")
{
from = $("#from").val(); // start time
to = $("#to").val(); // end time
fromH = from.substr(0,2); // get hour from start time
fromM = from.substr(3,2); // get mins from start time
toH = to.substr(0,2); // get hour from end time
toM = to.substr(3,2); // get mins from end time
var timeerror = false;
var inputDate = $("#datetimepicker").val(); // date
inputFrom = new Date(inputDate+" "+from); // time and start date
inputTo = new Date(inputDate+" "+to); // time and end date
if(fromH > toH)
{
timeerror=true;
}
if(fromH == toH && fromM >= toM)
{
timeerror=true;
}
if(to == from)
{
timeerror=true;
}
if(inputFrom <= now || inputTo <= now)
{
inputtimeerror = true;
}
if(error == false && inputtimeerror == false)
{
$.ajax({
type:'post',
url: 'timeconflict.php',
data: { startTime : from,
endTime : to,
inputDate : inputDate,
room : target },
dataType: 'json',
success : function(e)
{
if (e.length == 0)
{
console.log("No value returned");
}
else
{
console.log(e[0]);
console.log("Conflict time schedule!");
conflict = true;
error=true;
alert("Conflict");
return false;
}
}
});
}
if(inputtimeerror)
{
error=true;
message = "Reservation time must be higher than time today!";
}
if(conflict)
{
error = true;
message = "Conflict Time Schedule!";
}
if(timeerror)
{
message = "Invalid End Time!";
error=true;
}
}
if(error==true)
{
$("#error").text(message);
return false;
}
if(error==false)
{
$.ajax({
type:'post',
url: 'reserveroom.php',
data: { trtitle : $("#trtitle").val(),
from : $("#from").val(),
to : $("#to").val(),
datetimepicker : $("#datetimepicker").val(),
ninjaday : $("#ninjaday").val(),
ninjaroom : $("#ninjaroom").val() },
dataType: 'json'
});
}
});
//timeconflict.php
<?php
include ('../conn.php');
// header("Content-Type: application/json");
$start_time = $_POST['startTime'];
$end_time = $_POST['endTime'];
$res_date = $_POST['inputDate'];
$res_room = $_POST['room'];
$sql = "SELECT * from tdc_reservation where ( ((`reserve_start` BETWEEN '".$start_time."' and '".$end_time."')";
$sql.= " or (`reserve_end` BETWEEN '".$start_time."' and '".$end_time."' )) or";
$sql.= " (('".$start_time."' BETWEEN `reserve_start` and `reserve_end`) or ";
$sql.= " ('".$end_time."' BETWEEN `reserve_start` and `reserve_end`)) or ";
$sql.= " ((`reserve_start` = '".$start_time."' ) or (`reserve_end`='".$start_time."' ))";
$sql.= " or ((`reserve_start` = '".$end_time."') or (`reserve_end` = '".$end_time."')) )";
$sql.= " and reserve_date='".$res_date."' and reserve_room = '".$res_room."' LIMIT 1 ";
$result = mysql_query($sql,$con);
$stack = array();
while($row = mysql_fetch_array($result))
{
$stack[] = $row;
}
$json = json_encode($stack);
mysql_close();
echo $json;
?>
I really hope someone would help me, this error already ate 2 days of my life :(
Modified your code, hope this will work
$('#submitreserve').click(function(){
var message="";
var to="";
var from="";
var fromH="";
var fromM="";
var toH="";
var toM="";
var now = new Date();
if($("#datetimepicker").val()=="" || $("#trtitle").val()=="" || $("#from").val()=="" || $("#to").val()=="")
{
message ="Please Fill all required Fields!";
}else{
from = $("#from").val(); // start time
to = $("#to").val(); // end time
fromH = from.substr(0,2); // get hour from start time
fromM = from.substr(3,2); // get mins from start time
toH = to.substr(0,2); // get hour from end time
toM = to.substr(3,2); // get mins from end time
var inputDate = $("#datetimepicker").val(); // date
inputFrom = new Date(inputDate+" "+from); // time and start date
inputTo = new Date(inputDate+" "+to); // time and end date
if(fromH > toH || (fromH == toH && fromM >= toM) || to == from)
{
message = "Invalid End Time!";
}
else if(inputFrom <= now || inputTo <= now)
{
message = "Reservation time must be higher than time today!";
}else{
$.ajax({
type:'post',
url: 'timeconflict.php',
data: { startTime : from,
endTime : to,
inputDate : inputDate,
room : target },
dataType: 'json',
success : function(e)
{
if (e.length == 0)
{
console.log("No value returned");
reserveRoom();
}
else
{
console.log(e[0]);
console.log("Conflict time schedule!");
alert("Conflict");
return false;
}
}
});
}
}
alert(message);
});
function reserveRoom(){
$.ajax({
type:'post',
url: 'reserveroom.php',
data: { trtitle : $("#trtitle").val(),
from : $("#from").val(),
to : $("#to").val(),
datetimepicker : $("#datetimepicker").val(),
ninjaday : $("#ninjaday").val(),
ninjaroom : $("#ninjaroom").val() },
dataType: 'json'
});
}

PHP - Sent one value in looping to AJAX / JQuery

I'm having problem to sent only one echo = 'true_user' back to jquery. Right now, the true_user will sent back to jquery based on $id that user have selected.
Second, how to combine when echo ='false' and echo ='failed' are sent back to jquery? I tried to use || and still not working.
jQuery / AJAX
<script>
jQuery(document).ready(function(){
jQuery("#delete_user").submit(function(e){
e.preventDefault();
var formData = jQuery(this).serialize();
$.ajax({
type: "POST",
url: "delete_users.php",
data: formData,
success: function(html){
if (html=='false_user'){
$.jGrowl("Please select user", { header: 'Error' });
alert(html);
}else if (html=='failed'){
$.jGrowl("Cannot delete your own account", { header: 'Account Protected' });
alert(html);
var delay = 1000;
setTimeout(function(){ window.location = 'admin_user.php' }, delay);
}else if(html=='true'){
$.jGrowl("Loading Please Wait......", { sticky: true });
$.jGrowl("Successfully Deleted", { header: 'User Deleted' });
alert(html);
var delay = 1000;
setTimeout(function(){ window.location = 'admin_user.php' }, delay);
}else if (html=='true_user'){
$.jGrowl("Loading Please Wait......", { sticky: true });
$.jGrowl("Successfully Deleted", { header: 'Users Deleted' });
alert(html);
var delay = 1000;
setTimeout(function(){ window.location = 'admin_user.php' }, delay);
}else if (html=='false','failed'){
$.jGrowl("Cannot delete your own account", { header: 'Account Protected' });
alert(html);
var delay = 1000;
setTimeout(function(){ window.location = 'admin_user.php' }, delay);
}else{
$.jGrowl("Please try again", { header: 'Error' });
alert(html);
var delay = 1000;
setTimeout(function(){ window.location = 'admin_user.php' }, delay);
}
}//success
});
return false;
});
});
</script>
delete_users.php
<?php
error_reporting(E_ALL&~E_NOTICE);
include('dbcon.php');
include('session.php');
//if (isset($_POST['delete_user'])){
$id=$_POST['selector'];
//$id = array(61);
$N = count($id);
if ($N == 0){ //if no selected
echo 'false_user';
} else { //if selected
for($i=0; $i < $N; $i++)
{
$stmt = $conn->prepare("select * from users WHERE user_id=:id");
$stmt->bindParam(':id',$id[$i]);
$stmt->execute();
$result = $stmt->fetchObject();
$userType = $result->user_type;
//$user_type = $row['user_type']
if ($userType >= 1){ //if user type not 0 = developer
if ($id[$i] == $session_id){ // cannot delete own account
echo 'failed';
} else if($N==1){
$stmt = $conn->prepare("DELETE FROM users where user_id=:id");
$stmt->bindParam(':id',$id[$i]);
$stmt->execute();
$stmt->rowCount();
echo 'true';
} else if ($N > 1){ // if select more than one
$stmt = $conn->prepare("DELETE FROM users where user_id=:id");
$stmt->bindParam(':id',$id[$i]);
$stmt->execute();
$stmt->rowCount();
$testing = 'true_user';
//return;
}
}else{ //other error
echo 'false';
}
}
}
?>

POST variables to model is not working in php codeigniter by using return in success

I tried the following code:
function doAjax() {
var sList = "";
$('input[type=checkbox]').each(function () {
var sThisVal = (this.checked ? "1" : "0");
sList += (sList=="" ? sThisVal : "," + sThisVal);
});
$.ajax({
url: "UserRights/update_rights",
type: "POST",
data:{ X : sList},
success: function(data) {
// alert("Success:"+data);
return data;
}
});
};
In model:
function update_userright()
{
if(!empty($_POST['X']))
{
if(isset($_POST['X']))
{
$checkbox_list =$this->input->post('X');
echo "Posted".$checkbox_list;
}
}
else
{
echo "Nothing";
/* $active=$this->input->post('menulist');
echo "Posted values .$active";
$sql= $this->db->query("UPDATE UserRightsNew SET Active='$active' WHERE UserCode='$default_usercode'; "); */
}
}
When i tried with alert message the values are posted but the return(data) is not working ... anybody guide me?
I think you have error in JavaScript. Try this.
function doAjax() {
var sList = sThisVal = "";
$('input[type=checkbox]').each(function () {
sThisVal = (this.checked ? "1" : "0");
sList += (sList=="" ? sThisVal : "," + sThisVal);
});
var result = '';
$.ajax({
url: "UserRights/update_rights",
type: "POST",
data:{ X : sList},
dataType: "html",
success: function(data) {
alert("Success: "+data);
result = data;
}, error: function(e){
alert(e); //To show errors
}
});
return result;
}
MODEL
update_userright(); //make sure to execute the function
function update_userright()
{
if(!empty($_POST['X']))
{
if(isset($_POST['X']))
{
$checkbox_list =$this->input->post('X');
echo "Posted".$checkbox_list;
}
}
else
{
echo "Nothing";
/* $active=$this->input->post('menulist');
echo "Posted values .$active";
$sql= $this->db->query("UPDATE UserRightsNew SET Active='$active' WHERE UserCode='$default_usercode'; "); */
}
}

Categories

Resources