if conditions are not working while $(document).ready(function() - php

I have tried the following code to display some divs.
<?
$uri=$_SERVER['REQUEST_URI'];
$uri=explode('/',$uri);
$uri=$uri[4];
echo $uri;
?>
<script type="text/javascript">
$(document).ready(function() {
var ty=<?=json_encode($uri);?>;
if(ty="gen")
{
alert("gen");
}
else if(ty="cc")
{
alert("cc");
}
else
{
alert("not gen");
}
});
</script>
$uri value will be something like /site/view-wall/type/gen/id/6. The type variable can be changed to vo,cc,fr etc. If I changed the web address to www.example.com/site/view-wall/type/cc/id/6 I am getting alert "gen", not "cc". Always I am getting alert "gen". The if conditions are not working. I couldn't figure out the simple if condition :(
Any help should be appreciated!

You are setting the variable value, you have to use double equal == to compare

In JavaScript, == or === are used to compare; you're using =, which sets the value of a variable. When you do this:
if(ty="gen")
{
alert("gen");
}
That's equivalent to doing this:
ty = "gen";
if(ty) {
alert("gen");
}
All non-empty strings are truthy, so your condition always succeeds.
To fix it, change the = in all of your conditions to == or ===.

Related

hiding a div from users view

I want to return true when the number of rows in a table is more than one and show a div with jquery as shown in the jquery code .In addition return false when the number of rows is zero and hide a div as shown in the code below.The php code is executing and returning a correct value but the jquery code is neither showing or hiding a div.I need to show a div when the value returned is true and hide a div when the value returned is false;
**php code** php code for retrieving the number of rows from a table
<?php
require'php/connection.php';//a file for connecting to the database
$user_name=getUserField('user_name');//function for getting the name of the user in session
$query="select `order_id` from `inbox` where `buyer_name`='$user_name'";
$query_run=mysql_query($query);
$num_rows=mysql_num_rows($query_run);
if($num_rows >= 1) {
return true;
} else if($num_rows == 0) {
return false;
}
?>
jquery code Jquery code for either hiding or showing a div
$(document).ready(function() {
$.post('php/ManNotify.php',{},function(data){
if(true) {
$('#notify').show();
} else if(false) {
$('#notify').hide();
}
});
});
Do you realize your if statement reads,
if(true) ..
else if(false) ...
The hide will never execute. Is this your problem?
When using AJAX calls with PHP, you should echo the value rather than return it. Modify your PHP code like so:
<?php
require'php/connection.php';//a file for connecting to the database
$user_name=getUserField('user_name');//function for getting the name of the user in session
$query="select `order_id` from `inbox` where `buyer_name`='$user_name'";
$query_run=mysql_query($query);
$num_rows=mysql_num_rows($query_run);
if($num_rows >= 1){
echo json_encode(array("status" => true));
} else if($num_rows == 0) {
echo json_encode(array("status" => false));
}
exit;
?>
You'll also need to modify your JavaScript accordingly. Right now, if(true) will always execute on the return. Modify it like so:
// Shorthand for $(document).ready
$(function(){
$.post('php/ManNotify.php',{}, function(data) {
// JavaScript truthy/falsy will take care of the statement
if(data.status) {
$('#notify').show();
} else {
$('#notify').hide();
}
});
});
EDIT:
As #mplungjan points out in the comments below, the JavaScript could be simplified in the callback to be the following: $('#notify').toggle(data.status);. The resulting JavaScript would be:
// Shorthand for $(document).ready
$(function(){
$.post('php/ManNotify.php',{}, function(data) {
$('#notify').toggle(data.status);
});
});
Thanks to #mplungjan for the suggestion.
$(document).ready(function(){
$.post('php/ManNotify.php',{},function(data){
if(data == 'true'){
$('#notify').show();
}else if(data == 'false')
{
$('#notify').hide();
}
});
});
There are two problems with your code:
The server-side code. Returning boolean TRUE or FALSE this way will only render the page blank.
The jQuery code logic is wrong: if(true){ case will always be executed (because the value is, well, always true).
A very simple fix would be (untested):
if($num_rows >= 1){
echo 'true';
} else {
echo 'false';
}
Then, in the JS:
$.post('php/ManNotify.php', function(data){
if(data === 'true'){
$('#notify').show();
} else {
$('#notify').hide();
}
});
Note that this is not optimized.
$(document).ready(function(){
$.post('php/ManNotify.php',{},function(data){
if(data == "true"){
$('#notify').show();
}else if(data == "false")
{
$('#notify').hide();
}
});
});

Registration form validating errors

If I submit blank fields it still adds it into database. I made a loop to check if everything is on place but it keeps redirecting it to error page. I've been struggling with this almost 2 hours but cant find a solution.
Links are here since i can post more than 2 :
Try to set
Don't allow nulls
in the column property of table. It can be done during the table design or Edit table Design in the database.
Hope this helps.
You using empty(). http://us3.php.net/empty
This only returns false if NULL, FALSE, or not exists, NOT if empty string.
You should be doing this:
foreach($required as $post){
if ($_POST[$post] == "") {
die(header("refresh:0.5;url=error.php"));
}
}
However, I don't know why you don't just put this over the entire code block so it only gets executed on submit of the form. Then you don't have to keep rechecking it.
if (isset($_POST)) { //or a specific $_POST variable if multiple submit paths
//code here
}
Additionally, you should edit your question to include the relevant code in the question or in the future, searchers may discover that your pastebin link no longer works.
I think in any way you should make some client-side validation on empty field like jQuery functions :
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
$("form").submit(function(){
if($("#first_name").val() == ''){
alert("First name cann't be empty");
return false;
}else if($("#last_name").val() == ''){
alert("Last name cann't be empty");
return false;
}else if($("#email").val() == ''){
alert("Email cann't be empty");
return false;
}else if($("#password").val() == ''){
alert("Password name cann't be empty");
return false;
}
});
});
</script>
You're trying to get indexes on $_POST array that doesn't exist, so correct your $required array and put fields names not the variables names, just like this in process.php:
$required = array('first_name','last_name','password','email');
foreach($required as $post){
if($post = empty($_POST[$post]) || $_POST[$post] == ""){
die(header("refresh:0.5;url=error.php"));
} elseif($required != empty($_POST)) {
echo "";
}
}
I think yor a looking for something like,
if(isset($_POST['field1']) && !$_POST['field1'] =="")
{
//your codes goes here
}
Maybe You have done something like
<input type=text name=name1 value ="" />
If so, Please do it like,
<input type=text name=name1 />
This will not send name1 to your page;

