Take user id from php for change password - javascript

I have this code for change password on the personal page of the user on my website. The script working but the problem is that work's only on id "60". how I can take the id from the page and set in this code? my page is like this "www.example.com/area-personale.php?id=60". and why the script start immediately when I enter on the page and i prefer that it starts when I press on submit.
</script>
</head>
<body>
<form name="frmChange" method="post" action=""
onSubmit="return validatePassword()">
<div style="width: 500px;">
<div class="message"><?php if(isset($message)) { echo $message; } ?></div>
<table border="0" cellpadding="10" cellspacing="0"
width="500" align="center" class="tblSaveForm">
<tr class="tableheader">
<td colspan="2">Change Password</td>
</tr>
<tr>
<td width="40%"><label>Current Password</label></td>
<td width="60%"><input type="password"
name="currentPassword" class="txtField" /><span
id="currentPassword" class="required"></span></td>
</tr>
<tr>
<td><label>New Password</label></td>
<td><input type="password" name="newPassword"
class="txtField" /><span id="newPassword"
class="required"></span></td>
</tr>
<td><label>Confirm Password</label></td>
<td><input type="password" name="confirmPassword"
class="txtField" /><span id="confirmPassword"
class="required"></span></td>
</tr>
<tr>
<td colspan="2"><input type="submit" name="submit"
value="Submit" class="btnSubmit"></td>
</tr>
</table>
</div>
</form>
</body>
</html>
<?php
session_start();
$_SESSION["id_user"] = "60";
$conn = mysqli_connect("x", "x", "x", "x") or die("Connection Error: " . mysqli_error($conn));
?>
<?php
if (count($_POST) > 0) {
$result = mysqli_query($conn, "SELECT password FROM vm_users WHERE id_user='" . $_SESSION["id_user"] . "'");
$row = mysqli_fetch_array($result);
if ($_POST["currentPassword"] == $row["password"]) {
mysqli_query($conn, "UPDATE vm_users set password='" . $_POST["newPassword"] . "' WHERE id_user='" . $_SESSION["id_user"] . "'");
$message = "Password modificata";
} else
$message = "Current Password is not correct";
}
?>
<html>
<head>
<title>Change Password</title>
<link rel="stylesheet" type="text/css" href="styles.css" />
<script>
function validatePassword() {
var currentPassword,newPassword,confirmPassword,output = true;
currentPassword = document.frmChange.currentPassword;
newPassword = document.frmChange.newPassword;
confirmPassword = document.frmChange.confirmPassword;
if(!currentPassword.value) {
currentPassword.focus();
document.getElementById("currentPassword").innerHTML = "required";
output = false;
}
else if(!newPassword.value) {
newPassword.focus();
document.getElementById("newPassword").innerHTML = "required";
output = false;
}
else if(!confirmPassword.value) {
confirmPassword.focus();
document.getElementById("confirmPassword").innerHTML = "required";
output = false;
}
if(newPassword.value != confirmPassword.value) {
newPassword.value="";
confirmPassword.value="";
newPassword.focus();
document.getElementById("confirmPassword").innerHTML = "not same";
output = false;
}
return output;
}

I used this and now works!
$_SESSION["id_user"] = $_GET["id"]

Related

Real time username check with $.ajax

