Validating form from ajax call with php - javascript

I have a farm that loads when an option is seleceted with ajax call, however i want to validate my form, immediately when i submit, it and there is error upon validation, the ajax called form dissapears.
This is my ajax
<script>
function salesType(str) {
if (str == "") {
document.getElementById("txtHint2").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint2").innerHTML = this.responseText;
}
};
xmlhttp.open("GET","showsalestype.php?&q="+str,true);
xmlhttp.send();
e.preventDefault();
}
}
</script>
my php
$q = $_GET['q'];
if($q == 'POS'){ ?>
<div class="form-group">
<label class="control-label col-md-3 col-sm-3 col-xs-12">POS Referece No <span class="required">*</span>
</label>
<div class="col-md-6 col-sm-6 col-xs-12">
<input id="atmref" name="atmref" class="form-control col-md-7 col-xs-12" type="text" value=" ">
</div>
<p><font size="2" color="#ff0000"> <?php echo $form->error("atmref"); ?> </font></p>
</div>
<?php } ?>
How do i prevent the ajax call to remain upon validation error

Related

Send image data from an html tag using AJAX to PHP and save it in MySQL as blob data

I want to send the image data from the html img tag using AJAX and save it in my MySQL db. I have a column in my db which is a longblob datatype, thats where I'm going to store the image. I also have other data that I'm going to save along with it but my main concern is the image, I don't know how to do it. I did try to find answers here on and other sites but didn't find what I was looking for. My code looks like this.
HTML:
<div class="col-lg-12">
<div class="form-group col-lg-4">
<label>ARP No.</label>
<label>
<input type="text" name="arp-no" class="form-control" id='arp-no' required=""/>
</label>
</div>
<div class="form-group col-lg-4">
<label>Owner</label>
<label>
<input type="text" name="owner" id="owner" class="form-control" value="" required=""/>
</label>
</div>
</div>
this is where the image tag is
<div class="col-lg-6">
<div class="form-group col-lg-12">
<img name="map-sketch" id="image" width="100%" height="100%" src='http://www.thekrausemouse.com/wp-content/uploads/2016/03/Sample.jpg'></img>
</div>
</div>
<div class="row">
<div class="col-lg-1">
<button type="button" class="btn btn-primary" onclick="saveFaas()">Save</button>
</div>
<div class="col-lg-2" id="saving-info"></div>
</div>
Javascript AJAX:
function saveFaas(){
if (confirm('Are you sure you want to save this information?')) {
var params = 'kind=land';
params += '&arp-no='+document.getElementById('arp-no').value;
params += '&owner='+document.getElementById('owner').value;
//the image data
params += '&image=';
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("saving-info").innerHTML = xmlhttp.responseText;
}else { // waiting for result
document.getElementById('saving-info').innerHTML = '<img src="../images/ajax_loader.gif">';
}
}
xmlhttp.open("POST", "../functions/save-faas.php", true);
xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xmlhttp.send(params);
}}
Can I pass the image data like the others?
Php:
<?php
//db info
include('../fragments/db-config.php');
// Create connection
$conn = new mysqli($servername, $dbusername, $dbpassword, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$kind = $_POST['kind'];
if ($kind == 'land') {
$image = $_POST['image']; // the image
$arp_no = $_POST['arp-no'];
$owner = $_POST['owner'];
$sql = "UPDATE faas SET arp_number='$arp_no', owner_name='$owner'
WHERE faas_id=$faas_id;";
}
if ($conn->query($sql) === TRUE) {
echo "<label>Record Updated</label>";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close(); ?>
So to wrap it up. I have an image data in my html, call ajax to send the image and the other data in php and save it in mysql db.
My javascript code here is in plain javascript so I would like a plain javascript solution also. Thank you.

Synchronous XMLHttpRequest on the main thread is deprecated AJAX

I am having this error in my console that is preventing my validation in two different forms in AJAX Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user’s experience.. My forms are working fine but this console log is bothering me.
I'll only add in code in the scripts to avoid confusion.
These are the two forms (onblur invokes the ajax validation)
edit.blade.php
<div class="main-content">
<!-- You only need this form and the form-basic.css -->
<form class="form-basic" method="post" id="myEditForm" action="/edit">
<div class="form-title-row">
<h1>Edit User</h1>
</div>
<input type="hidden" name="userid" id="editFormUserId">
<div class="form-row">
<label>
<span>Firstname</span>
<input type="text" name="firstname" id="editFormFirstName" onblur="validateEditForm('divfirstnameEditForm', this.value)">
</label>
</div>
<div id="divfirstnameEditForm"></div>
<div class="form-row">
<label>
<span>Lastname</span>
<input type="text" name="lastname" id="editFormLastName" onblur="validateEditForm('divlastnameEditForm', this.value)">
</label>
</div>
<div id="divlastnameEditForm"></div>
<div class="form-row">
<label>
<span>Password</span>
<input type="password" name="password" id="editFormPassword" onblur="validateEditForm('divpasswordEditForm', this.value)">
</label>
</div>
<div id="divpasswordEditForm"></div>
<div class="form-row">
<input class="button" type="button" onclick="fetchUser()" value="Submit" />
<input type="hidden" name="_token" value="{{ csrf_token() }}">
</div>
</form>
</div>
create.blade.php
<div class="main-content">
<!-- You only need this form and the form-basic.css -->
<form class="form-basic" method="post" id="myForm" action="/create">
<div class="form-title-row">
<h1>Create User</h1>
</div>
<div class="form-row">
<label>
<span>Firstname</span>
<input type="text" name="firstname" id="firstname1" onblur="validate('firstname', this.value)">
</label>
</div>
<div id="firstname"></div>
<div class="form-row">
<label>
<span>Lastname</span>
<input type="text" name="lastname" id="lastname1" onblur="validate('lastname', this.value)">
</label>
</div>
<div id="lastname"></div>
<div class="form-row">
<label>
<span>Password</span>
<input type="password" name="password" id="password1" onblur="validate('password', this.value)">
</label>
</div>
<div id="password"></div>
<div class="form-row">
<input class="button" onclick="checkForm()" type="button" value="Submit" />
<input type="hidden" name="_token" value="{{ csrf_token() }}">
</div>
</form>
</div>
scripts.js (contains fetchuser, checkform, validation methods for each form)
//start of checkuser
function fetchUser() {
console.log('fetchuser');
//fetch values from edit blade
var firstname = document.getElementById("editFormFirstName").value;
var lastname = document.getElementById("editFormLastName").value;
var password = document.getElementById("editFormPassword").value;
//Check input Fields Should not be blanks.
if (firstname == '' || lastname == '' || password == '') {
alert("Fill All Fields");
} else {
//Notifying error fields
var firstname = document.getElementById("divfirstnameEditForm");
var lastname = document.getElementById("divlastnameEditForm");
var password = document.getElementById("divpasswordEditForm");
//Check All Values/Informations Filled by User are Valid Or Not.If All Fields Are invalid Then Generate alert.
if (firstname.innerHTML == 'Firstname must be 2+ letters' || lastname.innerHTML == 'Lastname name must be 2+ letters' || password.innerHTML == 'Must be a combination of special character, number and letters') {
alert("Fill Valid Information");
} else {
//Submit Form When All values are valid.
document.getElementById("myEditForm").submit();
}
}
}
//end of checkuser
//checkform validation
function checkForm() {
console.log('checkform');
// Fetching values from all input fields and storing them in variables.
var firstname = document.getElementById("firstname1").value;
var lastname = document.getElementById("lastname1").value;
var password = document.getElementById("password1").value;
//Check input Fields Should not be blanks.
if (firstname == '' || lastname == '' || password == '') {
alert("Fill All Fields");
} else {
//Notifying error fields
var firstname = document.getElementById("firstname");
var lastname = document.getElementById("lastname");
var password = document.getElementById("password");
//Check All Values/Informations Filled by User are Valid Or Not.If All Fields Are invalid Then Generate alert.
if (firstname.innerHTML == 'Firstname must be 2+ letters' || lastname.innerHTML == 'Lastname name must be 2+ letters' || password.innerHTML == 'Must be a combination of special character, number and letters') {
alert("Fill Valid Information");
} else {
//Submit Form When All values are valid.
document.getElementById("myForm").submit();
}
}
}
// AJAX code to check input field values when onblur event triggerd.
function validate(field, query) {
var xmlhttp;
if (window.XMLHttpRequest) { // for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else { // for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState != 4 && xmlhttp.status == 200) {
document.getElementById(field).innerHTML = "Validating..";
} else if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById(field).innerHTML = xmlhttp.responseText;
} else {
document.getElementById(field).innerHTML = "Error Occurred. <a href='index.php'>Reload Or Try Again</a> the page.";
}
}
xmlhttp.open("GET", "/php/validation.php?field=" + field + "&query=" + query, false);
xmlhttp.send();
}
// AJAX code to check input field values when onblur event triggerd.
function validateEditForm(field, query) {
var xmlhttp;
if (window.XMLHttpRequest) { // for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else { // for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState != 4 && xmlhttp.status == 200) {
document.getElementById(field).innerHTML = "Validating..";
} else if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById(field).innerHTML = xmlhttp.responseText;
} else {
document.getElementById(field).innerHTML = "Error Occurred. <a href='index.php'>Reload Or Try Again</a> the page.";
}
}
xmlhttp.open("GET", "/php/validationEditForm.php?field=" + field + "&query=" + query, false);
xmlhttp.send();
}
Can you help me why it is showing up in my log?
You can either remove the last boolean value:
xmlhttp.open("Method", "URL");
or just use the true:
xmlhttp.open("Method", "URL", true);
From the docs at MDN:
An optional Boolean parameter, defaulting to true, indicating whether or not to perform the operation asynchronously. If this value is false, the send() method does not return until the response is received. If true, notification of a completed transaction is provided using event listeners. This must be true if the multipart attribute is true, or an exception will be thrown.

