How to post data using Ajax jQuery? - javascript

I want to send data from my website to a server for login form. I have a PHP script for that and it works fine as I already made an Android application using the same script. I am new to web development so I got stuck here.
I am getting an error of invalid keys but I mention proper key values in the name attribute. And after success I want to capture those values and as it contains some user information and I want to display it later.
HTML code
<form id="loginform">
<label for="phonenumber">Mobile Number</label>
<br/>
<!--<input type="tel" name="telNo" type="tel" size="20" maxlength="13">-->
<input type="text" id="userid" name="userid" size="20" maxlength="13" class="numeric" /><br>
<span class="error" style="color: red; display: none">Input digits (0 - 9)</span>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
var specialKeys = new Array();
specialKeys.push(8); //Backspace
$(function() {
$(".numeric").bind("keypress", function(e) {
var keyCode = e.which ? e.which : e.keyCode
var ret = ((keyCode >= 48 && keyCode <= 57) || specialKeys.indexOf(keyCode) != -1);
$(".error").css("display", ret ? "none" : "inline");
return ret;
});
$(".numeric").bind("paste", function(e) {
return false;
});
$(".numeric").bind("drop", function(e) {
return false;
});
});
</script>
<br/>
<label for="Name">Password</label>
<br/>
<input type="password" id="upassword" name="upassword">
<br/>
<input type="submit" value="Login">
<script type="text/javascript">
var frm = $('#loginform');
frm.submit(function(e) {
e.preventDefault();
$.ajax({
type: post,
url: "https://smilestechno.000webhostapp.com/ChkRMNRegistered.php",
data: frm.serialize(),
success: function(data) {
console.log('Submission was successful.');
console.log(data);
},
error: function(data) {
console.log('An error occurred.');
console.log(data);
},
});
});
</script>
</form>
Error
Notice: Undefined index: userid in /storage/ssd1/323/4193323/public_html/ChkRMNRegistered.php on line 6
Notice: Undefined index: upassword in /storage/ssd1/323/4193323/public_html/ChkRMNRegistered.php on line 7
{"result":[{"ResultStatus":"FAIL"},{"PPLink":"http://smilestechno.000webhostapp.com/ImagesUpload/abc.jpg"}]}

Related

Input type email still allows to go through

I have a textbox of input type email because it's meant for email addresses. So my page looks like this:
The input type of email should handle the syntax of email.So if email is test###gmail.com,it should not gone through though. When I hit send, it still able to initiate the email.
My javascript function:
<script>
//function to send email
function sendmessage(){
var recipient = document.getElementById("recipient").value;
var subject = document.getElementById("subject").value;
var content=document.getElementById("content").value;
$.ajax({
url: 'sendemail.jsp',
type: 'POST',
data: {
recipient:recipient,
subject:subject,
content:content
},
success: function (data) {
alert("Successfully initiated email to queue");
},
error: function (request, error) {
alert("Request: " + JSON.stringify(error));
}
});
}
</script>
<body>
<div class="email_font">
   To:<input type="email" style="font-size: 10pt;" size="70" id="recipient"><br><br>
Subject:<input type="text" style="font-size: 10pt" size="70" id="subject" ><br><br>
Content:<br><textarea cols="80" rows="10" id="content" style="font-size: 13pt;">
<%=files%>: <%=url%>
</div>
<div class="Send">
<button type="button" style="font: 13px/1.231 Trebuchet MS;" onclick="sendmessage()"> Send </button>
</div>
Clicking send still allows to send, is there anything I made wrong?
You can Split the emails on a comma and validate the entries one by one
Following is the code to accept multiple valid email id both comma and semicolon as separator
function validateEmails(emailString) {
var regex = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
var result = emailString.replace(/\s/g, "").split(/,|;/);
for(var i = 0;i < result.length;i++) {
if(!regex.test(result[i])) {
return false;
}
}
return true;
}
Use the following code and it should help:
HTML:
<div class="input-wrp">
<input type="email" name="email" placeholder="E-MAIL ID*" required>
<p class="error">Email Error</p>
</div>
JS:
$('input[type="email"]').on('input', function() {
email($(this)); //Function Call
});
function email(input) { //Function
var inputVal = input.val();
var reg = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if(!reg.test(inputVal) && inputVal.length > 0) {
input.parent().find('.error').show();
} else {
input.parent().find('.error').hide();
}
}

