javascript form validation with multiple field and display on site - javascript

So, hey, I know that there's more than someone could want of this type of question, but maybe I can present it with a little twist, i have try to mix different thing reader here and there, but when i submit the form the validation process don't run and it just submit directly the form. It's a one go script, and it go like this:
<script type="text/javascript">
var errors =[];
function printarray(array){
for (var i=0; i<array.lenght; i++){
document.write(array[i]);
}
}
function validate(){
document.getElementById("npostform").elements["contenidotext"].value=window.frames["contenido"].document.body.innerHTML;
document.getElementById("npostform").elements["resumentext"].value=window.frames["resumen"].document.body.innerHTML;
if (document.npostform.titulo.value=="" || document.npostform.titulo.value==null){
errors.push("Se debe especificar un titulo <br>");
}
if (document.npostform.contenidotext.value=="" || document.npostform.contenidotext.value==null){
errors.push("Se debe incluir un contenido <br>");
}
if (document.npostform.resumentext.value=="" || document.npostform.resumentext.value==null){
errors.push("Se debe incluir un resumen <br>");
}
if(errors.length >0){
for (var i=0; i<errors.lenght; i++){
document.getElementById("error").innerHTML=printarray(errors);
}
return false;
}else{
return true;
}
}
</script>
<div id="error"></div>
<form action="entradas.php" name="npostform" id="npostform" method="post" enctype="multipart/form-data" onsubmit="return validate();">
<label for="Titulo">Titulo:</label>
<input type="text" name="titulo" value="<?php if (isset($_SESSION['titulo'])) { echo $_SESSION['titulo'];} ?>">
<br>
<label for="Categoria">Categoria-Seccion:</label>
<select name="categoria" value= "<?php if(isset($_SESSION['categoria'])){echo $_SESSION['categoria'];} ?>">
<option value=""></option>
<?php
foreach (tomarcategorias() as $order =>$categorias){
$name = $categorias['name'];
$id = $categorias['id'];
$order =$categorias['order'];
if ($categorias['type'] == 'Articulos'){
echo "<optgroup label='", $name, "'>";
foreach(tomarsecciones('idcategoria', $id) as $ord => $secciones){
$ord = $secciones['order'];
echo "<option value='", $secciones['id'], "'><PRE>", $secciones['name'], "</option>";
}
}
}
?>
</select>
<br>
<textarea name="contenidotext" rows="15" cols="50" style="display:none;"></textarea>
<iframe name="contenido" id="contenido" style="width:300; height:100; background: white;"></iframe>
<br>
<label>Resumen del articulo</label>
<br>
<textarea name="resumentext" rows="5" cols="50" style="display:none;"></textarea>
<iframe name="resumen" id="resumen" style="background: white;"><?php if (isset($_SESSION['resumen'])) { echo $_SESSION['resumen'];}?></iframe>
<br>
<input type="submit" name="add_post" value="Subir post"/>
</form>
I have to be sincere, in the head there is a linked javascript but that contain functions for buttons for a simple wysiwyg and already try to make all the script together, in the same and different files, didn't change a thing.
Does anybody know where the bug is? and also,is there a way to view the errors of javascript script as in php?

Related

Values to PHP function parameters from Button click Javascript function