ajax http request without form reload?

I am having problem with form onsubmit().
I do not want to reload page and only want to pass 2 parameter to another php.
<script type="text/javascript">
function doSomething() {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("addCategory").innerHTML = this.responseText;
}
};
xmlhttp.open("GET","/api/add_item_main_category.php?q1="+document.getElementById("myText1").value+"&q2="+document.getElementById("myText2").value,false); ///* Tested with true */
xmlhttp.send();
return false;
}
</script>
Here is my Form.
<form href="JavaScript:void(0);" onsubmit="return doSomething(); ">
<input type="text" id="myText1" name="maincategory" placeholder="Main Category" style="width: 100%;">
<input type="text" id="myText2" name="subcategory" placeholder="Sub Category" style="width: 100%;">
<br/>
<input type="submit" name="submit" value="Add Main Category">
<br/>
<div id="addCategory" ></div>
</form>
Submit button works on like this url "/api/add_item_main_category.php?q1=Car&q2=Toyota". Not working with user input just like above form and it redirected.

How to send the name and value off the textbox to ajax which is used in php for validation

So i am trying to send the name and value of the textbox to ajax and want to use that name of the text box in php to validate the field. I was trying to use this.name but apparently its not the correct way!.
This is my ajax code.
<script type="text/JavaScript">
function frmValidation(str)
{
if (str=="")
{
document.getElementById("txtError").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("txtError").innerHTML=xmlhttp.responseText;
}
xmlhttp.open("GET","validation.php?value="+str,true);
xmlhttp.send();
}
}
And thats my html
<div class="col-sm-6">
<div class="form-group">
<label for="First Name">First Name</label>
<input type="text" class="form-control" onblur="frmValidation(this.value)" tabindex="1" id="First Name" placeholder="First Name" name="fname"><span id="txtError" style="color: red"></span>
</div>
Thanks in advance!
Change to pass in this so you can access this.name and this.value inside the function
<input onblur="frmValidation(this)" ....>
JS
function frmValidation(elem){
var str = elem.value, name =elem.name;
//.....
xmlhttp.open("GET","validation.php?value="+str + '&name='+name,true);
//....
}
Since question is tagged jQuery can replace onblur with:
$('input').blur(function(){
$.get('validation.php', {name: this.name, value:this.value))
.done(function(resp){
$('#txtError').html(resp);
});
});

