What I am trying to do is check my CodeIgniter every 2 seconds to see if the session is still alive. But for some reason when I use the following code I get this error:
"Uncaught SyntaxError: Unexpected Token ;"
Any ideas as to why this is happening?
Javascript:
setInterval(function() {
$.getJSON("<?=base_url()?>index.php/regUserDash/sessionExpire"), function(data) {
var sessionState = jQuery.parseJSON('{"sessionExpired":"true","sessionExpired":"false"}');
if(sessionState.sessionExpired === "true") {
alert('expired');
} else if(sessionState.sessionExpired == "false") {
alert('not expired');
}
});
}, 2000);
Ci code:
public function sessionExpire() {
if ($this->session->userdata("logged") == "1") {
echo json_encode(array("sessionExpired" => false));
} elseif($this->session->userdata("logged") == "0") {
echo json_encode(array("sessionExpire" => true));
}
}
You had an extra parenthesis here:
$.getJSON("<?=base_url()?>index.php/regUserDash/sessionExpire") // <--
This should work:
setInterval(function() {
$.getJSON("<?=base_url()?>index.php/regUserDash/sessionExpire", function(data) {
var sessionState = $.parseJSON('{"sessionExpired":"true","sessionExpired":"false"}');
if (sessionState.sessionExpired === "true") {
alert('expired');
} else if (sessionState.sessionExpired == "false") {
alert('not expired');
}
});
}, 2000);
Related
How can I pause submission so that I can validate, check values, and possibly submit an xhtml callout based on the choices all before allowing the form to finally submit?
Have tried using various jquery methods found on here, using callbacks, setting timeouts, and holding in a while loop until everything's done. A lot of the alerts found in the code are only for troubleshooting/tracing purposes.
function completeTicket() {
alert("fnOpenDiag Called");
$("#dialog-confirm").html("Auto create return eTicket?");
// Define the Dialog and its properties.
$("#dialog-confirm").dialog({
resizable: false,
modal: true,
title: "Auto create return eTicket?",
height: 250,
width: 400,
buttons: {
"Yes": function () {
var quickissue = "Return <?php echo ($ticketRow['items_count'] >= 1 ? $ticketRow['items'] : 'Computer'); ?>";
var selectedLocation2 = <?php echo ($ticketRow['Location_ID'] == '' ? 0 : $ticketRow['Location_ID']); ?>;
xmlhttp=GetXmlHttpObject();
if (xmlhttp==null) {
alert ("This browser does not support XMLHTTP!");
}
var url="xhtmlCallOut_QuickEticket.php?callerID=pc_ticket_detail&selectedLocation_ID=" + selectedLocation2 + "&tboxIssue=" + quickissue;
xmlhttp.open("GET",url,false);
xmlhttp.send(null);
if (xmlhttp.readyState==4){
if (xmlhttp.responseText != 0){
alert(xmlhttp.responseText);
}
}
alert("ticket success");
return true;
$(this).dialog('close');
//callback(true);
//callback();
},
"No": function () {
return true;
$(this).dialog('close');
//callback(false);
//callback();
}
}
});
}
function checkForm() {
alert("checkform called");
if(document.getElementById('assocCompany').selectedIndex == 0) {
alert('Please associte this company with a known company name\nfrom the drop list.');
document.getElementById('assocCompany').focus();
e.preventDefault();
return false;
}
else if(document.getElementById('assignTech').selectedIndex == 0 && document.getElementById('status').selectedIndex >= 2){
alert('You must define a technician first!');
document.getElementById('assignTech').focus();
e.preventDefault();
return false;
}
else if(RegisterForm.elements['status'].value == 3 && RegisterForm.elements['tboxreaspend'].value.length < 3){
alert('You must give a reason for this ticket being changed to pending');
document.getElementById('tboxreaspend').focus();
e.preventDefault();
return false;
}
else if(RegisterForm.elements['tboxissue'].value.length < 3){
alert('You must give a description of the issue');
document.getElementById('tboxissue').focus();
e.preventDefault();
return false;
}
else {
pc_ticketdetail.actionbutton.disabled=true;
return false;
}
}
function showPendingReason() {
var y = document.getElementById("status");
var val = y.options[y.selectedIndex].value;
if (val == 3) {
$('#trReasPend').show();
} else {
$('#trReasPend').hide();
}
}
function submitForm() {
alert("submitform called");
var x = document.getElementById("status");
var valx = x.options[x.selectedIndex].value;
alert("statval is " + valx);
if (valx == 4) {
if (completeTicket()) {
e.preventDefault();
return false;
alert("complete ticket done");
} else {
e.preventDefault();
return false;
}
} else {
if (checkForm()) {
e.preventDefault();
return false;
alert("checkform done");
} else {
alert("checkform FALSE return");
e.preventDefault();
return false;
}
}
}
<div id="dialog-confirm"></div>
<form action="<?php $_SERVER['PHP_SELF']; ?>" name="pc_ticketdetail" id="pc_ticketdetail" method="post" onSubmit="return submitForm();">
<select name="status" id="status" onChange="javascript:showPendingReason();">
<option<?php if($ticketRow['status'] == 1){ echo ' selected'; } ?> value="1">New</option>
<option<?php if($ticketRow['status'] == 2){ echo ' selected'; } ?> value="2">Bench</option>
<option<?php if($ticketRow['status'] == 3){ echo ' selected'; } ?> value="3">Pending</option>
<option<?php if($ticketRow['status'] == 4){ echo ' selected'; } ?> value="4">Finished</option>
<?php if($ticketRow['status'] == 5){
echo '<option selected value="5">Closed/Deleted</option>';
} ?>
</select>
It currently seems to step through as expected except the "completeTicket" and "checkForm" functions are either not being called or not returning correctly. The form simply submits and closes when they should fail validation or open the modal dialogue and ask to create return ticket.
Take a look on the (async - await) function in javaScript.
async function
your checkForm() never return false so is your completeTicket() never return true. you can initially define a variable as false and make it true if it meets a specific condition then return the variable to the main function.
<script>
function c(){
let isTrue = false;
if(condition){
isTrue = true;
}
return isTrue;
}
function d(){
if(c()){
alert("c returned true");
} else{
alert("c returned false");
}
}
</script>
If you remove the alerts from under the return statements, that would help you in tracing the problem, because no code will run after you return from a function. Same thing for $(this).dialog('close').
And I think that you should capture the event object before using it in e.preventDefault() so try to remove the onSubmit attribute from the form and adding the listener through jQuery like so :
$(YOUR_FORM_SELECTOR).submit(function(e) {
// here you access to the e Object
})
I don't know if that related to the problem you have, Try describing what's happening exactly when you run the code.
I am using Spring MVC, Following is a method which will take either String or Input Stream from the Request and convert into PDF and write the PDF to the respose.
public void generatePDF(RequestDTO requestUIDTO, Map<String, Object> responseMap,
HttpServletRequest request, HttpSession session, HttpServletResponse response) {
Document document = new Document();
PdfWriter writer;
try {
writer = PdfWriter.getInstance(document, response.getOutputStream());
document.open();
//Here I need to get the HTML file as String or InputStream from the request.
//For now i am getting InputStream, It may be string
InputStream in = request.getInputStream();
XMLWorkerHelper.getInstance().parseXHtml(writer, document, in);
document.close();
} catch (DocumentException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Now the problem is, I don't know how to send the current rendered page as HTML to the server, I tried the following Java script but it is not working, the request itself is not going to the server May be because i am sending a huge file as request parameter.
function downloadLoanForm(){
var params = {};
params = {
htmlContent : "htmlContent"
}
handleRequest(this, params, 'generatePDF.htm', '');
}
$(document).ready(function(){
var htmlContent = $('#mainFormId').html();
$('#htmlContent').val(htmlContent);
});
My Question is this, Please let me know a way to send the current rendered HTML code to the Server as either a String (or) Stream.
Here is the Java script code for handleRequest() function,
function handleRequest(obj, params, request_url, replacement_element_id,
error_redirection, function_call_after_response) {
//check if there is any value present for the request url
if(!request_url)
{
alert('<spring:message code="JS_MSG_PROVIDE_URL_FOR_REQUEST" text=""/>');
return false;
}
//check if the url is an external url
if(isExternal(request_url) === true)
{
alert('<spring:message code="JS_MSG_REQUEST_CANNOT_SENT_TO_EXTERNAL_LINK" text=""/>');
return false;
}
//global variable for making the decision on the page redirect after the error from the server - default value is false
error_redirection = error_redirection || false;
//variable containing the replacement element id which will be used to place the content after the response from the server
replacement_element_id = replacement_element_id || false;
//variable to decide whether some manipulation has to be done on the response data from the server
// the response data is being sent to this function along with the replacement element id
function_call_after_response = function_call_after_response || '';
//alert(function_call_after_response+'-here');
//set the replacement element's html values to to be empty before the request is being made so as to ensure that user does not go forward without getting the correct result
if(replacement_element_id)
{
$('#'+replacement_element_id).html("");
}
//var serializedData = Array();
var counter = 0;
//SETTING THE REQUIRED ELEMENTS VALUES TO AN JSON OBJECT FOR SENDING TO THE SERVER - the elements required for the post is passed as an array in the arguments
var serializedData = {};
$.each(params, function(key, field) {
if($("#"+key).length > 0) {
//field = escapeHtml(field);
var value = $("#"+key).val();
/*if($('input[name="'+field+'"]').length > 0)
{
value = $('input[name="'+field+'"]').val();
}
else if($('select[name="'+field+'"]').length > 0)
{
value = $('select[name="'+field+'"]').val();
}
else if($('textarea[name="'+field+'"]').length > 0)
{
value = $('textarea[name="'+field+'"]').val();
}*/
value = escapeHtml(value);
if(value != "")
{
counter++;
}
//serializedData.field = value;
serializedData[field] = value;
/*
if(counter == 0)
{
serializedData = field+'='+value;
}
else
{
serializedData += '&'+field+'='+value;
}
counter++;
*/
}
});
if(counter == 0)
{
return false;
}
serializedData.csrfToken = $('form > input[name=csrfToken]').val();
//alert($('form > input[name=csrfToken]').val());
if(isExternal(request_url) === false)
{
$('input[name="'+$(obj).attr('name')+'"]').css('float', 'left');
$.blockUI({ message: "<h3><img src='images/processing.gif' id='processing_plz_wait' alt='Processing...' title='Processing...' border='0' class='processing_img' /><br/><spring:message code="JS_MSG_PLEASE_WAIT" text=""/></h3>" });
$(".blockOverlay").show();
$(".blockOverlay").css("opacity", "0.6");
$(".blockMsg").show();
$(".blockMsg").css("opacity", "1");
//setTimeout(function() {
$.ajax({
type: "POST",
url: request_url,
data: serializedData,
success: function(data, status, xhr) {
if(data) {
//check for some strings to validate session time out - TODO need proper validation check
if(data.contains("<html>") && data.contains("<head>")){
document.location.href = 'logout.htm';
} else {
if(replacement_element_id === false) {
alert('<spring:message code="JS_MSG_OPERATION_PERFORMED_SUCCESSFULLY" text=""/>');
return false;
}
else {
//set the response from the server to the form display element
$('#'+replacement_element_id).html(data);
setTokenValFrmAjaxResp();
$('#'+replacement_element_id).find("form ").append('<input type="hidden" value="'+$('#csrfToken').val()+'" name="csrfToken">');
$('form > input[name=csrfToken]').val($('#csrfToken').val());
if(function_call_after_response != "")
{
eval(function_call_after_response);
}
return false;
}
}
}
},
//ERROR HANDLING AS PER THE RESPONSE FROM THE SERVER - TO DO (some extra layer of error handling to be done)
error: function(jqXHR, exception) {
if (jqXHR.status === 0) {
alert('<spring:message code="JS_MSG_NOT_ABLE_TO_CONNECT_VERIFY_NETWORK" text=""/>');
} else if (jqXHR.status == 404) {
alert('<spring:message code="JS_MSG_REQUEST_PAGE_NOT_FOUND" text=""/>');
} else if (jqXHR.status == 500) {
alert('<spring:message code="JS_MSG_INTERNAL_SERVER_ERROR" text=""/>');
} else if (exception === 'parsererror') {
alert('<spring:message code="JS_MSG_REQUESTED_DATA_PARSE_FAILED" text=""/>');
} else if (exception === 'timeout') {
alert('<spring:message code="JS_MSG_TOME_OUT_ERROR" text=""/>');
} else if (exception === 'abort') {
alert('<spring:message code="JS_MSG_AJAX_REQUEST_ABORTED" text=""/>');
} else {
alert('<spring:message code="JS_MSG_UNCAUGHT_ERROR" text=""/>' + jqXHR.responseText);
if(error_redirection === true)
{
//redirect to the corresponding error page
document.location.href = '';
}
}
setTokenValFrmAjaxResp();
return false;
}
});
//}, 100);
}
}
I have set 2 min for session timeout and if it occurred the page
will redirect to a session timeout page.
However, I have some pages that could be browsed without login.
In these pages, if I leave it more than 2 min, pop out will appear asking user to log in again. User will go back to click it and it will redirect to session timeout page.
Could anyone teach me, how to get rid of this such that the pages be browsed without login should not occur session time?
ajax.js
window.onload = init;
var interval;
function init() {
interval = setInterval(trackLogin, 1000);
}
function trackLogin() {
var xmlReq = false;
try {
xmlReq = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlReq = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e2) {
xmlReq = false;
}
}
if (!xmlReq && typeof XMLHttpRequest != 'undefined') {
xmlReq = new XMLHttpRequest();
}
xmlReq.open('get', 'check.php', true);
xmlReq.setRequestHeader("Connection", "close");
xmlReq.send(null);
xmlReq.onreadystatechange = function() {
if (xmlReq.readyState == 4 && xmlReq.status == 200) {
if (xmlReq.responseText == 1) {
clearInterval(interval);
alert('You have been logged out. You will now be redirected to home page.');
document.location.href = "index.php";
}
}
}
}
firstSession
<?php
// session_start ();
if (! isset ( $_SESSION ["isLoggedIn"] ) || ! ($_SESSION ['isLoggedIn'])) {
// code for authentication comes here
// ASSUME USER IS VALID
$_SESSION ['isLoggedIn'] = true;
$_SESSION ['timeOut'] = 120;
$logged = time ();
$_SESSION ['loggedAt'] = $logged;
// showLoggedIn ();
} else {
require 'timeCheck.php';
$hasSessionExpired = checkIfTimedOut ();
if ($hasSessionExpired) {
session_unset ();
header ( "Location:index.php" );
exit ();
} else {
$_SESSION ['loggedAt'] = time ();
}
}
?>
footer.php
<?php include ('includes/firstSession.php'); ?>
<footer class="main">
<div class="wrapper container">
<div class="copyright">All Rights Reserved
</div>
<div class="logo"><img src="images/logo.png"></div>
</footer>
</div>
draft ajax.js
window.onload = init;
var interval;
function init() {
interval = setInterval(trackLogin, 1000);
}
function trackLogin() {
var xmlReq = false;
try {
xmlReq = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlReq = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e2) {
xmlReq = false;
}
}
if (!xmlReq && typeof XMLHttpRequest != 'undefined') {
xmlReq = new XMLHttpRequest();
}
xmlReq.open('get', 'check.php', true);
xmlReq.setRequestHeader("Connection", "close");
xmlReq.send(null);
xmlReq.onreadystatechange = function() {
if (xmlReq.readyState == 4 && xmlReq.status == 200) {
return json_encode(array(
'role' => $_SESSION['role'], //assuming something like guest/logged-in
'user_id' => $_SESSION['user_id']
));
var obj = xmlReq.responseText;
var jsonObj = JSON.parse(obj);
//now we can make a comparison against our keys 'role' and 'user_id'
if(jsonObj['role'] == 'guest'){
//guest role, do something here
} else if (jsonObj['role'] == 'logged-in') {
alert('You have been logged out. You will now be redirected to home page.');
document.location.href = "index.php";
//do something else for logged in users
}
I think since you have a session that is persistent whether logged in or not, you need to base your action on the username (however that is set). See if this is what you are trying to do. I have notated for clarity:
myfunctions.php
<?php
// return a session set on not set OR false if set
function is_loggedin()
{
return (!empty($_SESSION["isLoggedIn"]));
}
// Check if username is set (not sure how your usernames are stored in your session
// but that is what you want to check here
function user_set()
{
return (!empty($_SESSION["username"]));
}
// Do your set time function
function set_time_out($timeout = 120)
{
$_SESSION['isLoggedIn'] = true;
$_SESSION['timeOut'] = (is_numeric($timeout))? $timeout : 120;
$_SESSION['loggedAt'] = time();
}
function process_timeout($supRed = false)
{
// If a user has NOT already been poking around your site
if(!is_loggedin()) {
// Set the timeout
set_time_out();
return 0;
}
else {
// If a navigating user is logged in
if(user_set()) {
// Check for expire time
require('timeCheck.php');
// If they have been timed out
if(checkIfTimedOut()) {
if(!$supRed) {
// destroy the session and forward to login (or wherever)
session_destroy();
header("Location:index.php" );
exit();
}
return 1;
}
}
// Set the logged time by default
$_SESSION['loggedAt'] = time();
}
return 0;
}
header.php
<?php
include_once("includes/firstSession.php");
include_once("includes/myfunctions.php");
process_timeout();
?><!DOCTYPE html>
...etc
check.php
<?php
include_once("includes/firstSession.php");
include_once("includes/myfunctions.php");
echo process_timeout(true);
EDIT:
This is the entire script, both js and php.
// return a session set on not set OR false if set
function is_loggedin()
{
return (!empty($_SESSION["isLoggedIn"]));
}
// Check if username is set (not sure how your usernames are stored in your session
// but that is what you want to check here
function user_set()
{
return (!empty($_SESSION["username"]));
}
// Do your set time function
function set_time_out($timeout = 120)
{
$_SESSION['isLoggedIn'] = true;
$_SESSION['timeOut'] = (is_numeric($timeout))? $timeout : 120;
$_SESSION['loggedAt'] = time();
}
function checkIfTimedOut()
{
if(!empty($_SESSION['loggedAt'])) {
$active = ($_SESSION['loggedAt'] + strtotime("120 seconds"));
$now = time();
return (($active - $now) > 0);
}
return true;
}
function process_timeout($supRed = false)
{
// If a user has NOT already been poking around your site
if(!is_loggedin()) {
// Set the timeout
set_time_out();
return 0;
}
else {
// If a navigating user is logged in
if(user_set()) {
// Check for expire time
// If they have been timed out
if(checkIfTimedOut()) {
// destroy the session
session_destroy();
if(!$supRed) {
// Forward to login (or wherever)
header("Location:index.php" );
exit();
}
return 1;
}
}
// Set the logged time by default
$_SESSION['loggedAt'] = time();
}
return 0;
}
check.php:
// Include the functions here
if(!empty($_POST['getPost'])) {
echo json_encode(array("redirect"=>process_timeout(true),"sess"=>$_SESSION));
exit;
}
CALLING PAGE:
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript" src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
<script>
function init()
{
interval = setInterval(trackLogin, 2000);
}
function trackLogin()
{
$.ajax({
url: '/check.php',
data: { getPost: true },
type: 'post',
success: function(response) {
var instr = JSON.parse(response);
console.log(response);
if(instr.redirect == 1) {
clearInterval(interval);
alert('You have been logged out. You will now be redirected to home page.');
document.location.href = "index.php";
}
}
});
}
$(document).ready(function() {
var interval;
init();
});
</script>
EDITED
I know the title is very annoying but anyways I start my question. I have created a function in a class that's kinda a multi-purpose one. I gave it a parameter which is of boolean type and of course only accepts "true" and "false" as values. Next, I am calling out that function through another PHP file on which the data is posted through ajax and that ajax is called through a button on my HTML page. Let me demonstrate it as a diagram:
I hope you've understood my program flow, now let's come to the code or in other words here is what I've tried:
HTML Page's button:
document.write('<span class="pull-right" style="margin-top: -30px; margin-right: 20px;"><button id="accept_offer" class="btn btn-success" onclick="setPostOfferAcceptance(32);">Accept Offer</button></span>');
AJAX Page:
<?php
require_once '../../Classes/MyClass.php';
$offer_id = $_POST["id"];
$acceptance = $_POST["acceptance"];
$accepted = MyClass::SetOfferAcceptance($offer_id, $acceptance);
if($accepted) $data["status"] = "success";
else $data["status"] = "error";
echo json_encode($data);
?>
MyClass's Function:
public static function SetOfferAcceptance($offerId, $acceptance) {
if(Utilities::IsValid($offerId) && Utilities::IsValid($acceptance)) {
Database::OpenConnection();
$offerId = Utilities::SafeString(Database::$databaseConnection, $offerId);
$acceptance = Utilities::SafeString(Database::$databaseConnection, $acceptance);
$query = "";
if($acceptance == true) {
$query = Database::$databaseConnection->prepare("UPDATE post_offer SET Accepted=1 WHERE Offer_ID = ?");
} else {
$query = Database::$databaseConnection->prepare("UPDATE post_offer SET Accepted=0 WHERE Offer_ID = ?");
}
$query->bind_param("i", $offerId);
$result = $query->execute();
Database::CloseConnection();
if($result) return 1; else return -1;
}
}
And sorry, but finally, here's my javascript function that posts the data to the AJAX page:
function setPostOfferAcceptance(offer_id) {
if($("#accept_offer").text() == "Accept Offer") {
$.post("admin/post_offer/set_post_offer_acceptance.php", {id: offer_id, acceptance: true}, function(data){
if(data.status == "success") {
$("#acceptedOfferModal").modal("show");
setTimeout(function(){ $("#acceptedOfferModal").modal("hide"); }, 2500);
$("#accept_offer").text("Unaccept Offer");
console.log(data.status);
}
}, 'json');
} else if($("#accept_offer").text() == "Unaccept Offer") {
$.post("admin/post_offer/set_post_offer_acceptance.php", {id: offer_id, acceptance: false}, function(data){
if(data.status == "success") {
$("#unacceptedOfferModal").modal("show");
setTimeout(function(){ $("#unacceptedOfferModal").modal("hide"); }, 2500);
$("#accept_offer").text("Accept Offer");
console.log(data.status);
}
}, 'json');
}
}
EDIT: I forgot to post the JS code. But I've updated it now. Please consider it. Thanks.
The problem is that the function SetOfferAcceptance() is never running the else condition which is that if $acceptance is not equal to true.
Why? Can anyone please point out my mistake.
Thanks.
If acceptance is boolean then use the following if...else, i.e. with tripple equals $acceptance === true:
// In AJAX page
if ($acceptance === true) {
$query = Database::$databaseConnection->prepare("UPDATE post_offer SET Accepted=1 WHERE Offer_ID = ?");
} else {
$query = Database::$databaseConnection->prepare("UPDATE post_offer SET Accepted=0 WHERE Offer_ID = ?");
}
Please reference: "How do the equality (== double equals) and identity (=== triple equals) comparison operators differ?"
Update:
Either check for $acceptance value in SetOfferAcceptace, or pass in boolean value to SetOfferAcceptance. Example with latter:
$offer_id = $_POST["id"];
$acceptance = false;
if (isset($_POST["acceptance"]) && $_POST["acceptance"] == 'accepted') {
$acceptance = true;
}
$accepted = MyClass::SetOfferAcceptance($offer_id, $acceptance);
Thanks you all for your answers but I figured out another alternative. That was instead of making $acceptance a boolean I made it a string and converted my JS code into:
function setPostOfferAcceptance(offer_id) {
if($("#accept_offer").text() == "Accept Offer") {
$.post("admin/post_offer/set_post_offer_acceptance.php", {id: offer_id, acceptance: "accepted"}, function(data){
if(data.status == "success") {
$("#acceptedOfferModal").modal("show");
setTimeout(function(){ $("#acceptedOfferModal").modal("hide"); }, 2500);
$("#accept_offer").text("Unaccept Offer");
console.log(data.status);
}
}, 'json');
} else if($("#accept_offer").text() == "Unaccept Offer") {
$.post("admin/post_offer/set_post_offer_acceptance.php", {id: offer_id, acceptance: "unaccepted"}, function(data){
if(data.status == "success") {
$("#unacceptedOfferModal").modal("show");
setTimeout(function(){ $("#unacceptedOfferModal").modal("hide"); }, 2500);
$("#accept_offer").text("Accept Offer");
console.log(data.status);
}
}, 'json');
}
}
And my class's function into:
public static function SetOfferAcceptance($offerId, $acceptance) {
if(Utilities::IsValid($offerId) && Utilities::IsValid($acceptance)) {
Database::OpenConnection();
$offerId = Utilities::SafeString(Database::$databaseConnection, $offerId);
$acceptance = Utilities::SafeString(Database::$databaseConnection, $acceptance);
$query = "";
if($acceptance == "accepted") {
$query = Database::$databaseConnection->prepare("UPDATE post_offer SET Accepted=1 WHERE Offer_ID = ?");
} else {
$query = Database::$databaseConnection->prepare("UPDATE post_offer SET Accepted=0 WHERE Offer_ID = ?");
}
$query->bind_param("i", $offerId);
$result = $query->execute();
Database::CloseConnection();
if($result) return 1; else return -1;
}
}
And that worked! :)
Thanks again #vee.
If I am not mistaken your issue stems from automatic type casting.
if($result) return 1; else return -1; // both of these evaluate to boolean true because -1 is an integer
if($result) return 1; else return 0; // evaluates to true/false respectively
if($result) return true; else return false; // evaluates to true/false respectively
The last line is what you should honestly be using.
I have PHP and JS script for uploading image. PHP file returns a var err:type and I'm checking in JS if return == err:type, but it doesn't work.
$(document).ready
(
function()
{
$('#avatar_image_upload_form').submit
(
function()
{
$('div#avatar_ajax_upload_demo img').attr('src','../../Files/Border/loading.gif');
}
);
$('iframe[name=avatar_upload_to]').load(
function()
{
var result = $(this).contents().text();
if(result !='')
{
$('div#avatar_ajax_upload_demo img').attr('src',result);
if(result == 'err:size')
{
$('div#avatar_ajax_upload_demo img').attr('src','../../Files/Border/avatar_big.jpg');
}
if (result == 'err:type')
{
$('div#avatar_ajax_upload_demo img').attr('src','../../Files/Border/avatar_invalid.jpg');
}
}
}
);
}
);
if(result == 'err:type') doesn't work, but result = "err:type"
According to this image:
There are a lot of white lines at the beginning of the string. You need to trim the result string to remove them:
var result = $(this).contents().text().trim();
You should best fix your PHP code in order not to send those blank lines.
[WRONG]
Maybe your error is here : (if avatar_upload_to isn't a variable)
$('iframe[name=avatar_upload_to]').load(
Should be
$('iframe[name="avatar_upload_to"]').load(
=====
[TEST]
What appends if you make this :
$('iframe[name=avatar_upload_to]').load(
function()
{
var result = $(this).contents().text();
console.log(result);
//or
alert(':'+result+':');
if(result !='')
{
$('div#avatar_ajax_upload_demo img').attr('src',result);
if(result == 'err:size')
{
$('div#avatar_ajax_upload_demo img').attr('src','../../Files/Border/avatar_big.jpg');
}
if (result == 'err:type')
{
$('div#avatar_ajax_upload_demo img').attr('src','../../Files/Border/avatar_invalid.jpg');
}
}
}
);