Friends,
I'm a newbie to PHP.
I've had a problem to deal with that I couldn't understand, so I posted it in this thread.
I've dynamically created 2 textboxes and a button.
Question ID text field
Question text field
Change Button
for the change button I need to write a 'onclick' javascript to pass Question ID
and Question value to a PHP function (set_id) written inside the Same file. In fact that’s why i
Called Form action $_SERVER[“PHP_SELF”].
Here’s my code.
<html>
<head>
<script>
function getvalue(value)
{
var qid_value = 'qid_'+value.substring(4);
alert('QID = '+ document.getElementById(qid_value).value + ' QUESTION = ' + document.getElementById(value.substring(4)).value);
/*
I created this javascript alert to test the id s of textboxes and their values
*/
}
</script>
</head>
<body>
<form action="<?php echo $_SERVER["PHP_SELF"]; ?>" method="post">
<!-- These fields are dynamically created -->
<input type="text" id="'.$var_id.'" name="'.$var_id.'" value="'.$row['qid'].'" readonly size="2 px"/>
<input type="text" id="'.$var_question.'" name="'.$var_question.'" value="'.$row['question'].'" style="size:auto"/>
<input type="button" id="'.$var_question.'" name="'.$var_question.'" value="Change" onclick="getvalue(this.name)"/>
<!-- These fields are dynamically created -->
</form>
</body>
</html>
<?php
$msg= "";
function display($qid,$question)
{
require('uni_db_conn.php'); // this is my db connection
$qid = $_POST[$qid];
$question= $_POST[$question];
$query = "UPDATE question SET question='.$question.' WHERE qid='.$qid.'";
$result = mysql_query($query);
if(!$result)
{
$msg= 'Cant Insert Values to the Table !'.mysql_error();
}
else
{
$msg = 'Successfully Added to the Table !';
}
echo '<label>'.$msg.'</label>';
}
function set_id($qid,$question)
{
if(isset($_POST[$question]))
{
display($qid,$question);
}
}
?>
Thank You ! Sorry If there was any mistake.
Try this code
<?php
if(isset($_POST['submit'])){
$QID = $_POST["qid"];
$QUE = $_POST["question"];
echo $QID;
echo $QUE;
}
?>
<html>
<head>
<script language="javascript">
function getvalue()
{
var valid= true;
var id = document.getElementById("ID").value;
var ques = document.getElementById("ques").value;
return valid;
}
</script>
</head>
<body>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" onSubmit=" return getvalue()" >
<input type="text" id="ID" name="qid"/>
<input type="text" id="ques" name="question"/>
<input type="submit" name="submit" value="Change"/>
</form>
</body>
</html>

how can i make textarea a read only but will not be greyed out

