Automatically submit input on page open with javascript - javascript

I have this code
var file = getUrlVars()["file"];
if(file){
document.getElementById('search').value = file;
}
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
vars[key] = value;
});
return vars;
}
It reads the parameter file from url and then puts the value in the search field.
The search field is ajax powered, when a user enters a letter it starts searching and outputs results.
The problem is that when the scripts puts the value in the search field nothing happens, how do i make the search to fire up?
This is my search field
<input type="text" id="search" class='search_input' />
UPDATE:
My Ajax search code is this
// Search
$(document).ready(function()
{
$(".search_input").focus();
$(".search_input").keyup(function()
{
var search_input = $(this).val();
var keyword= encodeURIComponent(search_input);
var yt_url='http://domain.com/search.php?q='+keyword;
$.ajax({
type: "GET",
url: yt_url,
success: function(response)
{
$("#result").html('');
if(response.length)
{
$("#result").append(response);
}
else
{
$("#result").html("<div id='no'>No results</div>");
}
}
});
});
} );

Your search will only "fire" if the event that initilizes the AJAX functionality is triggered. Thus, you need to trigger the event. My wild guess is the event is bound to either:
- keyup
- click
- blur
You haven't posted the relevant code, but that should be enough of an answer...
After your update
A quick solution is to initiate the keyup event on the search field:
$(".search_input").keyup(function() { ... }).keyup();
Or, you could re-factor the code:
function searchlogic() { ... };
$(".search_input").keyup(searchlogic);
searchlogic();

Related

How to Replace Form Without Triggering the Change Event?