Uncaught ReferenceError: submitToAPI is not defined at HTMLButtonElement.onclick

I am creating a form filling website it should return alert message if contact,email is not up to our standard.
But I am getting this error Uncaught ReferenceError: submitToAPI is not defined at HTMLButtonElement.onclick
var URL is I am passing these data to AWS API gateway and trigger a lambda function.
form html code
<h4>Name:</h4>
<input type="text" style="height:35px;" id="name-input" placeholder="Enter name here…" class="form-control" style="width:100%;" /><br/>
<h4>Company Name:</h4>
<input type="text" style="height:35px;" id="cname-input" placeholder="Enter name here…" class="form-control" style="width:100%;" /><br/>
<h4>Contact Number:</h4>
<input type="phone" style="height:35px;" id="phone-input" placeholder="Enter phone number" class="form-control" style="width:100%;"/><br/>
<h4>Email:</h4>
<input type="email" style="height:35px;" id="email-input" placeholder="Enter email here…" class="form-control" style="width:100%;"/><br/>4>
<div class="g-recaptcha" data-sitekey="6Lc7cVMUAAAAAM1yxf64wrmO8gvi8A1oQ_ead1ys" class="form-control" style="width:100%;"></div>
<button type="button" onClick="submitToAPI(event)" class="btn btn-lg" style="margin-top:20px;">Submit</button>
javascript
<script language="JavaScript" type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js" >
function submitToAPI(e) {
e.preventDefault(e);
var URL = "https://abc1234.execute-api.us-east-1.amazonaws.com/01/contact";
var e_name = /[A-Za-z]{1}[A-Za-z]/;
if (!e_name.test($("#name-input").val())) {
alert ("Name can not less than 2 char");
return;
}
var e_cname = /[A-Za-z]{1}[A-Za-z]/;
if (!e_cname.test($("#cname-input").val())) {
alert ("Name can not less than 2 char");
return;
}
var e_phone = /[0-9]{10}/;
if (!e_phone.test($("#phone-input").val())) {
alert ("Please enter valid mobile number");
return;
}
if ($("#email-input").val()=="") {
alert ("Please enter your email id");
return;
}
var e_email = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,6})?$/;
if (!e_email.test($("#email-input").val())) {
alert ("Please enter valid email address");
return;
}
var e_name = $("#name-input").val();
var e_cname = $("#cname-input").val();
var e_phone = $("#phone-input").val();
var e_email = $("#email-input").val();
var data = {
name : e_name,
cname : e_cname,
phone : e_phone,
email : e_email,
};
$.ajax({
type: "POST",
url : "https://abc1234.execute-api.us-east-1.amazonaws.com/01/contact",
dataType: "json",
crossDomain: "true",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(data),
success: function () {
// clear form and show a success message
alert("Successfull");
document.getElementById("contact-form").reset();
location.reload();
},
error: function () {
// show an error message
alert("There is some issue with our servers please contact our landline for enquiry");
}});
}
</script>
You are using the script tag with a src attribute, your browser is only executing the remote JS (Jquery)
Create a new script tag without the src and add your code in this new block!
Correct way is to first load jQuery as your script is dependent on it.
<script language="JavaScript" type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js" >
</script>
After that you can include your script
<script>
$(document).ready(function () {
function submitToAPI(e) {
// your code
}
});
</script>
Make sure jQuery is properly loaded into your page. Check network tab in dev console, make sure there is no "404".
$(document).ready(function () {
// This code is being loaded after jQuery has been initialized
});

Error using ajax to check email from database

