File submission worked until I added jQuery, whats the issue? - php

I am having a strange issue where I was able to submit files and successfully upload them, now that I have added this bit of jQuery within the head of the webpage, it doesn't seem to work anymore:
I tested once again without the jQuery and it works perfectly fine, my jQuery is messing with it somewhere. Anyway I can accomplish the same objective, differently?
Jquery:
$(document).ready(function() {
var options = $('select[name=itemType]');
var optionVal = options.val();
var filer = $('input[name=itemFile');
var filerVal = $('input[name=itemFile]').val();
options.change(function() {
optionVal = $(this).val();
if(optionVal == 1 || optionVal == 3) {
$('input[name=itemContact]').removeAttr('disabled');
$('input[name=itemContact]').attr('required','true');
} else {
$('input[name=itemContact]').attr('disabled','true');
$('input[name=itemContact]').removeAttr('required');
};
if(optionVal != 5) {
$('input[name=itemFile]').removeAttr('disabled');
$('span.inputFile').css("display","block");
} else {
$('input[name=itemFile]').attr('disabled','true');
$('span.inputFile').css("display","none");
};
});
filer.change(function() {
filerVal = $(this).val();
$(this).parent().text(filerVal);
});
});
HTML Form:
Note: $sectionName is defined earlier throughout the webpage, and does work.
<form class="col-12" method="post" action="./action.php?upload" enctype="multipart/form-data">
<p class="head">Upload to <i><?php echo $sectionName; ?></i></p>
<div class="con">
<input name="sectionID" type="hidden" value="<?php echo $section; ?>" required />
<select name="itemType" required>
<option selected disabled>Select an Item Type</option>
<option value="1">Downloadable, Contact</option>
<option value="2">Downloadable</option>
<option value="3">Installable, Contact</option>
<option value="4">Installable</option>
<option value="5">Browsable</option>
</select>
<span class="inputFile" style="display:none;">
Select a File
<input name="itemFile" type="file" required />
</span>
<input name="itemName" type="text" placeholder="Enter Item Name" required />
<input name="itemContact" type="email" placeholder="Enter Contact Email Address" disabled />
<button type="submit">Submit</button>
</div>
</form>
action.php?upload:
$fileDir = "./uploads/";
$fileName = preg_replace("/[^A-Z0-9._-]/i", "_", $_FILES['itemFile']["name"]);
$itemDir = $fileDir. $fileName;
$sectionID = $_POST['sectionID'];
$itemName = $_POST['itemName'];
$itemType = $_POST['itemType'];
$itemContact = $_POST['itemContact'];
if (file_exists($itemDir)) {
echo '<p class="alert">Sorry, file already exists</p>';
} else {
if (move_uploaded_file($_FILES["itemFile"]["tmp_name"], $itemDir)) {
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
if($createItem = $con->prepare("INSERT INTO items(sectionID,itemName,itemType,itemDir) VALUES(?,?,?,?)")) {
$createItem->bind_param("isis", $sectionID,$itemName,$itemType,$itemDir);
if($createItem->execute()) {
$itemID = $createItem->insert_id;
if($itemType == 1 || $itemType == 3) {
if($createContact = $con->prepare("INSERT INTO contacts(itemID,itemContact) VALUES(?,?)")) {
$createContact->bind_param("is", $itemID,$itemContact);
if($createContact->execute()) {
echo '<p class="alert">Item Created</p>';
} else {
echo "<p class=alert'>Execute failed: [createContact] (" . $createContact->errno . ") " . $createContact->error. '</p>';
};
} else {
echo '<p class="alert">Item Created</p>';
};
$createContact->close();
};
};
};
$createItem->close();
};
};
Rather than uploading the file, or storing it in $_FILES it doesn't even get passed to action.php. I have checked $_POST and $_FILES, it doesn't show up in either, whereas before it did.
Note: This is an internal website on one of my web servers, so it doesn't matter if it is vulnerable to SQL Injection.

Selector is not valid at this line
var filer = $('input[name=itemFile');
var filer = $('input[name=itemFile ] ');

Related

Why Am I getting the error Unexpected token < in JSON at position 0 parsererror?

