javascript empty field validation - php

I have used the following code to display product details in my shopping cart website.
<div id="inner_right">
<form name="product_form" id="product_form" method="post" onsubmit="form_quantity(<?php echo $productid; ?>);">
<input type="hidden" name="hidden_<?php echo $productid; ?>" id="hidden_<?php echo $productid; ?>" />
<h1>Product Details of <?php echo $fetchproductname; ?></h1>
<div> </div>
<div id="product_left"><img src="<?php echo $path.$fetchimage; ?>" alt="" width="400" height="300" /></div>
<div id="product_right">
<div><strong>Category Name:</strong> <?php echo $categoryname; ?></div>
<p><strong>Product Number:</strong> <?php echo $fetchproductno; ?></p>
<p><strong>Price:</strong> <span class="price">$<?php echo $fetchproductprice; ?></span></p>
<p><strong>Stock:</strong> <?php echo $fetchproductstock; ?> nos</p>
<?php
$select_quantity = "SELECT * FROM `tbl_cart` WHERE `intProductid` = '".$productid."' AND `intSessionid` = '".$globalsessionid."'";
$select_quantity_res = mysql_query($select_quantity);
$sel_qty_num = mysql_num_rows($select_quantity_res);
$fetch_quantity = mysql_fetch_array($select_quantity_res);
$fetch_proid = $fetch_quantity['intProductid'];
$fetch_exqty = $fetch_quantity['intQuantity'];
?>
<p><strong>Quantity:</strong> <input name="quantity_<?php echo $productid; ?>" id="quantity_<?php echo $productid; ?>" value="<?php echo $fetch_exqty; ?>" class="quantity" type="text" /></p>
<div class="submit">
<button id="registerButton" type="submit">Add To Cart</button>
</div>
<input type="hidden" name="cart" id="cart" value="<?php echo $productid; ?>" />
</div>
<div class="clear"> </div>
</form>
</div>
There is an quantity field and add to cart button in my page. If the buyer click add to cart button without entered the quantity field an error should popup. For that i used the following javascript code.
function form_quantity(val){
var enteredqty = document.getElementById('quantity_'+val).value;
if(enteredqty =='')
{
alert(Please enter quantity);
}
}
But it doesn't work. I couldn't trace the error. How can i correct my code?