how can i make textarea a read only but will not be greyed out?
i am using this script but its not working:
$(".readonly").keydown(
function keydown(e) {
if(!e.ctrlKey) return false; // Cancel non ctrl-modified keystrokes
if(e.keyCode == 65) return true;// 65 = 'a'
if(e.keyCode == 67) return true;// 67 = 'c'
return false;
}
)
i tried to use <textarea readonly> but its making the field greyed out, I want it to be readonly but dont want the textarea field to change to being greyed out.
here is my entire code:
<body>
<form name="search" method="post" action="">
<fieldset style='width: 500px'>
<legend align='left'><strong>Search</strong></legend>
<p>
Seach for: <input type="text" name="find" id="find" /> in
<Select NAME="field" id="field">
<Option VALUE="testA">A</option>
<Option VALUE="testB">B</option>
<Option VALUE="testC">C</option>
<Option VALUE="testD">D</option>
</Select>
<input type="hidden" name="searching" value="yes" />
<input type="submit" name="search" id="search" value="Search" />
</p>
</fieldset>
</form>
<script>
$(".readonly").keydown(
function keydown(e) {
if(!e.ctrlKey) return false; // Cancel non ctrl-modified keystrokes
if(e.keyCode == 65) return true;// 65 = 'a'
if(e.keyCode == 67) return true;// 67 = 'c'
return false;
}
)
</script>
<?php
//This is only displayed if they have submitted the form
if (isset($_POST['searching']) && $_POST['searching'] == "yes")
{
//If they did not enter a search term we give them an error
if (empty($_POST['find']))
{
echo "<p>You forgot to enter a search term";
exit;
}
// Otherwise we connect to our Database
mysql_connect("host", "username", "passw") or die(mysql_error());
mysql_select_db("testdb") or die(mysql_error());
// We preform a bit of filtering
$find = strtoupper($_POST['find']);
$find = strip_tags($_POST['find']);
$find = trim ($_POST['find']);
$field = trim ($_POST['field']);
//Now we search for our search term, in the field the user specified
$data = mysql_query("SELECT * FROM testtable WHERE UPPER($field) LIKE UPPER('%$find%')");
//And we display the results
while($result = mysql_fetch_array( $data ))
{
$myRes = "<form action='' method='post'>
<fieldset style='width: 10px'>
<legend align='left'><strong>Results</strong></legend>
<p>
<table width='auto' border='1' cellspacing='1' cellpadding='1' align='center'>
<tr>
<th align='center' scope='row'>A</th>
<td><textarea class=readonly name=testA id=testA cols=65 rows=3>" . $result['testA'] . "</textarea></td>
</tr>
<tr>
<th scope='row'>B</th>
<td><textarea class=readonly name=testB id=testB cols=65 rows=3>" . $result['testB'] . "</textarea></td>
</tr>
</table>
</p>
</fieldset>
</form>";
}
echo $myRes;
//This counts the number or results - and if there wasn't any it gives them a little message explaining that
$anymatches=mysql_num_rows($data);
if ($anymatches == 0)
{
echo "Sorry, but we can not find an entry to match your query<br><br>";
}
//And we remind them what they searched for
echo "<b>Searched For:</b> " .$find;
}
?>
</body>
You could use css
something like
textarea[readonly="readonly"], textarea[readonly] { //your styling }
eg
textarea[readonly="readonly"], textarea[readonly] { background-color:white; }
Also note that the mysql_ functions have been deprecated. You should MySQLi or PDO with prepared statements.
Looking at your code you are using class=readonly, unless you've actually created that class in css you should be using
<textarea readonly></textarea>

JavaScript/Jquery file not loading

My Jquery works fine in-line however when I try and make it external it doesn't seem to work.
I have both scripts stored in the: include('./includes/header.html');
And I also have them stored at the root of the folder.
If any one could help would be great.
I have two links held within the header.html
<!DOCTYPE html>
<head>
<title> <?php $page_title ?> </title>
<link rel="stylesheet" type="text/css" href="mystyle.css">
<script src="formValidation.js"></script>
<script src="jquery-1.10.2.js"></script>
</head>
<body>
<div id="wrapper">
<div id="header">
<h1>Films.com</h1>
</div>
<div id="content">
<div id="nav">
<ul>
<li>Login</li>
<li>Home</li>
<li>Register</li>
<li>Film</li>
<li>Add a Film</li>
</ul>
</div>
When going to add_film.php the Jquery that would normally slide down my form, now it doesn't slide down.
<?php
include('./includes/header.html');
echo "<h1>Add A film</h1>";
if(isset($_POST['submitted'])){
$errors = array(); // Initialize erroy array.
// Check for title.
if (empty($_POST['movie_title'])){
$errors[] = "You forgot to enter a title.";
} else {
$mn = (trim($_POST['movie_title']));
}
// Check for leading actor
if (empty($_POST['leading_actor'])){
$errors[] = "You forgot to enter the leading actor.";
} else {
$la = (trim($_POST['leading_actor']));
}
// Check for a rating
if (empty($_POST['rating'])){
$errors[] = "Please select a rating.";
} else {
$rating = ($_POST['rating']);
}
// Check for a review
if (empty($_POST['review'])){
$errors[] = "Please write a review";
} else {
$review = (trim($_POST['review']));
}
if (empty($errors)) { // If no errors were found.
require_once('./includes/Mysql_connect.php');
// Make the insert query.
$query = "INSERT INTO films (movie_title, actor, rating)
Values ('$mn', '$la', '$rating' )";
$result = mysql_query($query);
$id = mysql_insert_id();
$query = "INSERT INTO reviewed (review, movie_id)
values ('$review', '$id')";
$result = mysql_query($query);
//Report errors.
} else {
foreach ($errors as $msg){
echo " - $msg <br/> ";
}
}
}
?>
<html>
<form action="add_film.php" method="post" id="add_film">
<fieldset>
<label for="title">Movie Title</label>
<input type="text" name="movie_title" id="movie_title" />
<br/>
<br/>
<label for="actor">Leading Actor</label>
<input type="text" name="leading_actor" id="leading_name" />
<br/>
<br/>
<label for="rating">Rating</label>
<select id="rating" name="rating"/>
<option selected="selected" value=0 disabled="disabled">Select a Rating</option>
<option value="Terrible">Terrible</option>
<option value="Fair">Fair</option>
<option value="Ok">Ok</option>
<option value="Good">Good</option>
<option value="Excellent">Excellent</option>
</select>
<br/>
<br/>
<label for="review">Your Review</label>
<br/>
<textarea name="review" id="review" rows="15" cols="60"></textarea>
<br/>
<br/>
<input type="submit" name="submit" id="submit" value="submit" />
<input type="hidden" name="submitted" value="TRUE" />
</fieldset>
</form>
<br/>
</html>
<?php
include('./includes/footer.html');
?>
Here is my Jquery.
$(document).ready(function(){
$('#add_film').slideDown(800);
// Focus on first form field.
$("input:text:visible:first").focus();
$('#add_film').submit(function (e) {
var error = false;
// No value for movie_title
if ($('#movie_title').val() == "") {
alert("No Film");
error = true;
}
// No Value for actor
if ($('#leading_name').val() == "") {
alert("No actor");
error = true;
}
// No value for rating
if ($('#rating').val() == null) {
alert("No Rating");
error = true;
}
//No value for review
if ($('#review').val() == "") {
alert("No review");
error = true;
}
if (error) {
e.preventDefault();
}
});
});
Change the order you load them:
<script src="jquery-1.10.2.js"></script>
<script src="formValidation.js"></script>
the order in which you load the scripts is important.
since your script uses jquery, so jquery needs to be loaded before your script.
so change the order of loading. first load jquery, then your script.
this is also the reason, why your script works inline.

Cheking if form of submited email is correct

I've created this script to check form of email user will enter into textbox
function checkEmail() {
var mail = document.getElementById('mail');
var filter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/; /* regex koda najdena na codeproject.com*/
if (!filter.test(mail.value))
{
alert('enter valid email');
mail.focus;
return false;
}
It's used to check form in this script and suposed to show you alert, before you are able to continue
<?php
$flag = 0;
if(isset($_POST['submit']))
{
$con = mysql_connect("localhost","root","");
if (!$con){
die("cannot connect: " . mysql_error());
}
mysql_select_db("strek", $con);
$nar_db="SELECT * FROM narocniki;";
$result = mysql_query($nar_db, $con);
while($row=mysql_fetch_array($result))
{
if($_POST['mail']==$row['mail'])
$flag = 1;
}
if($flag==0)
{
$sql = "INSERT INTO narocniki (mail) VALUE ('$_POST[mail]')";
mysql_query($sql, $con);
mysql_close($con);
?>
<p align="center" class="vsebina" >
Tvoj mail je bil uspešno sprejet!</p>
<p align="center"><input type="button" name="return" value="nazaj"></p>
<?php
}
else
{
echo '<p align="center" class="vsebina">Naveden mail je že v bazi naročnikov!</p>';
?>
<p align="center"><input type="button" name="return" value="nazaj"></p>
<?php
}
}
else
{
include("vsebina/tabdog.html");
?>
<p align="center" class="vsebina" id="mail">
naroči se na najnovejše novice</p>
<form action="dogodki.php" method="post">
<p align="center" class="vsebina">vnesi svoj e-naslov: <input type="text" name="mail" id="mail" required>
<input type="submit" name="submit" value="potrdi" onClick="return checkEmail()">
</p>
</form>
<?php
}
?>
It's probably just something missing
Should I rather just include script inside the code, and where would be the best to place it-weather directly in head or rather somewhere in between
Is this even possible in my code, because it already checks if mail exists in database, and would then also need to check the form of email
Instead of doing it in the onclick attribute of the submit button, try doing it in the onsubmit attribute of the form:
<form action="dogodki.php" method="post" onsubmit="return checkEmail()">

Codeigniter ajax request fail on output

I'm trying to make an ajax request with jquery/codeigniter. Well, there seems to be a problem. i do get it to work, but it seems like the POST is not sent, for some reason...
Javascript
$('#profileUpdateButton').click(function() {
$.ajax({ // Starter Ajax Call
method: "POST",
url: baseurl + 'profile/statusUpdate',
data: $('#statusUpdateForm').serialize(),
success: function(data) {
alert(data);
}
});
return false;
});
From the codeigniter controller
if($this->input->is_ajax_request()) {
echo $this->input->post('profileUpdate');
}
If i replace the "echo $this->" etc.. with just echo "Hello" i do get an alertbox with "Hello", why don't i get the text from the box?
html
<div id="statusUpdate">
<?php echo form_open(base_url() . 'profile/statusUpdate', array('name' => 'statusUpdateForm')); ?>
<input type="text" value="Hva tenker du på?" name="profileUpdate" id="profileUpdate" onfocus="if(this.value == 'Hva tenker du på?')this.value=''" onblur="if(this.value == '')this.value='Hva tenker du på?'" />
<input type="submit" value="" name="profileUpdateButton" id="profileUpdateButton" />
<?php echo form_close(); ?>
</div>
Change your html markup to this...
<div id="statusUpdate"> <!-- Use ID not NAME here |v| -->
<?php echo form_open(base_url() . 'profile/statusUpdate', array('id' => 'statusUpdateForm')); ?>
<input type="text" value="Hva tenker du på?" name="profileUpdate" id="profileUpdate" onfocus="if(this.value == 'Hva tenker du på?')this.value=''" onblur="if(this.value == '')this.value='Hva tenker du på?'" />
<input type="submit" value="" name="profileUpdateButton" id="profileUpdateButton" />
<?php echo form_close(); ?>
</div>
you were setting the form's name and you were selecting $('#statusUpdateForm') which means the id of statusUpdateForm, not the name attribute...

Categories