All I have a form that submits data to a PHP file which inserts the post data into a CSV file, I'm upgrading this form to work with ajax so the user doesn't have to refresh the page upon a submission,
But I'm having an issue Im getting the error
Unexpected token < in JSON at position 0 parsererror
and Im not entirely sure what it means I've tested this form on the my dev server and it worked a charm and I copied it accross and made a few tiny tweaks the form ID its fields to validate etc, but now Im getting the error and Im not sure why, any ideas ?
<form id="form2" name="form2">
<div id="response"></div>
<table>
<tr><td><input type="text" name="fname" id="fname" placeholder="First Name"/></td><td><input type="text" name="lname" id="lname" class="required" placeholder="Surname"/></td></tr>
<tr><td><input type="text" name="email" id="email" placeholder="Email"/></td><td><input type="text" name="postcode" id="postcode" placeholder="Postcode"/></td></tr>
<tr><td colspan="2">
<p>Safe Combination</p>
<select name="number1">
<option value="0">0</option>
<option value="1">1</option>
...
</select>
<select name="number2">
<option value="0">0</option>
<option value="1">1</option>
...
</select>
<select name="number3">
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
...
</select>
<select name="number4">
<option value="0">0</option>
<option value="1">1</option>
...
</select>
<select name="number5">
<option value="0">0</option>
<option value="1">1</option>
...
</select>
<select name="number6">
<option value="0">0</option>
<option value="1">1</option>
...
</select></td></tr>
<tr><td colspan="2"><input class="btn btn-danger" type="submit" value="SUBMIT" id="submit" name="submit"/></td></tr>
</table>
</form>
JS
<script src="https://code.jquery.com/jquery-3.1.0.min.js" integrity="sha256-cCueBR6CsyA4/9szpPfrX3s49M9vUU5BgtiJj06wt/s=" crossorigin="anonymous"></script>
<script type="text/javascript">
$(document).ready( function(){
$('form#form2').submit(function (e) {
e.preventDefault();
// Get the Login Name value and trim it
var fname = $.trim($('#fname').val());
var lname = $.trim($('#lname').val());
var email = $.trim($('#email').val());
var postcode = $.trim($('#postcode').val());
// Check if empty of not
var valid = '';
if (fname === '') {
//alert('First Name is empty.');
valid+ 'First Name is empty.';
//return false;
}
if (lname === '') {
//alert('Last Name is empty.');
valid+ 'Last Name is empty.';
//return false;
}
if (email === '') {
//alert('Email is empty.');
valid+ 'Email is empty.';
//return false;
}
if (postcode === '') {
//alert('Postcode is empty.');
valid+ 'Postcode is empty.';
//return false;
}
if(valid != '') {
$('#form2 #response').addClass('alert alert-danger').html("Errors - " + valid)
} else {
$('#form2 #response').removeClass('alert alert-danger').addClass('alert alert-warning').html("<i class='fa fa-spinner fa-spin'></i> Processing the form");
var formData = $('#form2').serialize();
submitForm(formData);
}
});
});
function submitForm(formData) {
$.ajax({
type: 'POST',
url: 'comp/checker.php',
data: formData,
dataType: 'json',
cache: false,
timeout: 7000,
success: function(data) {
$('#form2 #response').removeClass('alert alert-warning').addClass((data.error === true) ? 'alert alert-danger' : 'alert alert-success').html(data.msg);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
$('#form2 #response').html('Something else went wrong :/ ' + errorThrown + textStatus);
},
complete: function(XMLHttpRequest, status) {
$('#form2')[0].reset();
}
});
}
</script>
PHP File
<?php
//header('Content-type: application/json');
sleep(5);
//if (!empty($_POST)) {
$date = date("d/m/Y");
$fname = trim($_POST['fname']);
$lname = trim($_POST['lname']);
$email = trim($_POST['email']);
$postcode = trim($_POST['postcode']);
$number1 = $_POST['number1'];
$number2 = $_POST['number2'];
$number3 = $_POST['number3'];
$number4 = $_POST['number4'];
$number5 = $_POST['number5'];
$number6 = $_POST['number6'];
$totalnumber = $number1 . '' . $number2 . '' . $number3 . '' . $number4 . '' . $number5 . '' . $number6;
$list = array("$date, $fname, $lname, $email, $postcode, $totalnumber");
$file = fopen("contacts_2.csv","a");
foreach ($list as $line) {fputcsv($file,explode(',',$line));}
fclose($file);
//HEADER TO INDEX.PHP
$return['error'] = false;
$return['msg'] = "<p>Thanks for your feedback</p>";
echo json_encode($return);
exit();
//} else {
// $return['error'] = true;
// $return['msg'] = "<p>Something went wrong, please retry in a few minutes</p>";
// echo json_encode($return);
// exit();
//}
?>
The response that you are receiving from the server is not a valid json.
You are probably getting the response in xml format.
This could be due to an error being generated by the php page. Check if the response is generated by the php page. Also check if the php page has adequate permissions to execute on the production server.
Check the browser console to see the response generated by the php file.
I kept getting this error:
"Unexpected token < in JSON at position 0"
Solution:
I was sending a number from javascript (via ajax with dataType: "json",) to php.
What I didn't realize was that the number would be converted to a string before reaching the php.
So, in order to use that sent value for doing queries etc. on the php side, I needed to convert it back to a number by using intval:
$gender = intval($_POST["gender"]);
If Wordpress try this function: wp_send_json() it worked for me.