I've read the answers from several users here, and my intention is to check if the email is already on the DB.
So my code is the following
**HTML CODE**
<div class="form-group">
<div class="col-sm-12">
<div class="input-group">
<span class="input-group-addon"><span class="glyphicon glyphicon-user"></span></span>
<input id="fnam" name="firstname" class="profile-input form-control" type="text" placeholder="First Name" autocomplete="off" maxlength="25" required />
<!-- <input id="fullname" name="fullname" class="form-control" placeholder="Full Name" required="" type="text">-->
</div>
</div>
</div>
</fieldset>
<fieldset>
<!-- Prepended text Last Name-->
<div class="form-group">
<div class="col-sm-12">
<div class="input-group">
<span class="input-group-addon"><span class="glyphicon glyphicon-user"></span></span>
<input id="lastname" name="lastname" class="profile-input form-control" type="text" placeholder="Last Name" autocomplete="off" maxlength="25" required />
<!-- <input id="fullname" name="fullname" class="form-control" placeholder="Full Name" required="" type="text">-->
</div>
</div>
</div>
</fieldset>
<fieldset>
<!-- Prepended text Email-->
<div class="form-group">
<div class="col-sm-12">
<div class="input-group">
<span class="input-group-addon"><span class="glyphicon glyphicon-envelope"></span></span>
<input id="email" name="email" class="profile-input form-control" type="email" placeholder="Email" autocomplete="off" maxlength="50" required/>
<!-- <input id="email" name="email" class="form-control" placeholder="Email" required="" type="text">-->
</div>
</div>
</div>
JS/ AJAX
function chemail(inputText) {
var email1 = $("#email").val();
var x = document.forms["myappForm"]["email"].value;
var datastring = '$email='+ x; // get data in the form manual
//var mailformat = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
var atpos = x.indexOf("#");
var dotpos = x.lastIndexOf(".");
// if(inputText.value.match(mailformat)){
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length) {
var msgp="Invalid Email. Ex: abc#ggggg.com";
document.getElementById("msgreturn").style.color= "red";
document.getElementById("msgreturn").innerHTML = msgp;
document.getElementById("lem").style.color= "red";
document.myappForm.email.focus();
return false;
}
else
{
document.myappForm.email.focus();
var msgp="Email verified";
document.getElementById("msgreturn").style.color= "green";
document.getElementById("msgreturn").innerHTML = msgp;
document.getElementById("lem").style.color= "green";
return true;
$("span.loading").html("<img src='images/ajax_fb_loader.gif'>");
$("span.validation").html("");
var datastring = '&email='+ x;
$.ajax({
type: "POST", // type
url: "check_email.php", // request file the 'check_email.php'
data: datastring, // post the data
success: function(responseText) { // get the response
if(responseText == 1) { // if the response is 1
$("span.email_val").html("<img src='images/invalid.png'> Email are already exist.");
$("span.loading").html("");
} else { // else blank response
if(responseText == "") {
$("span.loading").html("<img src='images/correct.png'> You are registred.");
$("span.validation").html("");
$("form input[type='text']").val(''); // optional: empty the field after registration
}
}
}
}
}
and the check_email.php
<?php require_once("../../php_includes/dbconnect.php");
$email = $_POST['x'];
$query = mysql_query("SELECT 'email' FROM 'members' WHERE 'email' = '$email'");
if(mysql_num_rows($query) == 1) { echo '1'; } else { echo '1'; }
?>
So the sources are all working, I've set some alerts inside of ajax but it didn't worked, can you please tell me where am I making the mistake , I'm following the example from other users from this site, however can't reach a solution.
Assuming that you have directly copied your code, the error can be found by checking indentation. I would suggest, BTW, that you make your editor replace tabs with spaces, as tabs may not show the spacing correctly on any other system (such as SO!).
function chemail(inputText) {
var email1 = $("#email").val();
var x = document.forms["myappForm"]["email"].value;
var datastring = '$email='+ x; // get data in the form manual
//var mailformat = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
var atpos = x.indexOf("#");
var dotpos = x.lastIndexOf(".");
// if(inputText.value.match(mailformat)){
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length) {
var msgp="Invalid Email. Ex: abc#ggggg.com";
document.getElementById("msgreturn").style.color= "red";
document.getElementById("msgreturn").innerHTML = msgp;
document.getElementById("lem").style.color= "red";
document.myappForm.email.focus();
return false;
}
else
{
document.myappForm.email.focus();
var msgp="Email verified";
document.getElementById("msgreturn").style.color= "green";
document.getElementById("msgreturn").innerHTML = msgp;
document.getElementById("lem").style.color= "green";
return true;
// HERE'S THE PROBLEM!!! The following code never gets executed. Missing parenthesis.
$("span.loading").html("<img src='images/ajax_fb_loader.gif'>");
$("span.validation").html("");
var datastring = '&email='+ x;
$.ajax({
type: "POST", // type
url: "check_email.php", // request file the 'check_email.php'
data: datastring, // post the data
success: function(responseText) { // get the response
if(responseText == 1) { // if the response is 1
$("span.email_val").html("<img src='images/invalid.png'> Email are already exist.");
$("span.loading").html("");
} else { // else blank response
if(responseText == "") {
$("span.loading").html("<img src='images/correct.png'> You are registred.");
$("span.validation").html("");
$("form input[type='text']").val(''); // optional: empty the field after registration
}
}
}
}
} // <--- this parenthesis is in the wrong place.
Another thing that should tip you off to the problem is to use the Network tab in the web console. You can use this to see the traffic between the browser and the server; in this case, you would find that there was no request made to the PHP script.
Addendum:
I believe datastring should be an object, not an url encoding. In other words,
var datastring = {email: x};
where x = $('#email').val();
For what it's worth, since you're using JQuery for your ajax, it would be more concise to change things like
document.getElementById("msgreturn").style.color= "red"; to $('#msgreturn').css('color','red');

check username availability with jQuery

I am using this function to check username availability when registering, and if the username exist, the submit button is disabled. I'm using a php script to check if the username exists in the database. The code works perfectly in my local server, but when hosted on a Godaddy server, I get the below error when I submit or when I try to navigate to another page:
After the empty response, I can't access my website for about a minute and then it's fine.
I tried a lot of things like calling jquery.js file before all other js files, but nothing works for me.
I am not very good with jQuery and javascript. Thank you for your suggestions.
ere is the script and the HTML form :
function check_availability_username() {
var min_chars = 4;
var max_chars = 30;
var re = /^\w+$/;
var characters_error1 = 'Minimum amount of chars is 4';
var characters_error2 = 'Maximum amount of chars is 30';
var characters_error3 = 'Chars can be only letters, numbers and underscores!';
var checking_html = 'Checking...';
var username = $('#username').val();
$.post("check_username.php", {
username: username
},
function(result) {
if (result == 1) {
if ($('#username').val().length < min_chars) {
$('#username_availability_result').html(characters_error1);
$('input[name=submit]').attr('disabled', true);
} else if ($('#username').val().length > max_chars) {
$('#username_availability_result').html(characters_error2);
$('input[name=submit]').attr('disabled', true);
} else if (!re.test($('#username').val())) {
$('#username_availability_result').html(characters_error3);
$('input[name=submit]').attr('disabled', true);
} else {
$('#username_availability_result').html(username + ' is Available');
$('input[name=submit]').attr('disabled', false);
}
} else {
$('#username_availability_result').html(username + ' is not Available');
$('input[name=submit]').attr('disabled', true);
}
});
if (event.which == 13 || event.keyCode == 13) {
$.post("check_username.php", {
username: username
},
function(result) {
if (result == 0) {
$('#username_availability_result').html(username + ' is not Available');
$('input[name=submit]').attr('disabled', true);
}
});
}
$('#submit').click(function() {
$.post("check_username.php", {
username: username
},
function(result) {
if (result == 0) {
$('#username_availability_result').html(username + ' is not Available');
$('input[name=submit]').attr('disabled', true);
}
});
});
}
<form id="login-id" action="suscribe-form.php" method="POST" onkeyup="return check_availability_username();">
<div class="form-group">
<label for="username">Username</label>
<input type="text" class="form-control button-or-space" name="username" id="username" value="" minlength="4" maxlength="25" required pattern="\w+">
<input type='hidden' id='check_username_availability' value='Check Availability'> <span id='username_availability_result' name='username_availability_result'></span>
</div>
<div class="form-group">
<label for="password1">Password</label>
<input type="password" class="form-control button-or-space" name="password1" id="password1" value="" minlength="8" maxlength="60" required pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}" onchange="form.password2.pattern = this.value;">
</div>
<div class="form-group">
<label for="password2">Confirm password</label>
<input type="password" class="form-control button-or-space" name="password2" value="" minlength="8" maxlength="60" required pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}">
</div>
<div class="form-group pull-right">
<input type="submit" name="submit" id="submit" value="Register" class="btn btn-success button-or-space">
</div>
</form>
And here is the php script :
<?php
mysql_connect('localhost', 'root', '');
mysql_select_db('DB');
$username = mysql_real_escape_string($_POST['username']);
$result = mysql_query('select username from user where username = "'.$username.
'"');
if (mysql_num_rows($result) > 0) {
echo 0;
} else {
echo 1;
}
?>
I finally found the solution. The problem was not from the jQuery or the php script, i only changed the way i call the function in the form from : onkeyup to onchange, and it is now working like a charm. I hope this tip avoid to others losing hours of time like it did to me. Thank's guys for your suggestions.
If you are getting 500 error that there is problem with the database connection.
check for the included files and connection variables used for database connection.
Hope that will work.

