How to trigger AJAX from a search button - javascript

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

Related

Google invisible reCaptcha is only working in Incognito mode

I have a Google reCAPTCHA setup on my contact form in my website.
and i'm trying to test it in both localhost and server as well but recaptcha is only working in incognito mode .
without capturing reCAPTCHA mails are sending .
Here my problem is grecaptcha.execute(); is not executing, Please suggest solution for this.
$("#cont_msg").keypress(function (e) {
var key = e.which;
if (key == 13) {
// the enter key code
$("#contact_form_submit").click();
return false;
}
});
$(
".app_form_wrapper .apps_input input, .app_form_wrapper .apps_input textarea"
).keypress(function () {
$(this).parent().removeClass("error");
});
function sendMail() {
var co_name = $("#cont_name").val();
var co_email = $("#cont_email").val();
var co_phone = $("#cont_phone").val();
var co_company = $("#cont_company").val();
var co_message = $("#cont_msg").val();
let data = {
username: co_name,
useremail: co_email,
userphone: co_phone,
usercompany: co_company,
usermessage: co_message,
};
$("#loading").show();
$("#contact_form_submit").hide();
$.ajax({
type: "POST",
url: "contact_ajaxmail.php",
data: data,
success: function (contact) {
//grecaptcha.execute();
$("#loading").hide();
$("#contact_form_submit").show();
var i = contact.split("#");
if (i[0] == "1") {
$("#cont_name").val("");
$("#cont_email").val("");
$("#cont_phone").val("");
$("#cont_company").val("");
$("#cont_msg").val("");
$("#contact_err").html(i[1]);
$(".app_form_wrapper .apps_input").addClass("success");
setTimeout(function () {
$(".app_form_wrapper .apps_input").removeClass("success");
$(".app_form_wrapper .apps_input").removeClass("error");
$("#cont_email").parent().removeClass("error");
}, 2500);
} else {
$("#cont_name").val(data.username);
$("#cont_email").val(data.useremail);
$("#cont_phone").val(data.userphone);
$("#cont_company").val(data.usercompany);
$("#cont_msg").val(data.usermessage);
$("#contact_err").html(i[1]);
$(
".app_form_wrapper .apps_input input, .app_form_wrapper .apps_input textarea"
).each(function () {
if (!$(this).val()) {
$(this).parent().addClass("error");
} else {
if (i[0] == 3) {
$("#cont_email").parent().addClass("error");
} else {
$(this).parent().addClass("error");
}
$(this).parent().removeClass("error");
}
});
}
},
});
}
**My form**
Here iam trying to send mails for entered email
<!DOCTYPE html>
<html lang="en">
<!-- BEGIN HEAD -->
<head>
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
</head>
<form class="app_form_wrapper" role="form" >
<div class="col-lg-6 text-left">
<div class="form-group apps-pulldown-20">
<div class="apps_input">
<input type="text" class="form-control" id="cont_name"placeholder="Name">
</div>
</div>
<div class="form-group apps-pulldown-20">
<div class="apps_input">
<input type="text" class="form-control" id="cont_email" placeholder="Email">
</div>
</div>
<div class="form-group apps-pulldown-20">
<div class="apps_input">
<input type="tel" class="form-control" id="cont_phone" placeholder="Phone Number" minlength="10" maxlength="15">
</div>
</div>
</div>
<div class="col-lg-6">
<div class="form-group apps-pulldown-20">
<div class="apps_input">
<input type="text" class="form-control" id="cont_company" placeholder="Company">
</div>
</div>
<div class="form-group apps-pulldown-20">
<div class="apps_input">
<textarea rows="10" class="form-control" id="cont_msg" placeholder="Message"></textarea>
</div>
</div>
</div>
<div class="col-lg-12">
<div class="g-recaptcha"
data-sitekey="Site_key"
data-callback="sendMail"
data-size="invisible">
</div>
<p>
This site is protected by reCAPTCHA and the Google
Privacy Policy and
Terms of Service apply.
</p>
<a class="btn btn-default btn-lg contact_btn" id="contact_form_submit">Send</a>
<a class="btn btn-default btn-lg contact_btn" id="loading" style="display: none;">Sending...</a>
<p class="input_error"id="contact_err" style="color:#FF6666;position:absolute;font-size:14px;font-weight: 500;letter-spacing: 0.5px;bottom: 10px;left: 0;right: 0;">
</p>
</div>
</form>
<script type="text/javascript">
$(document).ready(function () {
$("#contact_form_submit").on("click", function () {
var co_name = $("#cont_name").val();
var co_email = $("#cont_email").val();
var co_phone = $("#cont_phone").val();
var co_company = $("#cont_company").val();
var co_message = $("#cont_msg").val();
if (
co_name != "" &&
co_email != "" &&
co_phone != "" &&
co_company != "" &&
co_message != ""
) {
grecaptcha.execute();
} else {
$("#loading").hide();
$("#contact_form_submit").show();
$("#contact_err").html("Please fill all the fields !!!!");
}
});
})
</script>
</body>
</html>
Captcha needs two things to make it work properly
Client side code in Javascript, this you have done by looks of it properly.
Server side code, without implementing server side code the captcha is useless as bots will just post straight to your PHP form without having to enter a captcha! This is your missing piece based on your comments.
See
https://developers.google.com/recaptcha/intro
Notice it says you need to do 2 steps, 1 client side, 2 verify the response:
https://developers.google.com/recaptcha/docs/verify
Google returns loads results but this seems to be an up to date article
https://phppot.com/php/php-contact-form-with-google-recaptcha/
Google implementing google captcha php

