ajax http request without form reload? - javascript

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.

Related

how to put search results inside a div using ajax

the idea is, I want to put my search results from mysql inside "result_div" without reloading the whole page using ajax. thank you.
<button class="btn btn-default" id = "search_jo" >
<?php
if(isset($_POST['search_jo'])){
?>
<div class="panel-body" id = "result_div">
<?php
$sql = "some sql statement here";
$retval = mysql_query( $sql, $db_conn);
while($row = mysql_fetch_array($retval, MYSQLI_ASSOC))
{
// php echo statement here fecthing data from sql
}
mysql_free_result($result);
?>
</div>
<?php
}
?>
try this w3school code
<html>
<head>
<script>
function showResult(str) {
if (str.length==0) {
document.getElementById("livesearch").innerHTML="";
document.getElementById("livesearch").style.border="0px";
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 (this.readyState==4 && this.status==200) {
document.getElementById("livesearch").innerHTML=this.responseText;
document.getElementById("livesearch").style.border="1px solid #A5ACB2";
}
}
xmlhttp.open("GET","livesearch.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>
<form>
<input type="text" size="30" onkeyup="showResult(this.value)">
<div id="livesearch"></div>
</form>
</body>
</html>

Validating form from ajax call with php

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

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.

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