How to trigger AJAX from a search button

I have the following Javascript:
<script>
function showtickets(str) {
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
}
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "/processes/editticket.php?WTNum=" + str, true);
xmlhttp.send();
}
It works perfectly if I use a selectbox and trigger the function with "onchange". However, my client requested a searchbox instead. I cannot get it to work with a search box. Here is my HTML for the search box and the div where the results should go.
<form class='form-horizontal col-xs-12 col-md-12 col-lg-12' name="editticket" method="post" action="/processes/updateticket.php">
<div class='panel panel-primary'>
<div class='panel-heading'>
<h3 class='panel-title'>Edit Work Tickets</h3>
</div>
<div class='panel-body'>
<div class="input-group">
<span class="input-group-addon">Enter Ticket #</span>
<input type="text" class="form-control" id="search" name="WTNum" >
<span class="input-group-btn">
<button class="btn btn-default" type="button" onclick="showtickets(document.getElementById('search').value)">Search</button>
</span>
<div id="txtHint"><b></b></div>
</form>
Am I missing something!! This is driving me INSANE!!
Thank you all in advance. It is greatly appreciated.
Why not just call the showtickets function without arguments and then inside the function you do this
str = document.getElementById('search').value;
I think you must you javascript debug or alert in some scope to find where error

Categories

Resources