You've got a string literal with no quotes:
alert(Please enter quantity);
You need to say:
alert("Please enter quantity");
// OR
alert('Please enter quantity');
(When you say you couldn't trace your error, what did you actually try? If using Chrome it has built-in debugging tools, or for Firefox you can download Firebug, and these tools can easily tell you about errors like this.)
And to preempt your next question, once you fix the above error you'll find that although the alert displays the form still submits. You need to update your onclick to return the result of your form_quantity() function, and return false when you don't want the submit to go ahead (i.e., when there's a validation error):
<form name="product_form" id="product_form" method="post"
onsubmit="return form_quantity(<?php echo $productid; ?>);"></form>
<script>
function form_quantity(val){
var enteredqty = document.getElementById('quantity_'+val).value;
if(enteredqty === '') {
alert('Please enter quantity');
return false;
}
}
</script>

function form_quantity(val){
var enteredqty = document.getElementById('quantity_'+val).value;
alert(enteredqty);// check the givel value is right.
if(enteredqty ==''){
alert("Please enter quantity");// double qute added.
}
}
Check this, you may find some path.

Related

like system check if user like/unlike button

so here is my code for like system
<div class="btn like">
<div class="boxcoracao">
<?php foreach ($db->checklike($postid,$session_id) as $chk) {
if($postid== $chk['pl_puid'] && $session_id == $chk['pl_uid']){
?>
<input type="hidden" name="likepid" id="likepid" value="<?php echo $postid ?>">
<input type="hidden" name="likemid" id="likemid" value="<?php echo $mem_id ?>">
<span class="coracao ativo" name="like"><br>   Love</span>
<?php
}else{
?>
<input type="hidden" name="likepid" id="likepid" value="<?php echo $postid ?>">
<input type="hidden" name="likemid" id="likemid" value="<?php echo $mem_id ?>">
<span class="coracao" name="like"><br>   Love</span>
<?php
}
}
?>
</div>
</div>   
what happen here is if sessionID exists on the DB the if statement will run if not else will... but what happens is after writing this code my button disappear
sql query
function checklike($pid,$mid){
$query = "SELECT * FROM plike WHERE pl_puid = '$pid' AND plc_uid = '$mid'";
$stmt = $this->dbh->prepare($query);
$stmt->execute(array("0"));
$active_data = $stmt->fetchAll(PDO::FETCH_ASSOC);
return $active_data;
}
also im confuse im in going to use forloop for this??.. any better idea on how to do it...
this button refers to the default icon if the user didn't hit like
this button refers to the icon where the user hit like
but what happens on the above code is it disappears the button since the button is inside the if statement i dont have any idea on how to do it.. any idea please..
You are using if else statements inside html wrongly.
See this:
link
Example:
<? if ($condition): ?>
<p>Content</p>
<? elseif ($other_condition): ?>
<p>Other Content</p>
<? else: ?>
<p>Default Content</p>
<? endif; ?>

How do I let a user input a video url and have the video show on the same page upon submit?

I've seen a few similar questions, but none of the answers have worked for me. Ideally, the user would input the video url into the form, hit submit, and then the video would show below the form. Here's my code that's not working (sorry if it's messy or confusing):
<form id="rp_embed_video" name="rp_embed-video" method="post" action="">
<div class="rp_block">
<label><?php printf( __( 'Add Video Link:' ) ); ?></label>
<input type="url" id="rp_newvid" name="rp_newvid" value="" required />
</div>
<div class="rp_block">
<label><?php printf( __( 'Choose One:' ) );?></label>
<input type="radio" name="rp_type" value="YouTube" required checked />
<input type="radio" name="rp_type" value="Vimeo" required />
</div>
<div class="rp_block">
<label><?php _e('Title');?></label>
<input type="text" name="rp_title" value="" />
</div>
<div class="rp_block">
<?php $desc_status = (int)get_option('rp_uploader_desc',false);?>
<label><?php _e('Description');?><?php if(!$desc_status):?><span>*</span><?php endif;?></label>
<textarea name="rp_desc" <?php if(!$desc_status):?>class="wpvp_require"<?php endif;?>></textarea>
</div>
<div class="rp_block">
<div class="rp_cat" style="float:left;width:50%;">
<label><?php _e('Choose category');?></label>
<?php RP_Helper::rp_upload_categories_dropdown();?>
</div>
<?php
$hide_tags = get_option('rp_uploader_tags','');
if($hide_tags==''){ ?>
<div class="rp_tag" style="float:right;width:50%;text-align:right;">
<label><?php _e('Tags (comma separated)');?></label>
<input type="text" name="rp_tags" value="" />
</div>
<?php
}
?>
</div>
<input type="hidden" name="rp_action" value="rp_embed" />
<p class="rp_submit_block">
<input type="submit" class="rp-submit" name="rp-embed" value="Add Video" />
</p>
</form>
<?php
if (isset($_POST['rp_newvid'])) {
// Get the video URL and put it in the $video variable
$videoID = $_POST['rp_newvid'];
$type = $_POST['rp_type'];
echo rp_video_embed($_POST['rp_newvid'], '720px', '380px', $_POST['rp_type']);
}
?>
<?php
function rp_video_embed($videoID,$width,$height,$type){
if($type){
if($videoID){
if($type=='YouTube'){
$embedCode = '<iframe width="'.$width.'" height="'.$height.'" src="http://www.youtube.com/embed/'.$videoID.'" frameborder="0" allowfullscreen></iframe>';
}
elseif($type=='Vimeo'){
$embedCode = '<iframe width="'.$width.'" height="'.$height.'" src="http://player.vimeo.com/video/'.$videoID.'" webkitAllowFullScreen mozallowfullscreen allowFullScreen frameborder="0"></iframe>';
}
$result = $embedCode;
}
else{
$result = '<span style="color:red;">'._e('No video code is found').'</span>';
}
}
else{
$result = '<span style="color:red;">'._e('The video source is either not set or is not supported').'.</span>';
}
return $result;
}
?>
It appears that you are asking a user to enter a URL such as "www.youtube.com/watch?v=vidID", then taking that entire string value and inserting it into the <iframe> source value.
This essentially sets the source to "www.youtube.com/embed/www.youtube.com/watch?v=vidID".
You need to parse the URL submitted by the user and take only the vidID value before inserting into the <iframe>
Because of the structure of these URL's the video ID is the last value in the string. This means you could do "explode" the string and take the last value in the array that creates.
Here's a quick example of how you could do this:
<?php
//Sample Variables
$youtubeURL = 'www.youtube.com/watch?v=vidID';
$vimeoURL = 'https://vimeo.com/vidID';
//Test Values
$vidURL = $youtubeURL;
$videoSource = 'youtube';
//Select Delimiter based on the video source
switch ($videoSource) {
case 'youtube':
$delimiter = '=';
break;
case 'vimeo':
$delimiter = '/';
break;
default:
//Whatever fallback you want
}
//Isolate the vidID value string
$vidID = end(explode($delimiter, $vidURL));
?>

PHP (5.5) - database search with MySQLi - getting datalist but no output

I'm just learning how to do this so please forgive my ignorance!
Here is my test site: http://webtestkit.com/1KaraokeDJ/index.php
First, I found this code in a learning example and that code worked just fine. (http://www.mostlikers.com/2013/08/search-engine.html) - no problems. I even made the sample database and checked all was working.
now I wanted to change it to work for my purpose (a karaoke search)...
here is my code:
<?php
include("connect.php");
session_start();
if(isset($_POST['submit']))
{
$search=$_POST['search'];
$_SESSION['title']= $search;
if(($_SESSION['title'])!="")
{ header("location:index.php"); }
else
{ echo "<script> alert('Please enter something to search for') </script>"; }
}
?>
<html>
<head>
<title>1KaraokeDJ.com</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div class="login">
<form method="post">
<p><img src="top.jpg" /></p>
<p>
<?php if(isset($_SESSION['title'])) { ?>
<input name="search" type="search" list="searchkey" value="<?php echo $_SESSION['title'];?>" class="search" />
<?php } else { ?>
<input name="search" type="search" list="searchkey" placeholder="Just type your text here and press enter - ex : Abba" class="search" />
<?php } ?>
</p>
<datalist id="searchkey">
<?php
$tile=$db->query("SELECT * FROM `1KaraokeDJ.com`");
while($storetitle=mysqli_fetch_object($tile))
{ ?>
<option value="<?php echo $storetitle->title ?>">
<?php } ?>
</datalist>
<p><input type="submit" name="submit" id="click" class="searchbutton" value="Karaoke Search" /></p>
<?php if(isset($_SESSION['title'])) {
if(($_SESSION['title']!=""))
{
$data=$_SESSION['title'];
$view=$db->query("select * from 1KaraokeDJ.com where title like '%$data%' limit 10");
$check=mysqli_num_rows($view);
if($check!="")
{
while($descri=mysqli_fetch_object($view))
{
?>
<div class="reslt">
<h3 id="resuil-title"><?php echo $descri->title; ?></h3>
<p class="Description">
<?php $description = str_replace($data, '<span class="highlight">'.$data."</span>", $descri->artist);
echo $description; ?>
<p>
<hr>
</div>
<?php } } else { ?>
<div class="reslt">
<h3 id="resuil-title">Nothing fond!</h3>
<p class="Description">Try changing your search terms<p><hr>
</div>
<?php } } } ?>
</form>
</div>
</body>
</html>
The search field is finding data in the dropdown list so the connection is fine and the search works.
I think I understand most of the code, but I don't seem to understand this:
$view=$db->query("select * from 1KaraokeDJ.com where title like '%$data%' limit 10");
$check=mysqli_num_rows($view);
if($check!="")
{ while($descri=mysqli_fetch_object($view)) {
My If always goes to else "Nothing Found"
Any help? The way I learn is by doing - so it's trial and error until I figure it out!
Your table 1KaraokeDJ.com is interpreted as DatabaseName.TableName
To avoid this, escape your table name
Select * from `1KaraokeDJ.com` Where ...

Deleting objects using checkboxes with Codeigniter

I have read many post like this but have failed to find my particular situation.Trying to delete the selected checkbox. right now you can submit the form and it takes you to all the right pages except it doesn't actually delete anything.
Here is my controller info
function deleteFolder() {
if(array_key_exists('deleteMe',$_POST)) {
$checkbox = $this->input->post['checkbox'];
$this->index_model->deleteFolder($checkbox);
}
$this->folderdeleted();
}
Here is my Model
function deleteFolder($checkbox) {
$this->db->where('folderName', 'folderName');
$this->db->delete('senior', $checkbox);
return;
}
Here is my View
<!DOCTYPE html>
<?php $this->load->view('partials/page_head'); ?>
<body>
<div id="container">
<div id="top">
<div class="topcenter">
<h2><a class="homebtn" href="<?php echo base_url();?>">Home</a></h2>
</div>
<div class="navdescription"><span>Delete Page</span></div>
</div>
<div class="projectFolders">
<?php foreach($foldername as $row) { ?>
<div class="folder">
<button><?php echo $row->folderName; ?></button>
<div class="delete">
<form name="delete" method="post" action="<?php echo base_url(); ?>index.php/home/folderdeleted">
<p>
<input type = "checkbox" id = "check_<?php echo $row->folderName; ?>"/>
<?php echo form_submit('deleteFolder', 'Delete'); ?>
</p>
</form>
</div>
</div>
<?php } ?>
</div>
</div><!-- End of container div -->
</body>
</html>
There are several errors in your code. I'm not sure whether I've found all of them and whether the code will work.
The controller should be:
function deleteFolder() {
if($this->input->post('checkbox') !== false) {
$checkbox = $this->input->post('checkbox');
$this->index_model->deleteFolder($checkbox);
}
$this->folderdeleted();
}
The model should be:
function deleteFolder($checkbox) {
$this->db->where('folderName', $checkbox);
$this->db->delete('senior');
return;
}
The input tag in the view should be:
<input name="checkbox" value="<?php echo $row->folderName; ?>" type = "checkbox" id = "check_<?php echo $row->folderName; ?>"/>
A little warning for checkboxes: if they aren't checked, you won't find anything in the $_POST variable.

Input values lost when form submitted with errors

My form is working fine with the validations being done by PHP.
I have three fields: Name, EMail and Message.
Form and PHP code is within the same pgae, same page is called for validations when user submits the form.
When a user submits the form, same page is called and it checks whether the form is submitted or not.
If the form is submitted it then does the validations for blank entries and throws error message below the fields to inform user that field is left blank. It also shows error icon next to field.
Till this, it is working fine.
However, the problem, is if the user has filled any field, for example name filed and left the other two fields(EMail and Message) blank, then on submittion, it throws error messages for blank fields which is ok, but for name field which was filled by user it empty the content and shows blank name field and does not show error(as earlier user had filled it).
My only concern is that when it relods the form after submission, it should also reload the earlier values in the respective fields which user input before submitting.
Below is the PHP validation code.
<?php
error_reporting(E_ALL & ~E_NOTICE);
if(isset($_POST['nameField_Name']) AND isset($_POST['nameField_EMail']) AND isset($_POST['nameField_Message']) AND isset($_POST['nameSubmit'])){
// Form Submited
if ($_POST['nameField_Name']) {
$phpVarNameField = mysql_escape_string($_POST['nameField_Name']);
} else {
$errormsgNameField = "Name field is required, Please enter your Name.";
}
if ($_POST['nameField_EMail']) {
$phpVarEMailField = mysql_escape_string($_POST['nameField_EMail']);
} else {
$errormsgEMailField = "E-Mail field is required, Please enter your E-Mail ID.";
}
if ($_POST['nameField_Message']) {
$phpVarMessageField = mysql_escape_string($_POST['nameField_Message']);
} else {
$errormsgMessageField = "Message field is required, Please enter your Message.";
}
}
?>
Below is the form code.
<form name="myform" action="contactus.php" method="post"">
<div id="r1">
<div id="r1c1">
<input type="text" name="nameField_Name" id="idField_Name" placeholder="Enter your name here"/>
</div>
<div id="r1c2">
<?php
if(isset($errormsgNameField)){ // Check if $msg is not empty
echo '<img src="error.png" width="45" height="45" style="margin: 5px 0px" alt="">';
}
?>
</div>
</div>
<div id="afterr1">
<?php
if(isset($errormsgNameField)){ // Check if $msg is not empty
echo '<div class="statusmsg" id="idErrorMsgNameField">'.$errormsgNameField.'</div>'; // Display our message and wrap it with a div with the class "statusmsg".
}
?>
</div>
<div id="r2">
<div id="r2c1">
<input name="nameField_EMail" type="text" id="idField_EMail" placeholder="Enter your E-Mail address here" />
</div>
<div id="r2c2">
<?php
if(isset($errormsgEMailField)){ // Check if $msg is not empty
echo '<img src="error.png" width="45" height="45" style="margin: 5px 0px" alt="">';
}
?>
</div>
</div>
<div id="afterr2">
<?php
if(isset($errormsgEMailField)){ // Check if $msg is not empty
echo '<div class="statusmsg" id="idErrorMsgEMailField">'.$errormsgEMailField.'</div>'; // Display our message and wrap it with a div with the class "statusmsg".
}
?>
</div>
<div id="r3">
<div id="r3c1">
<textarea name="nameField_Message" id="idField_Message" placeholder="Enter your message for us here"></textarea>
</div>
<div id="r3c2">
<?php
if(isset($errormsgMessageField)){ // Check if $msg is not empty
echo '<img src="error.png" width="45" height="45" style="margin: 115px 0px" alt="">';
}
?>
</div>
</div>
<div id="afterr3">
<?php
if(isset($errormsgMessageField)){ // Check if $msg is not empty
echo '<div class="statusmsg" id="idErrorMsgMessageField">'.$errormsgMessageField.'</div>'; // Display our message and wrap it with a div with the class "statusmsg".
}
?>
</div>
<div id="r4">
<div id="r4c">
<input type="Submit" name="nameSubmit" id="idButton_Submit" value="Submit" alt="Submit Button"/>
</div>
</div>
</form>
Any help will be great on this.
Thank You.
You will need to add a value attribute on your <input> elements:
<input type="text"
name="whatever"
value="<?php echo htmlspecialchars($_POST['whatever']); ?>"
>
It may be easier to read if PHP outputs the field:
<?php
printf('<input type="text" name="%s" value="%s">',
'whatever',
htmlspecialchars($_POST['whatever']));
?>
This can even be wrapped in a function so you don't need to retype it for every single form field.
Note the call to htmlspecialchars. It is needed so that < and > and quotes don't destroy your HTML document.
Try changing your tag like :
<input type="text"
name="nameField_Name"
id="idField_Name"
placeholder="Enter your name here"
value ="<?php
if (isset($phpVarNameField))
echo $phpVarNameField;
?>"
/>
.......
<input
name="nameField_EMail"
type="text"
id="idField_EMail"
placeholder="Enter your E-Mail address here"
value ="<?php if (isset($phpVarEMailField)) echo $phpVarEMailField; ?>"
/>
.......
<textarea name="nameField_Message" id="idField_Message" placeholder="Enter your message for us
here" value ="<?php if (isset($phpVarMessageField)) echo $phpVarMessageField; ?>" ></textarea>
Good Luck !
Well, You could do validation with jQuery validation plugin - easy and good. jQuery plugin
Or with PHP store POST data in array, check for errors and fields that are not empty set as value to input text.
if (isset($_POST)) {
$data = $_POST;
}
foreach ($data as $row) {
if ($row == "")
$error = true; // do what ever you want
}
and then in form
<input type="text" name="name" value="<?php ($data['name'] != "")? $data['name'] : '' ?>" />
something like this.

Categories