Use data from JQuery .get function in an Else If statement - javascript

I am running a simple .get statement with JQuery:
$.get("check.php", function(data)
{
if (data == "yes")
{
$('#thisimg').attr('src' ,'yes.jpg');
}
else
{
$('#thisimg').attr('src' ,'no.jpg');
}
});
When I call an alert with data as the parameter it returns "yes", however the if statement is still not running and changing the images src.
This is my check.php file:
<?php
//connect to db here
//run sql select statement to check whether or not the value is 0 or 1
//value is saved into variable $selected, and the value is 1
if ($selected == 1)
{
echo "yes";
}
else
{
echo "no";
}
?>

Oftentimes there will be an invisible character in returned data. If you .trim data it should work:
if (data.trim() == "yes")
{
$('#thisimg').attr('src' ,'yes.jpg');
}
else
{
$('#thisimg').attr('src' ,'no.jpg');
}

Related

Redirect page if I hit back button, in the web browser?

I have an "Exam form" in PAGE A, that if submitted writes data into the database, and then redirect to PAGE B.
My problem is that, if I hit back button in PAGE B. It goes back to PAGE A, where I can again submit form and it again writes into the database.
What is the best method to block this back button issue ?
Could I redirect to some other page ?
I am looking for javascript method or php based solution is would be better. SQL based solution is messy.
Note: In SQL database, Primary key is an autogenerated id. I am using a general method save(), to write all data into the db. which basicaly collect all data from the form make it into an object and write it into db. Its a general method that I use in many other forms in the project. I would like to not touch that.
I tried fetching 'apno' & 'qid' from database and compare it while posting second time.
<?php
$j = 1;
foreach ($allquestions as $questions)
{
if (is_post_request())
{
$args = $_POST['answers' . $j];
$check_if_submited = Answers::find_by_objapno($apno);
foreach ($args as $key => $value)
{
if ($key == "qid")
{
$qid = $value;
}
}
if ($check_if_submited->apno == $apno && $check_if_submited->qid == $qid)
{
$session->message('Not Saved. Exam Already Taken.');
redirect_to(url_for('/user/student/showexams.php?id=' . $sid));
}
else
{
$answers = new Answers($args);
$result = $answers->save();
if ($result === true)
{
$answers->aid_create();
if ($j < $qcount)
{
}
else
{
$session->message($j . ' Answers Saved.');
redirect_to(url_for('/user/student/showexams.php?id=' . $sid));
}
}
else
{
echo "Error";
}
}
}
else
{
$answers = new Answers;
}
}
?>
qid is not primary key. db could have multiple qid.
try the following code.
jQuery(document).ready(function($) {
if (window.history && window.history.pushState) {
$(window).on('popstate', function() {
var hashLocation = location.hash;
var hashSplit = hashLocation.split("#!/");
var hashName = hashSplit[1];
if (hashName !== '') {
var hash = window.location.hash;
if (hash === '') {
alert('Back button was pressed.');
window.location='www.example.com';
return false;
}
}
});
window.history.pushState('forward', null, './#forward');
}
});

Redirect to URL if input exists in database