Why isn't my form working correctly when trying to post something using Ajax and an external PHP file, which is receiving two strings?

So basically I'm trying to use Ajax to work with a PHP file and post both inputs (fullname and phonenumber), but it doesn't seem to be working when I try and click the submit button it only refreshes.
Here's my code, it's all on the HTML file:
HTML:
<!DOCTYPE html>
<html lang="en-us">
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="style2.css" type="text/css">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
function validateForm () {
var x=document.forms["myForm"] ["fullname"].value;
if (x==null || x=="")
{
alert ("First name must be filled out");
return false;
}
var x=document.forms["myForm"] ["phonenumber"].value;
if (x=null || x=="")
{
alert ("Please enter a phone number");
return false;
}
function isNumberKey(evt) {
var e = evt || window.event; //window.event is safer,
var charCode = e.which || e.keyCode;
if (charCode > 31 && (charCode < 47 || charCode > 57))
return false;
if (e.shiftKey) return false;
return true;
}
</script>
<script>
$.ajax({
type: "POST",
url: "http://www.bmoseley.com/ajax/addrecord.php",
data: "fullname=" + fullname + "&phonenumber=" + phonenumber,
success: function(){
alert("Name and phone number added successfully!");
}
});
$("#displayInfo").load("http://www.bmoseley.com/ajax/listrecords.php");
}
</script>
</head>
<body>
<div id="wrap">
<div id="wrapper">
<div id="info">
<form name="myForm" action="#" onSubmit="return validateForm ()">
<table border="0">
<tr>
<td><input id="fullname" name="fullname" maxlength="50" type="text" name="fullname" placeholder="Name" action="#"></td>
</tr>
<tr>
<td><input id="phonenumber" name="phonenumber" maxlength="10" onkeypress="return isNumberKey(event)" placeholder="Phone Number"></td>
</tr>
<tr>
<td><input class="button" type="submit" value="Submit"></td>
</tr>
</table>
</form>
</div>
<div id="displayInfo">
<script>
$(document).ready(function(){
$("#displayInfo").load("http://www.bmoseley.com/ajax/listrecords.php");
});
</script>
</div>
</div>
</div>
</div>
</body>
</html>
Sorry for the messy code. Hope someone can help!
You need to sent the ajax request on the form submit, your code does it while page is loading.
Remove the inline submit handler onSubmit="return validateForm ()" and try
jQuery(function () {
//register a form submit event handler
$('form').submit(function (e) {
//stop the default form submission
e.preventDefault();
//validations, use jQuery selectors to get the input elements
var fullname = $('#fullname').val();
if (fullname == '') {
alert("First name must be filled out");
return;
}
var phonenumber = $('#phonenumber').val();
if (phonenumber == '') {
alert("Please enter a phone number");
return;
}
//if validations are successful then send the ajax request
$.ajax({
type: "POST",
url: "http://www.bmoseley.com/ajax/addrecord.php",
data: "fullname=" + fullname + "&phonenumber=" + phonenumber,
success: function () {
alert("Name and phone number added successfully!");
}
}).always(function () {
//once ajax request is completed reload the list
$("#displayInfo").load("http://www.bmoseley.com/ajax/listrecords.php");
});
})
})
function isNumberKey(evt) {
var e = evt || window.event; //window.event is safer,
var charCode = e.which || e.keyCode;
if (charCode > 31 && (charCode < 47 || charCode > 57)) return false;
if (e.shiftKey) return false;
return true;
}
It seems that #Arun has already the answer on your question only an additional information to you because I saw your comment on his answer.
If the console says jquery is not defined maybe you did not include the library on your file, you may do it so by
//referencing it on google_codes like
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
//or downloading the framework at [jquery][1] and include to your file like
<script type = "text/javascript" src = "path where you paset the downloaded file"></script>
hope it hepls :)

Categories