Scroll bottom does not work on ajax

So I found this piece of code and implemented it into my chat script. What it is meant to do is scroll to the bottom of the chat div which contains the messages of the specific chat. The chat is generated by a chat_generate() function which uses the xmlhttp protocol. The problem is that this gives me some errors. The code is as follows:
Html:
<button onclick="chat_generate(1);"></button>
JS:
function chat_generate(chat_id) {
var id = chat_id.toString();
var check_user_in = "#chat_"+id;
if($(check_user_in).length == 0) {
var open ="";
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myObj = JSON.parse(this.responseText);
/*var text = "Welcome to chat: "+myObj[1];*/
open = [
"<div class='full_wrap' id='chat_"+chat_id+"'> <div class='force-overflow'></div> <div id='nav_"+chat_id+"' class='chat_side'> <h2>Chat Settings & Info</h2> <a id='closebtn' href='javascript:void(0)'",
"class='closebtn' onclick='chat_closeNav("+chat_id+")'>×</a> <div class='authr' style='background-image:url("+myObj[3]+");'> <a> <div class='authr_img' style='background-image:url(pimages/"+myObj[8]+");'></div>​ </a> <form action='mypage.php' method='post'> <div ",
"class='authr_name'><button value='"+myObj[6]+"' name='userlink' class='subm_as_text'> "+myObj[6]+"</button></div> </form> </div> <div class='chat_info'> <div ",
"class='chat_descy'> <h2>Chat Description</h2> <div class='descc'> <h3>"+myObj[2]+"</h3> </div> </div> <div class='chat_fol'><h2>Chat users: 2</h2></div> <div class='chat_back'> <h2> ",
"Change Chat Wallpaper</h2> <form method='post' action='picture.php' enctype='multipart/form-data'> <input type='file' id='upload' class='custom-file-input' name='chat_wall'> <input type='submit' ",
"class='chat_wall_subm' value='Change'/> </form> </div> </div> <form method='post' action='chat.php' > <button class='chat_leave' name='chat_leave' value='$chat_index' >Leave Chat</button> </form> </div> <div class='chat_mnav'> ",
"<span onclick='chat_openNav("+chat_id+")'>☰</span> <i class='material-icons' id='chat_un_small' onclick='chat_un_small("+chat_id+")'>arrow_upward</i> <h1>"+myObj[1]+"</h1> <div class='chat_close' onclick='chat_close("+chat_id+")'><i ",
"class='material-icons' ></i></div> </div> <div class='conceal_wrapper'> <div class='msgs' style='background-image:url("+myObj[4]+")' id='"+chat_id+"'> </div> <form method='post' id='form_"+chat_id+"' class='comform'> <div class='chat_wcom' > <input maxlength='140' type = 'text' id='input_"+chat_id+"' class='comin' placeholder='My message...' name='sendmsg' onkeypress='g(event,"+chat_id+")' ",
"autocapitalize='off' autocorrect='off' /> <input class='hidden_index' type='text' value='"+chat_id+"' name='chat_index'/> </div> </form> </div> <div class='chat_enlarge'> <div class='chat_enlarge_full' onmouseover='chat_action(this)' onmouseout='chat_action_negative(this)' ",
"onclick='chat_enlarge_full("+chat_id+")'></div> <div class='chat_enlarge_standard' onmouseover='chat_action(this)' onmouseout='chat_action_negative(this)' onclick='chat_enlarge_standard("+chat_id+")'></div> <div ",
"class='chat_enlarge_small' onmouseover='chat_action(this)' onmouseout='chat_action_negative(this)' onclick='chat_enlarge_small("+chat_id+")'></div><div class='chat_enlarge_close' onmouseover='chat_action(this)' onmouseout='chat_action_negative(this)' onclick='chat_close("+chat_id+")'></div> </div></div>"
].join("\n");
var cusid_ele = document.getElementsByClassName('open_chat');
if(cusid_ele.length == 0){
alert("No more chat space");
}else{
if($(cusid_ele[0]).replaceWith(open)){
draggables();
startf();
}
}
}
chat_enlarge_standard(chat_id);
scrollOpen(chat_id);
};
xmlhttp.open("GET", "receivechatinfo.php?id="+id, true);
xmlhttp.send();
}else{
alert("The chat is already open");
}
}
function scrollOpen(id) {
var elem = document.getElementById(id);
elem.scrollTop = elem.scrollHeight;
}
I believe that the problem is that the chat html is inserted in place of the open_chat div before the function is called resulting in an error of cannot make something to value of null. But I do not know how to solve this problem in the following case.
Any help would be appreciated.

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