So I am doing a homework, in which I would like to check the username in real time, as the user types it.
It is working correctly, only when I change the content of the HTML element to "username available or not", it also displays the whole site one again there, but much smaller.
So actually in the cell ehere I want to display "available" or "not available" the whole page appears again. The proble must be the SUCCESS part of the $.ajax function, but I can not see why.
Please help me :)
Here are the codes:
Register.php:
<?php
define("HOSTNAME","localhost");
define("USERNAME","root");
define("PASSWORD","");
define("DATABASE","authentication");
//connect database
$conn = new mysqli(HOSTNAME,USERNAME,PASSWORD,DATABASE);
if($conn->connect_error){
die("Connection failed: " .$conn->connect_error);
}
if(isset($_POST['register_btn'])){
session_start();
$username = $conn->real_escape_string($_POST['username']);
$email = $conn->real_escape_string($_POST['email']);
$password = $conn->real_escape_string($_POST['password']);
$password2 = $conn->real_escape_string($_POST['password2']);
if($password == $password2 && strlen($password) > 5 && strlen($username) > 5 && strlen($email) > 5){
//create user
$password = md5($password); //hash password before storing for security purposes
$sql = "INSERT INTO users(username, email, password) VALUES('$username', '$email', '$password')";
if($conn->query($sql)){
echo "New record created successfully";
$_SESSION['message'] = "You are now logged in";
$_SESSION['username'] = $username;
header("location: home.php"); //redirect to home page
}
else{
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
else{
//failed
$_SESSION['message'] = "The two passwords do not match";
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Register</title>
<link rel="stylesheet" type="text/css" href="style.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<svg viewBox="0 0 500 37">
<path id="curve" d="M 105 33 q 150 -20 300 0" />
<text width="500">
<textPath xlink:href="#curve">az én oldalam lesz</textPath>
</text>
</svg>
<div class="header">
<h1>Register</h1>
</div>
<script type="text/javascript">
function checkUserRealTime(val){
$.ajax({
type:"POST", //type of the request to make
url:"checkUserRealTimeEx.php", //server the request should be sent
data:"username="+val, //the data to send to the server
success: function(data){ //the function to be called if the request succeeds
$("#msg").html(data);
}
});
}
</script>
<form method="post" action="register.php">
<table>
<tr>
<td>Username:</td>
<td><input type="text" name="username" class="textInput" placeholder="username" onkeyup="checkUserRealTime(this.value)"></td>
</tr>
<tr>
<td></td>
<td><p id="msg"></p></td>
<tr>
<td>Email:</td>
<td><input type="email" name="email" placeholder="E-mail address" class="textInput"></td>
</tr>
<tr>
<td>Password:</td>
<td><input type="password" name="password" placeholder="Password" class="textInput"></td>
</tr>
<tr>
<td>Password again:</td>
<td><input type="password" name="password2" placeholder="Password again" class="textInput"></td>
</tr>
<tr>
<td colspan="2"><input type="submit" name="register_btn" class="Register"></td>
</tr>
</table>
</form>
</body>
</html>
checkUserRealTimeEx.php:
<?php
require "register.php";
$username = $conn->real_escape_string($_POST["username"]);
$query = "SELECT * FROM users WHERE username='".$username."'";
$results = $conn->query($query);
$numRows = $results->num_rows;
if($numRows > 0){
echo "Username not available";
}
else{
echo "Username available";
}
?>
So as I said I am pretty sure the proble will be with the data as input value in the success part, but I don't really understand where I pass the value back to the register.php and what value data gets and where it gets from :/ If you could also explain that part to me, I would be very-very thankful :)
The issue is that the form on register.php submits to the register.php, which contains both the registration form and the logic to process the form. When you submit a form to a page (which is what you are doing here), the HTML of that page will be displayed unless you tell it to do otherwise. The cleanest way to handle this would be to have a separate page to handle the registration (as suggested by gibberish in his answer).
However, you could still have the form submit to itself as long as you hide the HTML content when registration has occurred and show some feedback instead (e.g. "Registration successsful!"). The PHP code at the top of register.php knows whether or not the form was submitted and whether or not the registration was successful. You can leverage that by setting a variable when the registration was successful (e.g. $registered=true) and use that variable to decide whether you want to display the registration form or a success message. Again, this isn't as 'clean' as two separate pages, but it is a quick workaround to solve your issue.
This updated version of register.php does what I am describing:
<?php
define("HOSTNAME","localhost");
define("USERNAME","root");
define("PASSWORD","");
define("DATABASE","authentication");
$registered = false;
$username = '';
//connect database
$conn = new mysqli(HOSTNAME,USERNAME,PASSWORD,DATABASE);
if($conn->connect_error){
die("Connection failed: " .$conn->connect_error);
}
if(isset($_POST['register_btn'])){
session_start();
$username = $conn->real_escape_string($_POST['username']);
$email = $conn->real_escape_string($_POST['email']);
$password = $conn->real_escape_string($_POST['password']);
$password2 = $conn->real_escape_string($_POST['password2']);
if($password == $password2 && strlen($password) > 5 && strlen($username) > 5 && strlen($email) > 5){
//create user
$password = md5($password); //hash password before storing for security purposes
$sql = "INSERT INTO users(username, email, password) VALUES('$username', '$email', '$password')";
if($conn->query($sql)){
echo "New record created successfully";
$_SESSION['message'] = "You are now logged in";
$_SESSION['username'] = $username;
header("location: home.php"); //redirect to home page
$registered = true; // Set the flag indicating that registration was successful
}
else{
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
else{
//failed
$_SESSION['message'] = "The two passwords do not match";
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Register</title>
<link rel="stylesheet" type="text/css" href="style.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<svg viewBox="0 0 500 37">
<path id="curve" d="M 105 33 q 150 -20 300 0" />
<text width="500">
<textPath xlink:href="#curve">az én oldalam lesz</textPath>
</text>
</svg>
<div class="header">
<h1>Register</h1>
</div>
<script type="text/javascript">
function checkUserRealTime(val){
$.ajax({
type:"POST", //type of the request to make
url:"checkUserRealTimeEx.php", //server the request should be sent
data:"username="+val, //the data to send to the server
success: function(data){ //the function to be called if the request succeeds
$("#msg").html(data);
}
});
}
</script>
<?php
if (!$registered) {
?>
<form method="post" action="register.php">
<table>
<tr>
<td>Username:</td>
<td><input type="text" name="username" class="textInput" placeholder="username" onkeyup="checkUserRealTime(this.value)"></td>
</tr>
<tr>
<td></td>
<td><p id="msg"></p></td>
<tr>
<td>Email:</td>
<td><input type="email" name="email" placeholder="E-mail address" class="textInput"></td>
</tr>
<tr>
<td>Password:</td>
<td><input type="password" name="password" placeholder="Password" class="textInput"></td>
</tr>
<tr>
<td>Password again:</td>
<td><input type="password" name="password2" placeholder="Password again" class="textInput"></td>
</tr>
<tr>
<td colspan="2"><input type="submit" name="register_btn" class="Register"></td>
</tr>
</table>
</form>
<?php
} else {
?>
<div>Registration Successful for user <?= $username ?></div>
<?php
}
?>
</body>
</html>
You cannot use the same document as the receiver for your ajax code. You must have a separate document.
(See this other answer)[values not updated after an ajax response

How do I redirect a form after submission to the same page?

I want my form to be submitted, after submitting that values it should redirect to the form and display the values. I've tried many things... but no luck yet...
So I've decided to post here. It should be like most of the edit fields, the stored value or the submitted value should appear.
This is my code:
<form method="post" name="contentUpload" action="insertContent.php" enctype="multipart/form-data">
<table>
<tr id="small">
<td>Category</td>
<td>
<select name="contentCategory">
<<option value="1">World</option>
<option value="2">Health/Env/Scn</option>
<option value="3">Travel</option>
</select>
</td>
</tr>
<tr id="small">
<td>Title</td>
<td>
<input type="text" name="contentTitle" size="80">
</td>
</tr>
<tr id="small">
<td>Writer</td>
<td>
<input type="text" name="writer" size="80">
</td>
</tr>
<tr id="small">
<td>Upload Picture</td>
<td>
<input type="file" name="fileToUpload" id="fileToUpload">
</td>
</tr>
<tr>
<td id="small">Display Mode</td>
<td required>
<input type="radio" name="status" value="Online" /> Online
<input type="radio" name="status" value="Offline" /> Offline
</td>
</tr>
<tr>
<td id="small">Final Submission</td>
<td>
<input type="submit" name="submitContent" value="Update">
<input type="reset" name="resetContent" value="Reset">
</td>
</tr>
</table>
</form>
</div>
this is my addcontent.php
<?php include ( "./inc/connect.inc.php" ); ?>
<?php
session_start();
$target_dir = "new/Images/";
$file_name = $_FILES["fileToUpload"]["name"];
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
if(isset($_POST["submitContent"]))
{
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false)
{
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
}
else
{
echo "File is not an image.";
$uploadOk = 0;
}
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0)
{
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
}
else
{
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file))
{
echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
}
else
{
echo "Sorry, there was an error uploading your file.";
}
}
if (isset($_POST['submitContent']))
{
$eid = $_SESSION['employeeId'];
$contentCategory = $_POST['contentCategory'];
$contentTitle = $_POST['contentTitle'];
$contentWriter = $_POST['writer'];
$displayMode = $_POST['status'];
$query = mysqli_query($con,"INSERT INTO contentdetails(employeeId,contentCategory,contentTitle,contentWriter,photo,displayMode,published_on)
VALUES('$eid','$contentCategory','$contentTitle','$contentWriter',
'$file_name','$displayMode',NOW())");
}
?>
in your form tag leave the action="" tag empty.
<?php
// Remove session_start() from this file. It should be before any html.
include 'insertContent.php';
if (isset($_POST['submitContent'])) {
foreach ($_POST as $p) {
echo $p . "<br>";
}
}
?>
<form method="post" name="contentUpload" action="" enctype="multipart/form-data">

My html form isn't submitting an email [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
I have a landing page (http://www.interiorswithaview.com/) that requires name, address, and phone#. After you submit the form directed to a thank you page with downloads: http://www.interiorswithaview.com/ThankYou.html
I also use a javascript (see below). I've used this template set in the past and I know its worked but now its not sending an email. I don't know if its outdated? Please help.
<script src="mail-form.js"></script>
<form method="POST" action="mailer.php" onsubmit="return ValidateRequiredFields();" name="mail">
<table width="235" height="400" border="0" bgcolor="#d1d3d4" align="center" cellpadding="0" cellspacing="0" style="font-size:13px; font-weight:bold; color:#58585b; padding:5px;">
<tbody>
<tr><td colspan="3"><img src="images/Form-header.png" width="200" height="63" alt="" align="center"/></td></tr>
<tr>
<td colspan="3">
<p align="center" style="padding:0 8px 0 8px;"><strong>Here are three informational guides to help you get started! To download these resources, just enter your information below.</strong></p>
<p>
<ul style="list-style: none; font-size: 16px; color: #d83e45;">
<li>Q & A</li>
<li>Case Study</li>
<li>Color Consultation</li>
</ul>
</p>
</td>
</tr>
<tr>
<td width="55" height="30" align="right" style="padding-right:6px;">Name:</td>
<td width="163" align="right">
<input name="Name" type="text" id="Name" size="23">
</td>
</tr>
<tr>
<td height="30" align="right" style="padding-right:6px;">Address:</td>
<td align="right"><input name="Address" type="text" id="Address" size="23"></td>
</tr>
<tr>
<td height="30" align="right" style="padding-right:6px;">Phone:</td>
<td align="right"><input name="Phone" type="text" id="Phone" size="23"></td>
</tr>
<tr>
<td height="5" align="right" style="padding-right:6px;"> </td>
<td align="right"> </td>
</tr>
<tr>
<td height="5" align="right" style="padding-right:6px;"> </td>
<td align="right"><input type="submit" name="submit" id="submit" value="Submit" /></td>
<td width="1"></td>
</tr>
</tbody>
</table>
</form>
PHP Code
<?php
if(isset($_POST['submit'])) {
$email_to = "email#gmail.com";
$subject = "New Landing Page Consult Lead";
$name_field = $_POST['Name'];
$address_field = $_POST['Address'];
$phone_field = $_POST['Phone'];
$body = "From: $name_field\n Address: $address_field\n Phone: $phone_field\n";
header('Location: ThankYou.html');
exit();
mail($to, $subject, $body, "From: $name_field");
}
else {
echo "what?";
}
?>
JavaScript
var FormName = "mail";
var RequiredFields = "Name,Phone,Address";
function ValidateRequiredFields() {
var FieldList = RequiredFields.split(",");
var BadList = new Array();
for(var i = 0; i < FieldList.length; i++) {
var s = eval('document.' + FormName + '.' + FieldList[i] + '.value');
s = StripSpacesFromEnds(s);
if(s.length < 1) {
BadList.push(FieldList[i]);
}
}
if(BadList.length < 1) {
return true;
}
var ess = new String();
if(BadList.length > 1) {
ess = 's';
}
var message = new String('\n\nThe following field' + ess + ' are required:\n');
for(var i = 0; i < BadList.length; i++) {
message += '\n' + BadList[i];
}
alert(message);
return false;
}
function StripSpacesFromEnds(s) {
while((s.indexOf(' ',0) == 0) && (s.length> 1)) {
s = s.substring(1,s.length);
}
while((s.lastIndexOf(' ') == (s.length - 1)) && (s.length> 1)) {
s = s.substring(0,(s.length - 1));
}
if((s.indexOf(' ',0) == 0) && (s.length == 1)) {
s = '';
}
return s;
}
Put the exit after the mail
header('Location: ThankYou.html');
mail($to, $subject, $body, "From: $name_field");
exit();
Try this!
Change your php code!
<?php
if(isset($_POST['submit'])) {
$email_to = "email#gmail.com";
$subject = "New Landing Page Consult Lead";
$name_field = $_POST['Name'];
$address_field = $_POST['Address'];
$phone_field = $_POST['Phone'];
$body = "From: $name_field\n Address: $address_field\n Phone: $phone_field\n";
mail($to, $subject, $body, "From: $name_field");
header('Location: ThankYou.html');
exit();
}
else {
echo "what?";
}
?>

My javascript validation just stopped working and I can't figure out why

I have been developing this page for a few days for a school project and it has been working perfectly up until about 10 minutes ago. I didn't change anything except adding an extra javascript validation. Now when I run my page and click "register" button, it registers with empty fields instead of popping up the appropriate alerts. Please help!
<?php
//Connect to database
include("dbconnect.php");
// SQL insertion if submit button is pressed
if (isset($_POST['Submit'])) {
$firstname = $_POST["firstname"];
$lastname = $_POST["lastname"];
$email = $_POST["email"];
$username = $_POST["username"];
$password1 = $_POST["password1"];
$class1 = $_POST["class1"];
$address = $_POST["address"];
$creditcard = $_POST["creditcard"];
$expiry = $_POST["expiry"];
$cvv = $_POST["cvv"];
$postcode = $_POST["postcode"];
$city = $_POST["city"];
$state = $_POST["state"];
$street = $_POST["street"];
$personcon = $conn;
$bbsSQL = "INSERT INTO TBLUSERS (FIRSTNAME, LASTNAME, EMAIL, USERNAME, PASSWORD, CLASS, ADDRESS, CREDITCARD, EXPIRY, CVV, POSTCODE, CITY, STATE, STREET) VALUES ('$firstname', '$lastname', '$email', '$username', '$password1', '$class1', '$address', '$creditcard', '$expiry', '$cvv', '$postcode', '$city', '$state', '$street')";
$personinfo = oci_parse($personcon, $bbsSQL);
oci_execute($personinfo);
oci_free_statement($personinfo);
oci_close($personcon);
//Send Email
$to = $email;
$subject = 'Registration Confirmation';
$message = 'Welcome, ' . $firstname . ' ' . $lastname . '.' . "\r\n" . "\r\n" . 'Username: ' . $username . "\r\n" . "\r\n" . 'Password: ' . $password1 . "\r\n" . "\r\n" . 'Class: ' . $class1 . "\r\n" . "\r\n";
$headers = 'From: fake#fake.com' . "\r\n" . 'X-Mailer: PHP/' . phpversion();
mail($to, $subject, $message, $headers);
//Pass the message to the login page after registration
$Message = urlencode("Thank you for your registration!");
header("Location:index.php?Message=" . $Message);
}
?>
<html>
<head>
<title>User Registration</title>
<link rel="stylesheet" type="text/css" href="style.css" />
<script type="text/javascript">
function validate()
{
//First Name
var fname = document.myForm.firstname.value;
var Vfname = /^[a-zA-Z]+$/;
if(!Vfname.test(fname)){
alert("Your last name can only contain letters.");
return false;
} else {
/* alert("Valid first name!"); */
}
//Last Name
var Lname = document.myForm.lastname.value;
var VLname = /^[a-zA-Z]+$/;
if(!VLname.test(Lname)){
alert("Your last name can only contain letters.");
return false;
} else {
/* alert("Valid last name!"); */
}
//Class
var cl = document.myForm.class1.value;
var Vcl = /^[a-zA-Z]{4}+[0-9]{3}+$/;
if (!Vcl.test(cl)){
alert("Your class must be 4 letters followed by 3 numbers.");
return false;
} else {
/* alert("Valid class!"); */
}
//Credit Card
var cc = document.myForm.creditcard.value;
var Vcc = /^[0-9]{10}+$/;
if (!Vcc.test(cc)) {
alert("Credit card number must be 10 digits.");
return false;
} else {
/* alert("Valid Credit Card!"); */
}
//Post Code
var pc = document.myForm.postcode.value;
var Vpc = /^[0-9]{4}+$/;
if (!Vpc.test(pc)) {
alert("Post code must be 4 numbers.");
return false;
} else {
/* alert("Valid Post Code!"); */
}
//Password Confirmation
var pwd1 = document.myForm.password1.value;
var pwd2 = document.myForm.password2.value;
if(pwd1!=pwd2 || pwd1=="" || pwd2==""){
alert("Password unmatched!");
return false;
}
else
alert("Password matched!");
}
}
</script>
</head>
<body>
<div class="author">
COMP344 Assignment 1 2015 <br>
Daniel Buskariol <br>
42446937
</div>
<div id="heading"> New Star Public School </div>
<br>
<form name="myForm" method="POST" onsubmit="return validate()">
<table style="width:40%" cellpadding="10" cellspacing="1" align="center">
<tr>
<th colspan="4">Enter Registration Details</th>
</tr>
<tr>
<td colspan="4"></td>
</tr>
<tr>
<td>First Name</td>
<td><input type="text" name="firstname" tabindex="1" /></td>
<td>Post Code</td>
<td><input type="text" name="postcode" tabindex="9" /></td>
</tr>
<tr>
<td>Last Name</td>
<td><input type="text" name="lastname" tabindex="2" /></td>
<td>Credit Card</td>
<td><input type="text" name="creditcard" tabindex="10" /></td>
</tr>
<tr>
<td>Email</td>
<td><input type="text" name="email" tabindex="3" /></td>
<td>Expiry</td>
<td><input type="text" name="expiry" tabindex="11" placeholder="MM/YY" /></td>
</tr>
<tr>
<td>Class</td>
<td><input type="text" name="class1" tabindex="4" /></td>
<td>CVV</td>
<td><input type="text" name="cvv" tabindex="12" /></td>
</tr>
<tr>
<td>Street Number</td>
<td><input type="text" name="address" tabindex="5" /></td>
<td>Username</td>
<td><input type="text" name="username" tabindex="13" /></td>
</tr>
<tr>
<td>Street Name</td>
<td><input type="text" name="street" tabindex="6" /></td>
<td>Password</td>
<td><input type="password" name="password1" tabindex="14" /></td>
</tr>
<tr>
<td>Suburb/City</td>
<td><input type="text" name="city" tabindex="7" /></td>
<td>Confirm</td>
<td><input type="password" name="password2" tabindex="15" /></td>
</tr>
<tr>
<td>State</td>
<td><input type="text" name="state" tabindex="8" /></td>
<td align="right"><input type="reset" name="Reset"/> </td>
<td><input type="submit" name="Submit" value="Register"/></td>
</tr>
</table>
</form>
<br>
<p> Already a member? Click here to login. </p>
</body>
</html>
Open up your developer console and it will point you to the error.
You have an extra { because you missed a { after the else. So either add a { or remove the extra }.
The regular expression is wrong because you have a + after the {3} and after the {4}. Get rid of them.
In a few places, you put a + quantifier in a regex after already providing an explicit count, e.g. var Vcl = /^[a-zA-Z]{4}+[0-9]{3}+$/; ({4}+ and {3}+). That's not legal in a regular expression. If you checked your browser console, you'd probably see a SyntaxError when the validation is performed.

How To Integrate Codeigniter Form Validation Library and file uploading in a form using jQuery AJAX ?

this is my controller file
below code is working only file uploading into path and no data is displaying in database when i gave inputs. Another doubt, It is not showing validation errors when i submit with empty inputs.
var $default_news_status = 1;
var $default_client_status = 1;
var $default_client_partner_flag = 0;
var $default_client_logo_display_flag = 1;
var $default_client_test_status = 0;
public function construct()
{
parent::__construct();
$this->load->helper(array('form', 'url', 'file'));
}
/*controlles vadmin/addnews*/
public function addnews()
{
//$status = "";
//$msg = "";
$userfile = 'userfile';
//echo '<br>entered into ajax if block.. ';
/******* extracting file extension ********/
$org_filename = $_FILES['userfile']['name'];
$path_parts = pathinfo($org_filename);
//$file_extension = $path_parts['extension'];
/***** end extracting file extension ******/
$this->load->library('form_validation');
$this->form_validation->set_rules('title', 'Title', 'trim|required|min_length[5]');
$this->form_validation->set_rules('description', 'Description', 'trim|required');
$this->form_validation->set_rules('url', 'URL', 'trim|required');
$this->form_validation->set_rules('userfile', 'Image', 'trim');
$this->form_validation->set_rules('postedon', 'Posted On', 'trim|required');
$this->form_validation->set_rules('source', 'Source','trim|required|min_length[5]|max_length[12]');
$this->form_validation->set_rules('expiredate', 'Expire Date', 'trim|required');
if($this->form_validation->run() == FALSE)
{
echo json_encode(array('status'=>0, 'msg' => validation_errors()));
}
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 1024 * 1000;
//$config['file_name'] = 'client_'.time().'.'.$file_extension;
//echo "<pre>";
//print_r($_FILES);
$this->load->library('upload', $config);
if (!$this->upload->do_upload($userfile))
{
echo '<br>entered into upload failed block.. ';
$error = array('error' => $this->upload->display_errors());
echo json_encode($error);
}
else
{
echo '<br>entered into upload success block.. ';
/*$data = $this->upload->data();
echo "<pre>";
print_r($data);*/
/**** assignment of post data ******/
$title = $this->input->post('title');
$description = $this->input->post('description');
$url = $this->input->post('url');
$userfile = $this->input->post('userfile');
$postedon = $this->input->post('postedon');
$source = $this->input->post('source');
$expiredate = $this->input->post('expiredate');
$status = $this->default_news_status ;
/**** end assignment of post data ******/
/**** load news model to insert reocrd into table *****/
$this->load->model('vadmin/Newsmodel','',true);
$this->Newsmodel->addRequestForm();
/**** load news model to insert reocrd into table *****/
//print jsone response for ajax request
echo json_encode(array('status'=>0, 'msg' => 'Successfully Submitted'));
}
}
here is my view form
and js file is given below
<form method="post" action="" name="newsform" id="newsform" enctype= "multipart/form-data" >
<input type="hidden" value="" id="id" name="id" required="true">
<table width="580" cellpadding="5" cellspacing="5">
<tr>
<td width="130" align="left"><span class="required">*</span>Title</td>
<td align="left"><input name="title" type="text" id="title" style="width:250px;" value="<?php echo $news_title; ?>"/></td>
</tr>
<tr>
<td width="130" align="left"><span class="required">*</span>Description</td>
<td align="left"><textarea name="description" rows="8" cols="40" id="description" style="width:250px;" ><?php echo $news_description; ?></textarea></td>
</tr>
<tr>
<td width="130" align="left"><span class="required">*</span>URL</td>
<td align="left"><input name="url" type="text" id="url" style="width:250px;" value="<?php echo $news_url; ?>" /></td>
</tr>
<tr>
<td width="130" align="left"><span class="required">*</span>Image</td>
<td align="left"><input name="userfile" type="file" id="userfile" style="width:250px;" value="<?php echo $news_image; ?>" /></td>
<tr>
<td width="130" align="left"><span class="required">*</span>Posted On</td>
<td align="left"><input name="postedon" id="datepicker" style="width:250px;" value="<?php echo $news_posted_on; ?>" /></td>
</tr>
<tr>
<td width="130" align="left"><span class="required">*</span>Source</td>
<td align="left"><input name="source" type="text" id="source" style="width:250px;" value="<?php echo $news_source; ?>" /></td>
</tr>
<tr>
<td width="130" align="left"><span class="required">*</span>Expire Date</td>
<td align="left"><input name="expiredate" id="datepicker1" style="width:250px;" value="<?php echo $news_expire_date; ?>"/></td>
</tr>
<td colspan="2" align="left"><input type="submit" value="Submit" id="submit" onclick="return ajaxFileUpload();" />
<input type="reset" value ="reset" id="reset" /><span id="loading" >Please wait ..</span></td>
</tr>
</table>
<input type="hidden" name="nid" id="nid" value="<?php echo $news_id; ?>" />
</form>
here is my script
$.ajaxFileUpload
(
{
url:'<?php echo base_url();?>vadmin/ajax/addnews/',
secureuri:false,
fileElementId:'userfile',
dataType: 'json',
data: $("#newsform").serialize(),
beforeSend:function()
{
$("#loading").show();
},
complete:function()
{
$("#loading").hide();
},
success: function (resp)
{
if(resp.status == 0)
{
$('#message').css('color','red');
$('#message').html(resp.error).show(400);
}
if(resp.status == 1)
{
$('#message').css('color','green');
$('#message').html(resp.msg).show(400);
}
if(typeof(resp.error) != 'undefined')
{
if(resp.error != '')
{
alert(resp.error);
}else
{
alert(resp.msg);
}
}
},
/*error: function (resp, status, e)
{
alert('ajax error :: '+e);
} */
}
);
try like this
$data = $this->upload->data(); //remove comment
/*echo "<pre>";
print_r($data);*/
/**** assignment of post data ******/
$title = $this->input->post('title');
$description = $this->input->post('description');
$url = $this->input->post('url');
$userfile = $data['file_name']; // add this line
$postedon = $this->input->post('postedon');
$source = $this->input->post('source');
$expiredate = $this->input->post('expiredate');
$status = $this->default_news_status ;
for error try like this
if($this->form_validation->run() == FALSE)
{
echo json_encode(array('status'=>0, 'msg' => validation_errors()));
exit;
}

Categories

Resources