I would like to validate a form with an AJAX request to the server and then swap the form html in the web browser with the form html from the server because this would be an easy implementation in theory. It is proving a nightmare though because the change event is triggered without the user interacting further after the first interaction which triggered the first change event. Consequently an infinite loop of AJAX requests to the server is happening.
The html form sits inside a div which has classes 'container mb-4'. This is the JS code -
var _cont = $('.container.mb-4')
var _form = $('.custom-form')
function ajax_validation(form) {
form.on('change', 'input, select, textarea', function() {
form_data = form.serialize()
$.ajax({
url: "/form/6/",
type: "POST",
data: form_data,
success: function(data) {
if(!(data['success'])) {
_cont.empty()
_cont.append(data['form_html'])
form = _cont.find('form')
ajax_validation(form)
}
},
error: function () {
form.find('.error-message').show()
}
});
})
}
ajax_validation(_form)
The change event I am assuming is triggered because the server returns a form input field with a different csrf token as the value to the previous input field - all other fields are the same. So an obvious solution would be to keep the same csrf token. But I want to understand why the JS code isn't working. I thought destroying the form would destroy the change event bound to it. So am at a loss to explain this infinite loop. How do I change this so I can just swap the form and not trigger another change event until the user really does change something?
It's not a good thing to use events in function no need to do that
Also your event here for input , select , textarea for serialize you need to select the closest() form
Try the next code
var _cont = $('.container.mb-4');
var _form = $('.custom-form');
_cont.on('change', 'form input,form select,form textarea', function() {
var ThisForm = $(this).closest('form');
var form_data = ThisForm.serialize();
$.ajax({
url: "/form/6/",
type: "POST",
data: form_data,
success: function(data) {
if(!(data['success'])) {
_cont.html(data['form_html']);
}
},
error: function () {
ThisForm.find('.error-message').show()
}
});
});
And logically if(!(data['success'])) { should be if(data['success']) {
First let's understand the issue that you have. You have a function called ajax_validation that is defining a change event on the form's elements which, on response will call ajax_validation. So, if any change happens on your elements, then a new request is sent to the server. So, if any value is changed, like a token, the request will be sent again. You could use a semaphore, like this:
var semaphore = true;
function ajax_validation(form) {
form.on('change', 'input, select, textarea', function() {
if (!semaphore) return;
semaphore = false;
form_data = form.serialize()
$.ajax({
url: "/form/6/",
type: "POST",
data: form_data,
success: function(data) {
if(!(data['success'])) {
_cont.empty()
_cont.append(data['form_html'])
form = _cont.find('form')
ajax_validation(form)
}
semaphore = true;
},
error: function () {
form.find('.error-message').show()
}
});
})
}
Something like this should solve your issue for the time being, but you should consider refactoring your code, because what you experience is well-known and is called callback hell.
Turns out the password field was coming back blank from the server - this django must do out of the box if the PasswordInput widget is used. So the form is replaced with a new form which lacks the password input from the before. The browser was then applying the autofill password value to the form which was triggering the change event.
This is my code now. It checks that the form_data about to be sent for validation really is different to before minus the csrf token which will be different.
It is based on Mohamed's answer -
var _cont = $('.container.mb-4');
var _form = $('.custom-form');
var prev_data = undefined
_cont.on('change', 'form input,form select,form textarea', function() {
var ThisForm = $(this).closest('form');
var form_data_wo_csrf = ThisForm.find("input, textarea, select").not("input[type='hidden']").serialize()
if(form_data_wo_csrf == prev_data) {
return
}
var form_data = ThisForm.serialize()
$.ajax({
url: "/form/6/",
type: "POST",
data: form_data,
success: function(data) {
if(!(data['success'])) {
_cont.html(data['form_html']);
prev_data = form_data_wo_csrf
}
},
error: function () {
ThisForm.find('.error-message').show()
}
});
});

Jquery validation for div

I've set up a page with a bunch of contenteditbale divs, along with some js/ajax functionality so that a user can inline edit.
<div class="inlineEdit" contenteditable="true"></div>
JS is a s such:
$(document).ready(function(){
$('div.inline-edit').blur(function()
{
var pathArray = window.location.pathname.split( '/' );
var segment_3 = pathArray[3];
var editableObj = $(this);
var token_input = $('input.token');
var save_data ={};
var token_name = token_input.attr('name');
save_data['field'] = editableObj.attr('id');
save_data['id'] = editableObj.closest('.inline-id').attr('id');
save_data['editedValue'] = editableObj.text();
$.ajax({
url: segment_3+'/update',
type: 'POST',
data:save_data,
success: function(){
//on success functionality
}
});
});
});
This part all works perfectly grand, all the right fields get updated with the right info. All i need is some way to validate that information before it get to the ajax
I know of JQuery Validation however I'm pretty sure it doesn't work with divs.
Is there a solution or am I stuck/have to change up the divs?
You can create a temporary input box and pass the value through it to check validity. I wrote a function to use HTML5 validation to check for validity.
function validityChecker(value, type) {
type = type?type:'text'
$('body').append('<input id="checkValidity" type="'+type+'" style="display:none;">');
$('#checkValidity').val(value)
validity = $('#checkValidity').val()?$('#checkValidity').val().length>0:false && $('#checkValidity')[0].checkValidity()
$('#checkValidity').remove();
return validity;
}
In your case use like this:
if(validityChecker(save_data['editedValue'], 'number')){ // if you want to check for number
$.ajax({
url: segment_3+'/update',
type: 'POST',
data:save_data,
success: function(){
//on success functionality
}
})
}
Demo:
function validityChecker(value, type) {
type = type?type:'text'
$('body').append('<input id="checkValidity" type="'+type+'" style="display:none;">');
$('#checkValidity').val(value)
validity = $('#checkValidity').val()?$('#checkValidity').val().length>0:false && $('#checkValidity')[0].checkValidity()
$('#checkValidity').remove();
return validity;
}
save_data = 'This is not a number';
alert(validityChecker(save_data, 'number')) // false
alert(validityChecker(save_data, 'text')) // true
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

$.ajax error getting back data from php file

I'm developing a website, and right now the registration form of it! But I have something like a problem! I want to create a Username input field, and when the user is typing, check if the username already exists in the database and give some output.
The error is this one: suppose that in the database there is only the username "Manuel". If I type "Manuel" in the input field no message is shown. Now if I type any other character it gives me the message 'The user already exists'. If i delete the last typed character the message goes away. If I type again and have something like "Manuela", the message shows up, if I type again and have "Manuelae" the message goes away
Thanks for your help!!
Here the code
Here the input field: (register.php)
<input type="text" id="username" name="username" maxlength="40" required="required">
<span id="username-info">What's your username?</span>
Here the javascript and jquery code (registration.js)
$(document).ready(function () {
var userExists = new Boolean();
var username = $("#username");
var usernameInfo = $("#username-info");
username.keyup(validateUsername);
}
Here the function validateUsername():
function validateUsername(){
checkUsername();
var minlenght = 5;
var usernameVal = username.val();
if(usernameVal.length < 1){
usernameInfo.addClass("input-error");
usernameInfo.text(messages.FIELD_REQUIRED);
} else if(usernameVal.length < minlenght){
usernameInfo.addClass("input-error");
usernameInfo.text(messages.USERNAME_MIN_WORDS+minlenght+' '+messages.USERNAME_CHARACTERS);
} else if(userExists){
//here i tell the user that the user already exists
usernameInfo.addClass("input-error");
usernameInfo.text('The user already exists');
} else {
usernameInfo.removeClass("input-error");
usernameInfo.text("");
}
}
And here the function checkUsername():
function checkUsername() {
var url = 'processregistration.inc.php';
$.ajax({
type: "POST",
dataType:"json",
url: url,
data: {username: username.val()},
success: function(data){
userExists = data.CHECK; //true if the user exists, false if not
}
});
}
Ajax means Asynchronous JavaScript and XML.
You are doing a check on a value which is actually not received.
You should do something like this :
function validateUsername() {
// remove input-error, text
if (...localcheck...) {
// add input-error, text
}
else if (...otherlocalcheck...) {
// add input-error, text
}
else {
$.ajax({
...
success : function(data) {
if (data.CHECK) {
// add input-error, text
}
}
});
}
}
I think you are on the right track, but I don't think your implementation is correct.
Note: I'm not a javascript hero
$("#filter").keyup( function(e) {
var filter = $("#filter").val(),
timer = $('#filter').data('timeout'),
if(timer) {
clearTimeout(timer);
$('#username').removeData('timeout');
}
$('#username').data('timeout', setTimeout(function() {
var url = 'processregistration.inc.php';
$.POST(url, {username: $('#username').val()}, function(data) {
// you get the picture ;)
updateComponentThatShowsIfUserNameIsTakenFunction(data.CHECK);
});
}, 100));
function updateComponentThatShowsIfUserNameIsTakenFunction(taken) {
$('#username').addClass('input_error');
}
What I did: Removed global variables, they are annoying and error prone. Instead, I'm using a callback named updateComponentThatShowsIfUserNameIsTakenFunction. You can also change it to directly call that function with the "data" of course. I have also added a timeout for you so that you won't call the server EVERY key-up. Every key-up cancels the previous timeout, causing the check to only trigger 100ms after the user is done typing (you don't want to spam your server).
I hope this works and helps you further!

Jquery and the plug-in Validate, testing for no errors

I have obviously done something stupid or failed to understand some fundamental process. Very early days playing with this.
I am trying to check for a form being validated, when the Submit Button is clicked with the onClick method.
<input class="submit" type="submit" value="Submit" onClick="submitForm()" />
I am using Jquery and the plug-in Validate. The problem I have is validating on each field is occurring, but if I click on submit with no data or not every field has been tested, I would need to validate the whole form, before submitting, I should get a return of false from validate().form(). This is not occurring as the else statement in submitForm() is never being executed.
On an empty form, after clicking submit the field error messages are shown, but my testing of a return for false, does not seem to work.
$(document).ready(function() {
$('#formEnquiry').validate();
});
function submitForm() {
$('#msgid').append('<h1>Submitting Form (External Routine)</h1>');
if ($('#formEnquiry').validate().form()) {
$("#msgid").append("<h1>(Outside Ready) VALIDATED send to PHP</h1>");
}
else {
$('#msgid').append('<h1>(Outside Ready) NOT VALIDATED</h1>');
}
};
An example of Ajax
$(function() {
$("#ipenter").submit(function() {
var ip = $("#ip").val();
var date = $("#date").val();
var spammer = $("#spammer").val();
var country = $("#country").val();
var total = $("#total").val();
var dataString = $('#ipenter').serialize();
$.ajax({
url: "/test/process",
data: dataString,
type: "POST",
success: function(msg) {
$('#ipenter').append('<h3 class="gotin">Post succesfull!');
$('h3.gotin').delay(8000).fadeOut(500);
},
error: function(data){
$('#ipenter').prepend('<h3 class="didnt">Post sucked!');
$('h3.didnt').delay(8000).fadeOut(500);
}
});
return false;
});
});
You dont really even need the val() part
You can also throw some validation into this script before the ajax
if (spammer == "") {
$("#spammer_error").show();
$("input#image").focus();
return false;
This is a basic example of ajax(I'm using codeigniter so you may need to use a valid URL for the url)

Help submitting a form to a JQuery script using a javascript submit() function

I attempted to ask this question last week without a resolution. I am still unable to get this to work. What I would like to do is submit data entered through a WYSIWYG javascript editor to a JQuery script I have that will first tell the user if they are trying to submit an empty textbox The last thing I need it to do is tell the user if their data was entered successfully or not.
I am having a problem inside the JQuery script as nothing is being executed when I click the save button.
This editor uses javascript submit() that is tied to a small save icon on the editor. When the user presses the button on the editor, it fires the function I have in the form tag. That's about as far as I was able to get.
I think there is an issue with the form tag attributes because when I click anywhere on the editor, the editor jumps down off the bottom of the screen. I believe it has something to do with the onclick event I have in the form tag.
The first part of the JQuery script is supposed to handle form validation for the textarea. If that's going to be really difficult to get working, I'd be willing to let it go and just handle everything server side but I just need to get the data POSTed to the JQuery script so that I can send it to my php script.
Thanks for the help guys.
<form name="rpt" class="rpt" id="rpt" action="" onclick="doSave(); return false;">
function doSave()
{
$(function()
{
$('.error').hide();
$(".rpt").click(function()
{
$('.error').hide();
var textArea = $('#report');
if (textArea.val() == "")
{
textArea.show();
textArea.focus();
return false;
}
else
{
return true;
}
var dataString = '&report='+ report;
alert (dataString);return false;
$.ajax({
type: "POST",
url: "body.php?action=customer",
data: dataString,
dataType: 'json',
success: function(data){
$('#cust input[type=text]').val('');
var div = $('<div>').attr('id', 'message').html(data.message);
if(data.success == 0) {
$('#cust input[type=text]').val('');
$(div).addClass('ajax-error');
} else {
$('#cust input[type=text]').val('');
$(div).addClass('ajax-success');
}
$('body').append(div);
}
});
return false;
});
});
}
There are a few things you need to change. Firstly this:
<form name="rpt" class="rpt" id="rpt" action="" onclick="doSave(); return false;">
isn't the jQuery way. Plus its not the click() event you want. Do this:
<form name="rpt" class="rpt" id="rpt" action="">
<script type="text/javascript">
$(function() {
$("#rpt").submit(do_save);
});
</script>
The construction:
$(function() {
..
});
means "when the document is ready, execute this code". It is shorthand for and exactly equivalent to the slightly longer:
$(document).ready(function() {
..
});
This code:
$("#rpt").submit(doSave);
means "find the element with id 'rpt' and attach an event handler to it such that when the 'submit' event is executed on it, call the do_save() function".
And change doSave() to:
function doSave() {
$('.error').hide();
$(".rpt").click(function() {
$('.error').hide();
var textArea = $('#report');
if (textArea.val() == "") {
textArea.show();
textArea.focus();
return false;
} else {
return true;
}
var dataString = '&report='+ report;
alert (dataString);return false;
$.ajax({
type: "POST",
url: "body.php?action=customer",
data: dataString,
dataType: 'json',
success: function(data){
$('#cust input[type=text]').val('');
var div = $('<div>').attr('id', 'message').html(data.message);
if (data.success == 0) {
$('#cust input[type=text]').val('');
$(div).addClass('ajax-error');
} else {
$('#cust input[type=text]').val('');
$(div).addClass('ajax-success');
}
$('body').append(div);
}
});
});
return false;
}
Note: return false is in the correct place now so it actually prevents the form submitting back to the server. action="" just means the form will submit back to its current location so you have to prevent that.
function X() {
$(function() {
//... things you want to do at startup
});
};
Doesn't do what you want. Nothing is ever executed, because you never tell it to be executed.
You might want to try something like:
<script type="text/javascript">
jQuery(function($) {
//... things you want to do at startup
});
</script>
Also, you want the onsubmit event of the form. You can use
$('#theform').submit(function() {
//... perform the ajax save
});
In addition, you may want to look into the Form plugin.

Categories