xhttp.send() get error POST 500 (Internal Server Error)

when trying to send the data to the server the error POST 500(internal server Error ) display
here is my form
<form class="input-group" id="f">
<div class="form" style="display :-webkit-inline-box;">
<input type="text" class="form-control" name="comment" placeholder=" Comment ">
<span class="input-group-btn">
{{--<input class="btn btn-default" type="button" onclick="loadDoc()" value="Comment!">!--}}
<input class="btn btn-default" type="button" onclick="loadDoc()" value="Comment!">
</span>
</div>
<input type="hidden" name="_token" value="{{ csrf_token() }}">
</form><!-- /input-group -->
and this is the javascript code
function loadDoc() {
var dd = document.getElementById('f');
var d = [];
r=0;
for (var i = 0; i < dd.elements.length; i++){
if(dd[i].type == "text") {
d[r] = dd[i].value;
r++;
}
}
var xhttp = new XMLHttpRequest();
var url = "/place/{{$place->id}}";
var params = "data="+d;
xhttp.open("POST", url , true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var json = JSON.parse(this.response);
console.log(json);
}
};
xhttp.send(params);
}
i am trying to make a comment
If you don't plan to use CSRF Token, than go to the
App/Http/Kernel.php
And delete or comment line
\App\Http\Middleware\VerifyCsrfToken::class
And your profilem is solved... otherwise add _token param in that xhttp request...

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.

Categories

Resources