Pass form field values data to another page with php

I have two PHP pages: index.php and thankyou.php. In index.php, there is a form. I am validating form with Javascript and ajax and the form values are being inserted into database. After database query I am redirecting this form to Thankyou.php. What i want is to pass form field values to thankyou.php. Please find below the complete code. :
Sql query running in header :-
?php
error_reporting(0);
include_once('cc/connect.php');
if($_SERVER['REQUEST_METHOD'] === 'POST')
{
$str="insert into registration(fname,lname,email,mobile_number,code,designation,organization,comps,city,affid,date_time,status)values('".mysql_escape_string($_POST['txtfname'])."','".mysql_escape_string($_POST['txtlname'])."','".mysql_escape_string($_POST['txtemail'])."','".mysql_escape_string($_POST['txtmobilenumber'])."','".mysql_escape_string($_POST['txtcode'])."','".mysql_escape_string($_POST['desig'])."','".mysql_escape_string($_POST['org'])."','".mysql_escape_string($_POST['comps'])."','".mysql_escape_string($_POST['txtcity'])."','".mysql_escape_string($_POST['txtaff'])."',now(),0)";
$rslt=mysql_query($str);
if(!$rslt)
{
echo '<script type="text/javascript">
alert("We are experiencing some issues, please try later");
</script>
';
}
else
{
echo '<script type="text/javascript">
window.location.href="thankyou.php";
</script>
';
}
}
?>
Javascript Validation :-
<script type="text/javascript">
function validate_form()
{
var pattern =/^[a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
var mob=/^(\+91[\-\s]?)?[89]\d{9}$/;
if(document.getElementById('txtfname').value=="" || document.getElementById('txtfname').value==null)
{
alert("Please enter First Name");
document.getElementById('txtfname').focus();
return false;
}
if(document.getElementById('txtlname').value=="" || document.getElementById('txtlname').value==null)
{
alert("Please enter Last Name");
document.getElementById('txtlname').focus();
return false;
}
if(document.getElementById('txtemail').value=="" || document.getElementById('txtemail').value==null)
{
alert("Please enter the Email");
document.getElementById('txtemail').focus();
return false;
}
if(!pattern.test(document.getElementById('txtemail').value))
{
alert("Please enter the valid Email");
document.getElementById('txtemail').focus();
return false;
}
if(document.getElementById('txtmobilenumber').value=="" || document.getElementById('txtmobilenumber').value==null)
{
alert("Please enter the Mobile Number");
document.getElementById('txtmobilenumber').focus();
return false;
}
if(document.getElementById('txtcode').value=="" || document.getElementById('txtcode').value==null)
{
alert("Please enter verification code");
document.getElementById('txtcode').focus();
return false;
}else
{
check_existence(document.getElementById('txtcode').value,6);
}
if(document.getElementById('comps').value=="" || document.getElementById('comps').value==null)
{
alert("Please enter Company strength");
document.getElementById('comps').focus();
return false;
}
if(!isNaN(document.getElementById('comps').value))
{
alert("Please select the valid Company strength");
document.getElementById('comps').value='';
document.getElementById('comps').focus();
return false;
}
if(document.getElementById('org').value=="" || document.getElementById('org').value==null)
{
alert("Please enter Organization");
document.getElementById('org').focus();
return false;
}
if(document.getElementById('txtcity').value=="" || document.getElementById('txtcity').value==null)
{
alert("Please enter the city");
document.getElementById('txtcity').focus();
return false;
}
if(!isNaN(document.getElementById('txtcity').value))
{
alert("Please enter the valid city");
document.getElementById('txtcity').value='';
document.getElementById('txtcity').focus();
return false;
}
}
function check_existence(val,caseno)
{
var pattern = /^[a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
var mob=/^(\+91[\-\s]?)?[789]\d{9}$/;
var xmlhttp;
if(caseno=="1")
{
if(!pattern.test(document.getElementById('txtemail').value))
{
alert("Please enter the valid email");
document.getElementById('txtemail').value='';
document.getElementById('txtemail').focus();
return false;
}
}
if(caseno=="2")
{
if(!mob.test(document.getElementById('txtmobilenumber').value))
{
alert("Please enter the valid mobile number");
document.getElementById('txtmobilenumber').value='';
document.getElementById('txtmobilenumber').focus();
return false;
}
}
if(caseno=="3")
{
if(!mob1.test(document.getElementById('txtname').value))
{
alert("Please enter the valid mobile number");
document.getElementById('txtname').value='';
document.getElementById('txtname').focus();
return false;
}
}
if(window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP")
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
if(xmlhttp.responseText=="1")
{
alert("Email address already exists");
document.getElementById('txtemail').value='';
document.getElementById('txtemail').focus();
}
if(xmlhttp.responseText=="2")
{
alert("Verification code has been sent to your mobile");
document.getElementById('txtcode').focus();
}
if(xmlhttp.responseText=="3")
{
document.forms["formsms"].submit();
}
if(xmlhttp.responseText=="4")
{
alert("Please enter the valid verification code");
document.getElementById('txtcode').focus();
}
if(xmlhttp.responseText=="5")
{
alert("Mobile Number already exists");
document.getElementById('txtmobilenumber').value='';
document.getElementById('txtmobilenumber').focus();
}
}
}
xmlhttp.open("GET","ajax_file.php?caseno="+caseno+"&val="+val,true);
xmlhttp.send();
}
</script>
Form Code :-
<div class="form-content">
<form class="form-box register-form form-validator" id="formsms" name="formsms" method="post">
<div class="form-group">
<label>First name: <span class="required">*</span></label>
<input class="form-control" type="text" name="txtfname" id="txtfname" required>
</div>
<div class="form-group">
<label>Last name: <span class="required">*</span></label>
<input class="form-control" type="text" name="txtlname" id="txtlname" required>
</div>
<div class="form-group">
<label>Email: <span class="required">*</span></label>
<input class="form-control" type="email" name="txtemail" id="txtemail" onchange="return check_existence(this.value,1);" required>
</div>
<div class="form-group">
<div style="float:left; width:270px;" >
<label>Mobile: <span class="required">*</span></label>
<input class="form-control" type="text" name="txtmobilenumber" id="txtmobilenumber" onchange="return check_existence(this.value,2);" required>
</div>
<div style="float:right">
<label>Verification Code: <span class="required">*</span></label>
<input class="form-control" type="text" name="txtcode" id="txtcode" required>
</div>
</div>
<div style="clear:both;"></div>
<div class="form-group">
<label>Select Graduation: <span class="required">*</span></label>
<select class="form-control" name="comps" id="comps">
<option>Select...</option>
<option value="BA">BA</option>
<option value="BBA">BBA</option>
<option value="BCom">BCom</option>
<option value="BSC">BSC</option>
<option value="BTech">BTech</option>
<option value="Other">Other</option>
</select>
</div>
<div class="form-group">
<label>Graduation%: <span class="required">*</span></label>
<input class="form-control" type="text" name="org" id="org" required>
</div>
<div class="form-group">
<label>City: <span class="required">*</span></label>
<input class="form-control" type="text" name="txtcity" id="txtcity" required>
</div>
<div class="buttons-box clearfix">
<input type="button" id="btnsubmit" name="btnsubmit" class="btn btn-default" value="Submit" onclick="return validate_form()"/>
<span class="required"><b>*</b> Required Field</span>
<br>
</div>
</form><!-- .form-box -->
</div>
The simplest way is to use PHP sessions. These will store data from one interaction with the user, to be retrieved on another interaction.
In connect.php, add:
session_start();
In index.php, after you've validated and saved info in the DB, save the data that you want to pass between pages in the $_SESSION array
$_SESSION['fname'] = $_POST['txtfname'];
....
It's actually better to save things to session after you've done all string manipulation (eg: after applying mysql_escape_string).
Now, whenever the user makes another request, you can find the data in that same array. So on thankyou.php
$fname = $_SESSION['fname'];
...
Here is a basic intro to sessions.
This next note goes beyond your question but it's one really important lesson: sessions rely on cookies to recognize a user when he makes another visit. This means that a savvy user can manipulate this cookie and break his session or try to present himself as someone else in order to bypass your security restrictions. Once you're comfortable with the basics, look into how to use sessions securely!
This sounds like a typical case when $_SESSION may come in handy. In this Case (since you are doing your thing with AJAX), you may want to handle the Session in your AJAX Processing PHP File... (header.php?) Well here's how:
<?php
// FILE-NAME: header.php //<== THE AJAX PROCESSING SCRIPT
//FIRST CHECK IF SESSION EXIST BEFORE STARTING IT:
if (session_status() == PHP_SESSION_NONE || session_id() == '') {
session_start();
}
error_reporting(0);
include_once('cc/connect.php');
if($_SERVER['REQUEST_METHOD'] === 'POST') {
// JUST START SETTING UP THE SESSION DATA IF DATA WAS POSTED...
$_SESSION['fname'] = htmlspecialchars(trim($_POST['txtfname']));
$_SESSION['lname'] = htmlspecialchars(trim($_POST['txtlname']));
$_SESSION['email'] = htmlspecialchars(trim($_POST['txtemail']));
$_SESSION['mobile_number'] = htmlspecialchars(trim($_POST['txtmobilenumber']));
$_SESSION['code'] = htmlspecialchars(trim($_POST['txtcode']));
$_SESSION['designation'] = htmlspecialchars(trim($_POST['desig']));
$_SESSION['organization'] = htmlspecialchars(trim($_POST['org']));
$_SESSION['comps'] = htmlspecialchars(trim($_POST['comps']));
$_SESSION['city'] = htmlspecialchars(trim($_POST['txtcity']));
$_SESSION['affid'] = htmlspecialchars(trim($_POST['txtaff']));
$_SESSION['date_time'] = date("Y-m-d", time());
$_SESSION['status'] = "0";
$str="insert into registration(fname,lname,email,mobile_number,code,designation,organization,comps,city,affid,date_time,status)values('".mysql_escape_string($_POST['txtfname'])."','".mysql_escape_string($_POST['txtlname'])."','".mysql_escape_string($_POST['txtemail'])."','".mysql_escape_string($_POST['txtmobilenumber'])."','".mysql_escape_string($_POST['txtcode'])."','".mysql_escape_string($_POST['desig'])."','".mysql_escape_string($_POST['org'])."','".mysql_escape_string($_POST['comps'])."','".mysql_escape_string($_POST['txtcity'])."','".mysql_escape_string($_POST['txtaff'])."',now(),0)";
$rslt=mysql_query($str);
//... THE REST OF YOUR CODE...
}
Then, inside of thankyou.php, you can do this:
<?php
// FILE-NAME: thankyou.php
//FIRST CHECK IF SESSION EXIST BEFORE STARTING IT:
if (session_status() == PHP_SESSION_NONE || session_id() == '') {
session_start();
}
// TO GET THE EMAIL, FIRST & LAST NAMES HERE, YOU CAN SIMPLE DO LIKE SO:
$email = isset( $_SESSION['email'] )? $_SESSION['email'] : "";
$firstName = isset( $_SESSION['fname'] )? $_SESSION['fname'] : "";
$lastName = isset( $_SESSION['lname'] )? $_SESSION['lname'] : "";
// ASSUMING YOU WANT TO THANK THE USER BY NAME:
// YOU MAY DO SOMETHING LIKE SO:
$thankYou = "<div class='thank-you'>" . PHP_EOL;
$thankYou .= "<p class='appreciation'>Thank you, " ;
$thankYou .= "<span class='user-name'>{$firstName} {$lastName}</span>";
$thankYou .= " for your E-Mail... bla...bla..</p>" .PHP_EOL;
$thankYou = "</div>" . PHP_EOL;
echo $thankYou;

stop form from submitting (tried e.preventDefault() after $.post but it stops form from submitting

I have this in javascript
$('#submit').on('click', function(e) {
$('#message_line').text("");
if(validate_fields_on_submit()) {
e.preventDefault();
return;
}
// e.preventDefault();
var params = $('form').serialize();
$.post('check_duplicate.php', params, function(responseText) {
submitHandler(responseText);
});
// e.preventDefault();
//return false;
});
function submitHandler(response) {
$('#message_line').text("");
response = $.trim(response);
if(response == "" && response.indexOf("<") <= -1)
$('#registration').submit();
else if(response.indexOf("<") == 0) {
var name = $('[name="regusername"]').val();
$('#message_line').text("Some error occured, please try after some time.");
$("#message_line").attr("tabindex",-1).focus();
return false;
} else {
var name = $('[name="regusername"]').val();
var arr = response.split(',');
arr.pop();
arr.toString();
$('#message_line').text("'" + name + "' already exists, Please try different username");
$("#regusername").focus();
return false;
}
$('#busy_wait').css('display','none');
}
HTML CODE
<?php
session_start();
if ($_SERVER["REQUEST_METHOD"] == "POST") {
include("db/helper_functions.php");
if(validate_fields()) {
if(!check_duplicate($_POST["regusername"])) {
$count = insert_record($_POST["fname"],$_POST["lname"],$_POST["email"],$_POST["regusername"],$_POST["regpassword"]);
if($count > 0) {
include("includes/confirmation.php");
exit();
}
else {
$error = "Sorry registration failed, please try again.";
}
}
else {
$error = "Username already exists, please try different username.";
}
}
}
$page_title = "Registration";
if(isset($_SESSION["username"]))
include('includes/header_authorized.html');
else
include('includes/header.html');
?>
<div class="container">
<div class="regform">
<form name="registration" id="registration" method="post" action="registration.php">
<p><span class="req">* required field.</span></p>
<ul>
<li><label for="fname">First Name:</label>
<input type="text" class="textboxborder" id="fname" name="fname" size="20" maxlength="25" autofocus="autofocus" value="<?php if(isset($_POST['fname'])) echo $_POST['fname'];?>"/>
<span class="error" id="errfname">*<?php if(isset($errfname)) echo $errfname;?></span>
</li>
<li><label for="lname">Last Name:</label>
<input type="text" class="textboxborder" id="lname" name="lname" size="20" maxlength="25" value="<?php if(isset($_POST['lname'])) echo $_POST['lname'];?>"/>
<span class="error" id ="errlname">*<?php if(isset($errlname)) echo $errlname;?></span>
</li>
<li><label for="email">Email:</label>
<input type="text" class="textboxborder" name="email" id="email" size="40" maxlength="50" placeholder="abc#xyz.com" value="<?php if(isset($_POST['email'])) echo $_POST['email'];?>"/>
<span class="error" id="erremail">*<?php if(isset($erremail)) echo $erremail;?></span>
</li>
<li><label for="regusername">Username:</label>
<input type="text" name="regusername" id="regusername" size="20" maxlength="30" value="<?php if(isset($_POST['regusername'])) echo $_POST['regusername'];?>"/>
<span class="error" id="errregusername">*<?php if(isset($errregusername)) echo $errregusername;?></span>
</li>
<li><label for="regpassword">Password:</label>
<input type="password" name="regpassword" id="regpassword" size="20" maxlength="15" value="<?php if(isset($_POST['regpassword'])) echo $_POST['regpassword'];?>"/>
<span class="error" id="errregpassword">*<?php if(isset($errregpassword)) echo $errregpassword;?></span>
</li>
<li><label for="regconpassword">Confirm Password:</label>
<input type="password" name="regconpassword" id="regconpassword" size="20" maxlength="15"/>
<span class="error" id="errregconpassword">*<?php if(isset($errregconpassword)) echo $errregconpassword;?></span>
</li>
</ul>
<div id="message_line"> <?php if(isset($error)) echo $error;?></div>
<div class="buttons">
<input type="reset" value="Reset" id="reset"/>
<input type="submit" value="Submit" />
</div>
</form>
<img src="images/loading.gif" id="busy_wait" alt="busy wait icon" />
</div>
</div>
</body>
</html>
If in submit handler control goes in else if or else block form submission does not stop,I tried return false; and I tried using e.preventDefault(); at different places before ajax call and after but that stops form submission even after validation success and successful return from check_duplicate.php
Any help would be appreciated.
Assuming you have a submit button with id=submit, I would
rename the button since calling anything submit is poor practice since you need to actually submit the form programatically.
move the handler to the form submit event - I personally NEVER attach a handler to a submit button
I assume you do NOT want to submit if the validation returns false
Like this
$('#registration').on('submit', function(e) {
e.preventDefault();
$('#message_line').text("");
if(!validate_fields_on_submit()) { // I assume you meant NOT
return;
}
var params = $(this).serialize();
$.post('check_duplicate.php', params, function(responseText) {
submitHandler(responseText);
});
});
the post can be written
$.post('check_duplicate.php', params, submitHandler);
UPDATE Here is the complete script - NOTE IMPERATIVE to rename anything name=submit or id=submit to something else
$(function() {
$('#registration').on('submit', function(e) {
e.preventDefault();
$('#message_line').text("");
if(!validate_fields_on_submit()) { // I assume you meant NOT
return;
}
$('#busy_wait').show();
$.post('check_duplicate.php', $(this).serialize(), function(response) {
response = $.trim(response);
if (response == "" && response.indexOf("<") <= -1) {
$('#registration').submit(); // actually submit the form
}
else if(response.indexOf("<") == 0) {
var name = $('[name="regusername"]').val();
$('#message_line').text("Some error occured, please try after some time.");
$("#message_line").attr("tabindex",-1).focus();
} else {
var name = $('[name="regusername"]').val();
$('#message_line').text("'" + name + "' already exists, Please try different username");
$("#regusername").focus();
}
$('#busy_wait').hide();
});
});
Update3:
$(function() {
$('#registration').on('submit', function(e) {
e.preventDefault();
$('#message_line').text("");
if(!validate_fields_on_submit()) { // I assume you meant NOT
return;
}
$('#busy_wait').show();
var $thisForm=$(this); // save for later
var params = $thisForm.serialize();
$.post('check_duplicate.php', params, function(response) {
response = $.trim(response);
if (response == "" && response.indexOf("<") <= -1) {
// actually submit the form
$.post($thisForm.prop("action"), params, function(response) {
if (response.indexOf("success") !=-1) {
$('#message_line').text(response);
}
else {
$('#message_line').text("something went wrong");
}
$('#busy_wait').hide();
});
}
else if(response.indexOf("<") == 0) {
var name = $('[name="regusername"]').val();
$('#message_line').text("Some error occured, please try after some time.");
$("#message_line").attr("tabindex",-1).focus();
} else {
var name = $('[name="regusername"]').val();
$('#message_line').text("'" + name + "' already exists, Please try different username");
$("#regusername").focus();
}
$('#busy_wait').hide();
});
});
To prevent form submission the best method will be to return false on the onclick client event
Eg
$('#submit').click(function(){
return false;
})

HTML form with 2 (hidden) submit buttons and 1 other hidden input

I'm trying to build this application that runs on Android tablets with barcode scanners attached.
The barcode scanners send an Enter after each scanned code.
I need to scan 2 barcodes and submit the form.
I created a form with two sets of input + submit button, the second one hidden. After the first barcode is scanned and the scnner send the Enter key, the hidden elements are revealed and I can scan the second barcode. However, the second time the Enter key doesn't work. It only work if I push the button (after I unhide it).
How can I take care of this so it will not need user input (other than scanning barcodes)?
Here's my code so far:
<form action="barcode.php" method="post" class="pure-form" style="width:100%">
<fieldset>
<legend>Scaneaza o fisa noua de <?php echo $operation; ?>:</legend>
<input type="text" name="barcode" autofocus id="InputID" placeholder="Codul de bare" style="width:100%;font-size:2em">
<button style="width:0;visibility:hidden;" type="submit" onclick="show_popup('my_popup'); return false;"></button>
<div id="my_popup" style="display:none;border:3px dotted gray;padding:.3em;background-color:white;position:absolute;width:80%;height:20%;margin:-50px 50px 0 50px;">
<legend>Introdu numarul de KO-uri:</legend>
<input type="text" name="kos" autofocus id="InputID" placeholder="KO-uri" style="width:100%;font-size:2em">
<button type="submit" class="pure-button pure-button-primary" style="/*width:0;visibility:hidden;*/" onclick="hide_popup('my_popup'); return true;">Trimite</button>
</div>
</fieldset>
</form>
<script type="text/javascript">
function FocusOnInput() { document.getElementById("InputID").focus(); }
function show_popup(id) {
if (document.getElementById){
obj = document.getElementById(id);
if (obj.style.display == "none") {
obj.style.display = "";
}
}
}
function hide_popup(id){
if (document.getElementById){
obj = document.getElementById(id);
if (obj.style.display == ""){
obj.style.display = "none";
}
}
}
</script>
And the barcode.php file:
<?php
ob_start();
mysql_connect ("localhost","root","root") or die (mysql_error());
mysql_select_db ("eficacitate");
$barcode = $_POST["barcode"];
$kos = $_POST["kos"];
$marca = $_COOKIE["marca"];
$operation = $_COOKIE["operation"];
if (substr($barcode,0,1)=="^") {
$j_nou = substr($barcode,1,strpos($barcode, "|")-1);
$parts = explode('|',$barcode);
$of_nou = $parts[1];
$cantitate_nou = $parts[2];
$serie_nou = $parts[3];
$adauga="INSERT INTO master (marca, operation,j,of,cantitate,serie,kos)
VALUES
('$marca','$operation','$j_nou','$of_nou','$cantitate_nou','$serie_nou','$kos')";
mysql_query($adauga);
}
header('Location: /eficacitate/scan.php');
ob_flush();
?>
Please give this a try:
<form action="barcode.php" method="post" class="pure-form" style="width:100%">
<fieldset>
<legend>Scaneaza o fisa noua de <?php echo $operation; ?>:</legend>
<input type="text" name="barcode" autofocus id="InputID" placeholder="Codul de bare" style="width:100%;font-size:2em">
<button id='barcodeButton' style="width:0;visibility:hidden;" type="submit" onclick="show_popup('my_popup'); return false;"></button>
<div id="my_popup" style="display:none;border:3px dotted gray;padding:.3em;background-color:white;position:absolute;width:80%;height:20%;margin:-50px 50px 0 50px;">
<legend>Introdu numarul de KO-uri:</legend>
<input type="text" name="kos" autofocus id="InputID" placeholder="KO-uri" style="width:100%;font-size:2em">
<button id='kosButton' type="submit" class="pure-button pure-button-primary" style="/*width:0;visibility:hidden;*/" onclick="hide_popup('my_popup'); return true;">Trimite</button>
</div>
<script type="text/javascript">
function FocusOnInput() { document.getElementById("InputID").focus(); }
document.onkeydown = function(event) {
if (event.keyCode == '13') {
barcodeButton = document.getElementById('barcodeButton');
kosButton = document.getElementById('kosButton');
if (document.getElementById('my_popup').style.display == 'none') {
barcodeButton.click();
show_popup('my_popup');
} else {
kosButton.click();
hide_popup('my_popup');
}
}
}
function show_popup(id) {
if (document.getElementById){
obj = document.getElementById(id);
if (obj.style.display == "none") {
obj.style.display = "";
}
}
}
function hide_popup(id){
if (document.getElementById){
obj = document.getElementById(id);
if (obj.style.display == ""){
obj.style.display = "none";
}
}
}
Let me know if this solves what you are trying to achive. Just out of curiosity, why aren't you using jQuery here?

display alert when form is submitted

I need to display the alert saying thanx your msg is received but this doesnot works so please hel me out how to do.Is there coding error or what i coudnt get to it.i would pe pleased if someone helps me out.thankyou
<h4>Send Your Feedback Here.<p>
<form name ="register" action="contact.php" method="post" enctype="multipart/form-data">
Name<br>
<input type="text" name="name" size="30">
</p>
<p>
Email<br>
<input type="text" name="email" size="30"></p><p>
Message<br>
<textarea name="message" rows="5" cols="40"></textarea>
<p>
</p>
<p>
Security Check<br>
Sum of <?php $a = rand(0,9);
$b = rand(0,9);
echo $a . "+" . $b ;
$result = $a + $b ;
?> =
<input type="text" name="ver" /><input type="hidden" name="rval" value="<?php echo $result; ?>" />
<button type="button" onClick="validate()">Send</button>
</p>
</form>
<script type="text/javascript">
function validate()
{
var x = document.register.ver.value;
var y = document.register.rval.value;
var nameCheck = document.register.name.value,
emailCheck = document.register.email.value,
msgCheck = document.register.message.value;
var msg ="";
if(x!=y)
{
msg+= "Sorry!! Captcha Mismached."+"\n";
}
if(nameCheck=="")
{
msg+= "Dont you have a name????"+"\n";
}
if(emailCheck=="")
{
msg+= "Enter email... how am I supposed to contact you"+"\n";
}
if(msgCheck="")
{
msg+= "Dont you have any messages for me??"+"\n";
}
if(msg!="")
{
alert(msg);
}
else
{
<?php
//Get message data.
$name = $_POST['name'];
$message = $_POST['message'];
$email=$_POST['email'];
$ver = $_POST['ver'];
$rval = $_POST['rval'];
if($ver==$rval)
{
//Email it.
mail(
'example#example.com', //Where to send
"Contact form - $name", //Email subject
$message, //Message body
$email //email address
);
echo "<script type=\"text/javascript\">alert('Thank you form is submitted');</script>";
}
else
{
echo "<script type=\"text/javascript\">alert('Wrong captcha');</script>";
}
?>
}
}
You can't mix JavaScript and PHP like that. The PHP will be parsed on the served before the page is served up to the user. Including it inside of your JavaScript else block will have no effect, since the code will be run when the page is generated anyway.
You should look into the use of AJAX.
<script type="text/javascript">
function thevalidate()
{
var x = document.register.ver.value;
var y = document.register.rval.value;
var nameCheck = document.register.name.value,
emailCheck = document.register.email.value,
msgCheck = document.register.message.value;
var msg ="";
if(x!=y) {
msg+= "Sorry!! Captcha Mismached."+"\n";
}
if(nameCheck=="") {
msg+= "Dont you have a name????"+"\n";
}
if(emailCheck=="") {
msg+= "Enter email... how am I supposed to contact you"+"\n";
}
if(msgCheck="") {
msg+= "Dont you have any messages for me??"+"\n";
}
if(msg!="") {
alert(msg);
} else {
<?php
//You need to process data here..
?>
}
}
</script>
<h4>Send Your Feedback Here.<p>
<form name ="register" action="php/process.php" method="post" enctype="multipart/form-data">
Name<br>
<input type="text" name="name" size="30">
</p>
<p>
Email<br>
<input type="text" name="email" size="30"></p><p>
Message<br>
<textarea name="message" rows="5" cols="40"></textarea>
<p>
</p>
<p>
Security Check<br>
Sum of <?php $a = rand(0,9);
$b = rand(0,9);
echo $a . "+" . $b ;
$result = $a + $b ;
?> =
<input type="text" name="ver" /><input type="hidden" name="rval" value="<?php echo $result; ?>" />
<button type="button" onClick="thevalidate()">Send</button>
</p>
</form>

Categories