Selecting Radio Option based on Query String

I'm having some trouble with selecting the radio option affiliated to the query string. I have the following code in place...
<?php if ( $_GET['fp'] == 'floorplanfive' ) { ?>
<script type="text/javascript">
jQuery('#choice_2_4').attr('checked', 'checked');
console.log("test");
</script>
<?php } ?>
The console is showing the message 'test' but the radio option is not being selected.
The page can be found here.
Please help out. :-)
You need to put your code inside of the $(document).ready() function:
jQuery(document).ready(function() {
// your code
});
Use this:
jQuery('#choice_2_4').prop('checked', true);
Edit: if your radio button is loaded after this code, use it:
jQuery(document).ready(function () {
jQuery('#choice_2_4').prop('checked', true);
}
Use == comparison operator instead of = assignment.
Assignment in if condition will always return true.
Change your code to:
<?php if ( $_GET['fp'] == 'floorplanfive' ) { ?>
<script type="text/javascript">
jQuery('#choice_2_4').attr('checked', 'checked');
console.log("test");
</script>
<?php } ?>
Try Following:
jQuery('#choice_2_4').attr('checked', true).checkboxradio("refresh");

DIV container stays blank

I need to run the function find_optimal_schedule() every 5 seconds, while each time updating the DIV container schedule. Below is my code snippet. The problem is that alert("Init") is executed, while alert("True") or alert("False") are not executed. FireBug shows that optimize.php is runned every 5 seconds, but I don't understand why the content of DIV container stays blank all the time.
P.S. The code gantt.php works properly, because I tested it in DIV container without the timer and the Gantt chart was displayed correctly. Therefore, I do not provide this code here, because it's not the case.
scheduler.php
<script>
window.setInterval(function(){
find_optimal_schedule();
}, 5000);
</script>
<script>
function find_optimal_schedule() {
$.ajax({
url: 'modules/mod_scheduler/pages.php?page=optimize.php',
dataType: 'json',
success: function(output){
alert("Init");
if(output.msg === 1){
alert("True");
$('#schedule').html(output.html);
} else {
alert("False");
return false;
}
}
});
}
</script>
<div style="width:100%; height:350px; position:relative" id="schedule" class="schedule"></div>
pages.php
<?php
#session_start();
#$pag_mod = $_GET['pag_mod'];
if(!isset($pag_mod))
$pag_mod = 0;
if (isset($_GET['pag_mod'])) {
include 'modules/mod_scheduler/'.$_GET['pag_mod'];
}
else {
include 'modules/mod_scheduler/scheduler.php';
}
?>
optimize.php
<?php
// Dispay Gantt chart
$html_code = '<img src="modules/mod_scheduler/gantt.php">';
echo json_encode(array('msg' => 1, 'html' => $html_code));
?>
I believe you output.msg should be compared with == instead of ===.
if(output.msg == 1){
alert("True");
$('#schedule').html(output.html);
} else {
alert("False");
return false;
}
Via nnnnn, it appears that === is valid for comparision in javascript; therefore, the only thing I can think of is that output.msg is undefined. Since === is not causing the javascript error, output.msg is the only other thing that could be.
You are using a strict equality operator (===) instead of equality.
This means that the comparison is true if also the data types are considered equal, in addition to the values; maybe output.msg comes as a string and is not equated to a number. Try == instead.
Try
console.log(output)
to see if output is a valid object. Firebug should show you the entire object with all its properies.

loading a returned value from php into a js variable using ajax and jquery

Basically all i wanna do is something like this.
var myVar = $.load("phpscript.php","var=one");
phpscript.php
<?
$a = $_GET['var'];
if($a == "one") { return 1 };
else return false;
?>
Right now i am doing this the most idiotic way as i cannot find out how to do this the proper way. what i am doing currently is making my phpscript return a hidden field with the value
return "<input type='hidden' value='1' id='takeValueFromThisID>";
into a div from the calling page and finally use the above id to retrieve the value. Even though this works its very idiotic. Can some one pls guide me in the right way to do it.
$.get("phpscript.php", { 'var': 'one' }, function(resp) {
alert(resp); // '1'
});
and a test PHP script:
<?php
echo '1';
?>
PHP Code
<?
$a = $_GET['var'];
if($a == 'one') {
echo 1
} else {
echo 0; // or '' may be?
}
?>
AJAX
var myVar;
$.get("phpscript.php", {"var": "one"}, function (resp) {
myVar = resp;
});
The problem here is that myVar will be "1" or whatever after the AJAX request is completed. This may take a couple of milliseconds (or seconds). If you plan to use myVar in your script you must wait until it becomes something other than undefined.

Categories