I'm trying to redirect a user to an existing URL (stored in a MySQL database) if the value they input already exists in the database. I've got most of it working, but I've run into some issues.
I'm using AJAX to check the database. It sends the input value to another PHP file & checks the database to see if it already exists.
if($row) {
echo ".$row["itemNum"].";
} else {
}
It's within the AJAX code that I'm having issues, in particular this:
success: function (response) {
if (response == <?php ".$row["itemNum"]." ?>) {
window.location.href = "http://www.example.com/" <?php echo "+"; if (".$row["itemNum"].") { echo ".$row["itemNum"]." } else {""}
} else {
// do other stuff
}
}
$row["itemNum"] doesn't always exist, so it's in a conditional statement to prevent a syntax error.
The above doesn't work regardless of how I do it.
I have a feeling the main issue is with the if (response == <?php ".$row["itemNum"]." ?>) line?
Based on this code:-
if($row) {
echo $row["itemNum"]; // check the change here
} else {
}
You have to do like this:-
success: function (response) {
if (response !== '') { // if response have some value
window.location.href = "http://www.example.com/"+response;
} else {
// do other stuff
}
}
As you suspected you have problem with following line.
if (response == <?php ".$row["itemNum"]." ?>) {
The Problem is your use of (") and (.) characters
Following syntax will give you what you want.
if (response == <?=$row["itemNum"]?>) {

Cant make comparison with php echo output in javascript (jquery-post)

I enter password in password field, and send it from javascript to php, and compare it with the '123' key variable in php. So if it is true it echo outs true, otherwise false.
Then, in my javascript file at callback function field, the data can not be used in if statement. I dont know why.
However, when I just want to write data it writes true in my html file, but i cant make comparison with this 'true'
My javascript:
$.post('validation.php', { input: pass }, function(data) {
if ( data === "true")
{
// even if it is true, It skips here, goes else
}
else
{
}
});
My php file is:
<?php
$key = '123';
if (isset($_POST['input'])) {
$pass = $_POST['input'];
if ($pass === $key)
{
echo 'true';
}
else
{
echo 'false';
}
}
?>
you might need to trim the returned value when comparing it in your javascript:
...if(data.trim() === "true")...
or
var option = data.trim();
if(data.trim() === option)...
use the function localeCompare. for example:
data.localeCompare("true")

jQuery if statement broken?

I have a php webpage where a user enters their details into a form and after submitting two sections, named profile and images, must then appear. Here is the javascript code:
jQuery(document).ready(function($) {
var registered = <?php echo $registered; ?>;
alert(registered);
if (registered == 'false') {
$("#profile").hide();
$("#images").hide();
}
if (registered == 'true') {
alert('hello');
$("#profile").show();
$("#images").show();
}
});
For some reason it does not go into the if statement at all, even though the alert shows registered's value as true. What could be the problem here?
var registered = <?php json_encode($registered) ?>
if(registered == true) {
alert(registered);
$("#profile").hide();
$("#images").hide();
} else {
alert('hello');
$("#profile").show();
$("#images").show();
}
You are mixing up the string 'true' with the boolean true. Try a version that uses booleans from start to finish instead:
var registered = <?= json_encode($registered) ?>;
if (registered) {
$("#profile").hide();
$("#images").hide();
} else {
$("#profile").show();
$("#images").show();
}
Edit - Thanks to Jon in another comment for suggesting using json_encode.
use JSON.parse() Takes a well-formed JSON string and returns the resulting JavaScript object.
//JSON.parse(registered);
var registered = <?php echo $registered; ?>;
if (!(JSON.parse(registered))) {
$("#profile").hide();
$("#images").hide();
}
else {
$("#profile").show();
$("#images").show();
}
Remove the quotes and try
jQuery(document).ready(function($) {
var registered = <?php echo $registered; ?>;
alert(registered);
if (registered == false) { //Remove the quotes
$("#profile").hide();
$("#images").hide();
}
if (registered == true) { //Remove the quotes
alert('hello');
$("#profile").show();
$("#images").show();
}
});
Reason in this demo.
var registered = true;
alert(registered == 'true'); //return false
alert(registered == 'false'); //return false
In JavaScript data type comparison is a bit inconsistent. So always try to compare same data-types.
so try:
var registered = true;
alert(registered == true); //return true
alert(registered == false); //return false
Change your code to:
if (registered) {
alert('hello');
$("#profile").show();
$("#images").show();
}
else {
$("#profile").hide();
$("#images").hide();
}
Try with this
jQuery(document).ready(function($) {
var registered = "<?php echo $registered; ?>";
alert(registered);
if (registered == false) {
$("#profile").hide();
$("#images").hide();
}
else if (registered == true) {
alert('hello');
$("#profile").show();
$("#images").show();
}
});

use span id value as a conditional javascript

I have this span in the html body:
<span id="username_status"></span>
snippet of sql query:
if($exist > 0)
{
echo 'Sorry, That username is Taken!'; //value in username_status
}
else{
echo 'Username available!'; //value in username_status
}
and i'm trying to use the query result to generate a form validation alert:
var s1 = document.getElementById('username_status').innerHTML;
if (s1 === "Sorry, That username is Taken!")
{
alert("Please Change Your Username. It is already used.");
return false;
}
}
I've searched far and wide, but it looks i'm not getting anything. any help?
Instead of returning a message you can return a status code like status:success.
And i think you should send an ajax request to handle this,if you want to use javascript:
Javascript(I assume you use jQuery):
$.post("your-php-file.php",{username:"some-username"},function(data){
if(data.status == "success"){
alert("This username is available");
}
else{
alert("This username is already in use.");
}
});
PHP:
if($exist > 0){
$res['status'] = "success";
}
else{
$res['status'] = "failed";
}
echo json_encode($res);

Categories

Resources