I am developing a simple tool as a project and I am having some issues with the website crashing when the AJAX part of my website is requested/used to many times in a row.
I have a bunch of text fields, and when the user enters into any of them, I want to the test to be typed out automatically below the input field. For example if the user types "test1" Into the first field, and "test2" into the second, I want "test1 test2" to dynamically output below without the page refreshing. I know how to do this in PHP however I need to use AJAX or JQUERY so the page does not refresh.
Here is my input field page:
<form id="refme">
<input type="text" id="url" placeholder="URL" autocomplete="off"><br>
<input type="text" id="f_name" placeholder="First Name" autocomplete="off"><br>
<input type="text" id="s_name" placeholder="Second Name" autocomplete="off"><br>
<br>
Reference
<hr>
<!-- FINISHED REFERENCE -->
<div id="sindex_result">
</div>
</form>
<script>
$(document).ready(function() {
$('#refme input[type=text]').keyup(function() {
var url = $('#url').val();
var f_name = $('#f_name').val();
var s_name = $('#s_name').val();
if(url === '' && f_name == '' && s_name == ''){}
else
{
$('#sindex_result').html('');
$.ajax({
url:"http://bradleycousins.co.uk/fetch.php",
method:"post",
data:{url:url, f_name:f_name, s_name:s_name},
dataType:"text",
success:function(data)
{
$('#sindex_result').html(data);
}
});
}
});
});
</script>
Here is my AJAX, 'fetch.php' file:
echo $_POST['f_name'] . " " . $_POST['s_name'];
This should be pretty simple and currently what I have works. However when used say 4 times in a row then the website goes offline and I get this error "Failed to open page / Safari went offline" This is an issue with all browsers, I checked, so it must be an issue in the code.
Thankyou for any help
====
EDIT
A possible solution might be to delay the AJAX Call requests ? I have tried implementing this but nothing outputs at all now,
<script>
$(document).ready(function() {
var delay = (function () {
var timer = 0;
return function (callback, ms) {
clearTimeout(timer);
timer = setTimeout(callback, ms);
};
})();
$('#refme input[type=text]').keyup(function() {
delay(myKeyUpFunction, 250);
var url = $('#url').val();
var f_name = $('#f_name').val();
var s_name = $('#s_name').val();
if(url === '' && f_name == '' && s_name == ''){}
else
{
$('#sindex_result').html('');
$.ajax({
url:"http://bradleycousins.co.uk/fetch.php",
method:"post",
data:{url:url, f_name:f_name, s_name:s_name},
dataType:"text",
success:function(data)
{
$('#sindex_result').html(data);
}
});
}
});
});
</script>
The solution is you add a slight delay so that when the user types the Ajax call is made 250ms after input has finished.
$('#refme input[type=text]').keyup(function() {
delay(function(){
var url = $('#url').val();
var f_name = $('#f_name').val();
var s_name = $('#s_name').val();
if(url === '' && f_name == '' && s_name == ''){}
else
{
$('#sindex_result').html('');
$.ajax({
url:"http://bradleycousins.co.uk/fetch.php",
method:"post",
data:{url:url, f_name:f_name, s_name:s_name},
dataType:"text",
success:function(data)
{
$('#sindex_result').html(data);
}
});
}
}, 250);
Related
I know it seems basic, but hear me out, I've been trying to figure it out for a good chunk of the day and something just isn't working.
I'm trying to replace the value of a hidden form field with the visitors IP address. This is the field in question:
<label class="previewLabel" for="awf_field-106493013">ipaddress:</label>
<div class="af-textWrap"><input type="text" id="awf_field-106493013" class="text" name="custom ipaddress" value="" onfocus=" if (this.value == '') { this.value = ''; }" onblur="if (this.value == '') { this.value='';} " tabindex="503" /></div>
And this is the code I have on my page currently:
<script type="text/javascript">
function getUrlParam(name, url) {
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, '\\$&');
var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, ' '));
}
var tid = getUrlParam("adid");
var date = Date(Date.now());
jQuery(document).ready(function () {
(function (){
jQuery.ajax({
async: false,
type: 'GET',
url: 'https://api.ipify.org/?format=json',
success: function(data) {
//callback
console.log(data.ip) //This works properly;
jQuery('#awf_field-106493013').val(data.ip); //This does not work
}
});
}());
jQuery('#awf_field-106493014').val(date.toString()); //This works properly
if(tid != null){
jQuery('#awf_field-106493015').val(tid.toString()); //This works properly
}else{
jQuery('#awf_field-106493015').val("nulltid"); //This works properly
}
});
</script>
I've also tried to make the call and replacement with jQuery.get and the replacement with document.getElementById. All other fields are replaced except for this one IP field and, as the comment in the code says, the IP is even properly printed into the console before it's dropped while trying to be replaced.
I've also tried changing async from false to true, but this also did not work.
I have no idea why this is behaving how it is and would like some assistance.
Thanks!
Are you saying you are unable to retrieve the ip address to the text box with id "awf_field-106493013" ?
If yes, your code works fine for me.
https://jsfiddle.net/7yqrk1hL/
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
<label class="previewLabel" for="awf_field-106493013">ipaddress:</label>
<div class="af-textWrap"><input type="text" id="awf_field-106493013" class="text" name="custom ipaddress" value=""
onfocus=" if (this.value == '') { this.value = ''; }" onblur="if (this.value == '') { this.value='';} "
tabindex="503" /></div>
<script>
$(document).ready(function () {
(function () {
jQuery.ajax({
async: false,
type: 'GET',
url: 'https://api.ipify.org/?format=json',
success: function (data) {
//callback
console.log(data.ip) //This works properly;
jQuery('#awf_field-106493013').val(data.ip); //This does not work
}
});
}());
jQuery('#awf_field-106493014').val(date.toString()); //This works properly
if (tid != null) {
jQuery('#awf_field-106493015').val(tid.toString()); //This works properly
} else {
jQuery('#awf_field-106493015').val("nulltid"); //This works properly
}
});
</script>
</body>
</html>
As it turned out this particular api was returning some sort of weird json object, after reading their documentation I changed https://api.ipify.org/?format=json to https://api.ipify.org/ and it worked perfectly.
hello i have a login validation form which uses a mix of jquery and ajax to do validations... if the values are ok the form should submit, if the values are not ok then the form should not submit... however in my case the form is submitting even when the values are incorrect ( i am using the mousedown function ) please see below my code..
<form method="post" name="loginform" action="models/login.php">
<input type="email" class="homepage" name="user_email2" id="user_email2" placeholder="Email" maxlength="50" />
<div class="errormsg" id="errormsg6"></div>
<input type="password" class="homepage" name="user_password2" id="user_password2" placeholder="Password" maxlength="20" />
<div class="errormsg" id="errormsg7"></div>
<input type="submit" name="login" id="login" value="Submit">
<div class="errormsglast" id="errormsg8"></div>
</form>
jquery and ajax
$(document).ready(function()
{
/* ----------------- Login Validations Global Variables ----------------- */
var user_email2 = "";
var user_emailajax2 = "";
var user_password2 = "";
var user_passwordajax2 = "";
var emailformat = new RegExp(/^[+a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/i);
/* ----------------- Define Validate Email */
var validate_email_login = function()
{
var item5 = $("#user_email2").val().toLowerCase();
if (item5.length < 6 || item5.length > 50)
{
$("#errormsg6").html("Email : 6 - 50 Characters");
user_email2 = "";
}
else
{
$("#errormsg6").html("");
user_email2 = item5;
if (!emailformat.test(item5))
{
$("#errormsg6").html("Wrong Email Format");
user_email2 = "";
}
else
{
$("#errormsg6").html("");
user_email2 = item5;
$.ajax(
{
type: 'POST',
url: 'classes/validatelogin.php?f=1',
data: "user_email2=" + item5,
success: function(msg)
{
if (msg == "ok")
{
user_emailajax2 = "";
$("#errormsg6").html("Email Does Not Exist");
}
else if (msg == "exists")
{
user_emailajax2 = item5;
$("#errormsg6").html("");
}
}
});
}
}
}
/* ----------------- Define Validate Password */
var validate_password_login = function()
{
var item5 = $("#user_email2").val().toLowerCase();
var item6 = $("#user_password2").val();
if (item6.length < 8 || item6.length > 20)
{
$("#errormsg7").html("Password : 8-20 Characters");
user_password2 = "";
}
else
{
$("#errormsg7").html("");
user_password2 = item6;
if (user_email2 != "" && user_emailajax2 != "")
{
$.ajax(
{
method: "POST",
url: "classes/validatelogin.php?f=2",
data: "user_email2=" + item5 + "&user_password2=" + item6,
success: function(msg)
{
if (msg == "WrongPw")
{
user_passwordajax2 = "";
$("#errormsg7").html("Wrong Password - See Forgot Password");
}
else if (msg == "CorrectPw")
{
user_passwordajax2 = item6;
$("#errormsg7").html("");
/* window.location.href="manage-properties"; */
}
}
});
}
}
}
/* ----------------- Run Functions */
$("#user_email2").on('focusout', validate_email_login);
$("#user_password2").on('focusout', validate_password_login);
/* ----------------- Stop on Submit */
$( "#login" ).mousedown(function()
{
validate_email_login();
validate_password_login();
if (user_email2 == "" || user_emailajax2 == "" || user_password2 == "" || user_passwordajax2 == "")
{
$("#errormsg8").html("Please Fill All Fields (Correctly)");
console.log("submit false");
return false;
}
else
{
$("#errormsg8").html("");
console.log("submit true");
return true;
}
});
});
Solution Tried - problem is that when user puts the wrong event that is fine, but if user then puts the correct values, the submit returns false on first time, then second time it returns true... it should return true in first go
<input type="button" name="login" id="login" value="Submit">
$( "#login" ).mousedown(function()
{
validate_email_login();
validate_password_login();
if (user_email2 == "" || user_emailajax2 == "" || user_password2 == "" || user_passwordajax2 == "")
{
$("#errormsg8").html("Please Fill All Fields (Correctly)");
console.log("submit false");
return false;
}
else
{
$("#errormsg8").html("");
console.log("submit true");
$('[name=loginform]').submit();
}
});
});
Instead of having a type="submit" button just have a normal button e.g<input type="button" name="login" id="login" value="Submit">. Then when you finished checking the values and happy that it should send then just call:
$('[name=loginform]').submit();
Because what is happening currently is that the form submits when you click on the button, because you are not stopping that event from happening.
If you want to prevent the form from submitting I would suggest either not using that button and initiating the submit yourself like I mentioned above, or alternatively you can use the onsubmit="someFunction()" on the form element way and just return false if it should not submit and return true if it should.
I would say your code suffers from a few issues and some bad practices.
I see you are trying to learn JS so forgive me for not directly solving your issue but to give you some pointers and point you to some best practices.
Logic -
It seems like you are doing a login form. I would say most of this checks should not happen in the client but on the server.
When user signups it might be wise to check user name length on the client as well and prompt the user that he can't use the user name he wants to register with, but during login all the client care is can I login or not.
Security -
You seem to have two serious security issues with your code
You allow to test if an e-mail/user exist or not using 'classes/validatelogin.php?f=1'. in general you should always test the user and password together if they exist and match the user should be able to login, if not the login should fail. you shouldn't notify the user why it fails (if the user name does not exist or if it exist but the password is wrong).
You don't seem to hash passwords in the database. I assume it by limiting the password max length. let the user choose as long password as he wants and hash it using a secure hashing algorithm (I'd suggest bcrypt but google around and find a suitable one). I know you are only learning but this is highly important I think hashing is the first thing you need to learn when handling user logins
Working with the DOM.
You should cache your DOM elements
so instead of calling $('#id') all the time in the main function scope set
var emailInput = $("#user_email2");
function submitForm() {
var email = emailInput.val().toLowerCase();
...
}
You should also probably set the text value of the element and not the html doesn't matter much now but since you are setting text value its good practice and will help you avoid unexpected injections and errors.
Since your using ajax you should not let the form to submit itself even when validation is successful.
Common logic should be packed into functions and reused.
There are many places where your original code can be split into shorter and reusable functions
handle async code better
jQuery supports the Promise API when using ajax requests, I would rather use it. Your original code had a few async calls if you needed to sync between them it would have been painful using plain callbacks (and it is probably what caused you issues in the first place)
Here is a simplified solution using my suggestions -
$(document).ready(function() {
"use strict";
var emailInput = $("#user_email2"),
emailError = $("#errormsg6"),
passwordInput = $("#user_password2"),
passwordError = $("#errormsg7");
function required (value) {
if (value) {
return true;
} else {
return false;
}
//this is just to make the code clear you could use
//`return value ? true : false` or `return !!value`
}
$('form:eq(0)').on('submit', function (e) {
var valid = true,
email = emailInput.val(),
password = passwordInput.val();
e.preventDefault();
if ( !required(email) ) {
emailError.text('Email is required');
valid = false;
}
if ( !required(password) ) {
passwordError.text('Password is required');
valid = false;
}
if ( valid ) {
$.ajax({
method: "POST",
url: "login.php",
data: {
email: email,
password: password
}
}).done(function (data, textStatus, jqXHR) {
//redirect user to main page
}).fail(function (jqXHR, textStatus, errorThrown) {
//show the user the error
})
}
});
});
I have the following code. So basically the JavaScript needs to look at the username and password and check it via an API (which works) and returns true or false. True giving the user access to the next page and false reloading the login page. Everything works perfectly except for the JavaScript if statement. My code is as follows:
var ApiKey = ''; //generated API Key
var userPass = document.getElementById('pass'); //gets the password
var userName = document.getElementById('usr'); //gets the username
function testAJAX(){
$.getJSON("http://mywebsitesapiaddress.com/api" + ApiKey +"&user="+ userName.value + "&pass=" + userPass.value, function(data) {
if (data.success == "true") {
window.location = "mainpage.html";
}
else {
location.reload();
}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<input type="text" name="username" id="usr" placeholder="Enter your username">
<input type="password" name="password" id="pass" placeholder="Enter your password">
<button onclick="testAJAX()" id ="login">Login</button>
When JSON data is true or false. Double quotes cannot be used.Thank you for the quick responses. Turns out the problem was that the datatypes are clashing, I changed the API response to 1 and 0 and that seemed to have solved the problem. Easier and more flexible when using numbers.
var ApiKey = ''; //generated API Key
var userPass = document.getElementById('pass'); //gets the password
var userName = document.getElementById('usr'); //gets the username
function testAJAX(){
$.getJSON("http://mywebsitesapiaddress.com/api" + ApiKey +"&user="+ userName.value + "&pass=" + userPass.value, function(data) {
if (data.success == 1) {
window.location = "mainpage.html";
}
else {
location.reload();
}
});
}
Your code looks fine, except for the type of the success property value.
It could be that the server is not returning a string literal 'true' instead a boolean value true so
if (data.success) { //or data.success === true
window.location = "mainpage.html";
} else {
location.reload();
}
Please find the code here - https://github.com/iamanandkris/RedirectURL/blob/master/app/views/editRedirect.scala.html. I am trying to print the contents of Input 1,2 and 3 in to the div as and when the focus changes from any of these 3 objects. I am able to see that the java script is getting invoked when the focus changes and am able to get the alert also. I am able to populate the below 3 values
var idToGet = document.getElementById('uid').value
var qargsToGet = document.getElementById('qargs').value
var rurlToGet = document.getElementById('rurl').value
But the statement is not working
var s= document.getElementById('thecurrenturl');
s.html = "testing again";
Please go thru the full code below:
#(redirectForm: Form[RedirectModel])(implicit flash: Flash, lang: Lang)
#import helper._
#import helper.twitterBootstrap._
#main(Messages("products.form")) {
<h2>#Messages("products.form")</h2>
#helper.form(action = routes.Redirects.save()) {
<fieldset>
<label for="targetURL">Target URL: </label>
<div id="thecurrenturl"></div>
<legend>
#Messages("products.details", Messages("products.new"))
</legend>
#inputText(
redirectForm("uid"), '_label -> "User ID",'onBlur->"myFunction()",'_help -> "Enter a valid user id."
)
#textarea(
redirectForm("qargs"), 'onBlur->"myFunction()"
)
#textarea(
redirectForm("rurl"), 'onBlur->"myFunction()"
)
</fieldset>
<p><input type="submit" class="btn primary"
value='#Messages("products.new.submit")'></p>
}
<script type="text/javascript">
var successFn = function(data) {
console.debug("Success of Ajax Call");
console.debug(data);
};
var errorFn = function(err) {
console.debug("Error of ajax Call");
console.debug(err);
}
ajax1 = {
success: successFn,
error: errorFn
}
function myFunction() {
alert("test")
var idToGet = document.getElementById('uid').value
var qargsToGet = document.getElementById('qargs').value
var rurlToGet = document.getElementById('rurl').value
var s= document.getElementById("thecurrenturl");
s.html = "testing again";
alert(idToGet+'/'+qargsToGet+'/'+rurlToGet)
jsRoutes.controllers.Redirects.getString()
.ajax(ajax1);
}
</script>
}
Change line below
s.html = "testing again";
to
s.innerHTML = "testing again";
html is a jQuery function.
Am trying to create a login page for my windows 8 app, am using Html5 and javascript.. so have tried to use winjs.xhr to post what is in the textboxes as variables to a specific url which is a php script so this is my example of the url "http://example.com/api/username=username&password=password" am using winjs.xhr to post these variables to the url but am not getting any response even in the console.log
this is my code
<script>
function handlelogin(){
document.getElementById("box").onsubmit = function(){
if(document.getElementById("email_address").value ==""){
document.getElementById("errormessage").innerHTML= "Please Provide Your Email Address";
return false;
}else{
var email_address = document.getElementById("email_address");
var password = document.getElementById("password");
var formparams = "?username=" + email_address.value + "&password=" + password.value;
document.getElementById("errormessage").innerHTML = "";
WinJS.xhr({type: "POST",
url: "http://example.com/api/",
data: formparams,
headers: { "Content-type": "application/x-www-form-urlencoded" }
}).then(
function (success) {
console.log(success.statusText);
if(success == 1703){
WinJS.Navigation.navigate("home.html");
}
},
function (error) {
console.log(error);
}
);
}
};
}
window.onload = function () {
handlelogin();
}
</script>
<form id="box" method="post" name="loginform">
<p>Email address</p>
<div class="email_address"><input type="text" id="email_address" /></div>
<p>Password</p>
<div class="password"><input type="password" id="password" /></div>
<p><span id="errormessage"></span></p>
<div class="button"><input type="submit" id="login" value="Sign In"/></div>
<p>ForgotPassword?</p>
</form>
First - don't use a submit button. Use a input type="button". No submit required, you are simply reading the values on the page.
Second - attach the event handler for the button's click event. Doing this 'onload' for the window isn't the right place.
Third - don't use 'onsubmit' for your 'box' element. There is no form submission going on here. There shouldn't usually be a form submit in WinJS - that's for a browser posting the page to the server. You already are POSTing your data. See the updated code:
I highly recommend putting ALL javascript into separate files, as you'll get bytecode optimization that way. Inline Javascript isn't optimized for the next load. A common way you could do this is include the onload code below (where I assign onclick) in your js file like so
app.onactivated = function (args) {
..
..
..
args.setPromise(WinJS.UI.processAll().then(function () {
document.getElementById("login").onclick = handlelogin;
}));
..
..
}
};
But the answer directly for your question above is:
<script>
function handlelogin() {
if (document.getElementById("email_address").value == "") {
document.getElementById("errormessage").innerHTML = "Please Provide Your Email Address";
return false;
} else {
var email_address = document.getElementById("email_address");
var password = document.getElementById("password");
var formparams = "?username=" + email_address.value + "&password=" + password.value;
document.getElementById("errormessage").innerHTML = "";
WinJS.xhr({
type: "POST",
url: "http://example.com/api/",
data: formparams,
headers: { "Content-type": "application/x-www-form-urlencoded" }
}).then(
function (success) {
console.log(success.statusText);
if (success == 1703) {
WinJS.Navigation.navigate("home.html");
}
},
function (error) {
console.log(error);
}
);
}
}
window.onload = function() {
document.getElementById("login").onclick = handlelogin;
};
</script>
Check out some of the sessions in App Builder where they discuss JavaScript projects http://aka.ms/stackbuilder