Making Java Script global variables - php

I am using the var function to create variables so that I can use them in PHP So I can use the post function, Basically I imported them in javascript.
Anyway how do I make them global variables?
Ive tried including them in the document.ready function or even before the code starts executing document.ready function. it be alot neater then just repeating those var everywhere.
Here is the code
$(document).ready(function () {
var user_login = $('#user_login').val();
var user_pass = $('#pass_login').val();
$('#field').keyup(function (e) {
if (e.keyCode == 13) {
//If enter is pressed vailidate the form
e.preventDefault();
$.ajax({
url: 'ajax/check.php',
type: 'post',
data: {
user_login: user_login,
pass_login: user_pass
},
success: function (data) {
$('#content').html(data);
}
});
};
});
$('#submit').click(function (e) {
if (e.keyCode != 13) {
$.ajax({
url: 'ajax/check.php',
type: 'post',
data: {
user_login: user_login,
pass_login: user_pass
},
success: function (data) {
$('#content').html(data);
}
});
}
});
});

You probably dont want them to be global, as there is no reason. As you have this coded now the variables will be evaluated only once as soon as the document is ready which will be before a user has entered anything in your form fields. You want to evaluate them in your onkeyup handler or on submit of the form so that you have the current values. Im not sure that your check.php does but it should look something like this:
$(function(){
$('form#theform').submit(function(e){
e.preventDefault();
var user_login = $('#user_login').val(),
user_pass = $('#pass_login').val();
// you ajax submit here
});
$('#field').keyup(function(e){
e.preventDefault();
var user_login = $('#user_login').val(),
user_pass = $('#pass_login').val();
// do your validation, if successful then do: $('theform').trigger('submit');
});
});
The reason you dont want to use globals here is because you ALWAYS need the most recent input. If you use a global variable then there is no way to tell that you have the most recent input because things are going to get out of sync.

Global is probably not the way to go here. It sounds like you are more interested in reducing the duplicate code? You could refactor the current code into something like:
$(document).ready(function () {
function submitForm() {
var user_login = $('#user_login').val();
var user_pass = $('#pass_login').val();
$.ajax({
url: 'ajax/check.php',
type: 'post',
data: {
user_login: user_login,
pass_login: user_pass
},
success: function (data) {
$('#content').html(data);
}
});
}
$('#field').keyup(function (e) {
if (e.keyCode == 13) {
//If enter is pressed vailidate the form
e.preventDefault();
submitForm();
};
});
$('#submit').click(function (e) {
if (e.keyCode != 13) {
submitForm();
}
});
});

You need to call .val() on your input each time you want to get the current value of the inputs. If you only call it once at the beginning, the variables won't stay up-to-date as the user types in the inputs.
Do something like this:
$(document).ready(function() {
// Make a function that returns the data, then call it whenever you
// need the current values
function getData() {
return {
user_login: $('#user_login').val(),
user_pass: $('#pass_login').val()
}
}
function check(e) {
e.preventDefault();
$.ajax({
url: 'ajax/check.php',
type: 'post',
data: getData(), // get current values
success: function (data) {
$('#content').html(data);
}
});
}
// Don't repeat so much; use the same function for both handlers
$('#field').keyup(function(e) {
if (e.keyCode == 13) check(e);
});
$('#submit').click(function(e) {
if (e.keyCode != 13) check(e);
});
});

Related

how to login after get key google recaptchaV3

I´m traying to do logging in my web with ajax. But i need generated google key when i do click in login, and before to do login. I have this function:
$('#main-login-form').on('submit', function(e){
renewKeyRecaptcha();
//e.preventDefault();
let key = $("#recaptchaResponse").val();
console.log(key);
if(key != null || key != ""){
var $this = $(this);
$(this).find('input').removeClass('is-invalid');
$(this).find('.error').html('');
var data = $this.serializeArray();
data.push({name: 'currentName', value: config.url.currentName});
$.ajax({
type: $this.attr('method'),
url: $this.attr('action'),
data: data,
dataType: $this.data('type'),
success: function (response) {
if(response.success) {
$(location).attr('href', response.redirect);
}
console.log(response);
},
error: function (jqXHR) {
var response = JSON.parse(jqXHR.responseText);
if (response.errors.password) {
$($this).find('input[name="password"]').addClass('is-invalid');
$($this).find('.password-error').html(response.errors.password);
} else if (response.errors.email) {
$($this).find('input[name="email"]').addClass('is-invalid');
$($this).find('.email-error').html(response.errors.email);
} else if (response.errors.gRecaptchaResponse) {
$($this).find('input[name="g-recaptcha-response"]').addClass('is-invalid');
$($this).find('.g-recaptcha-response-error').html(response.errors.gRecaptchaResponse);
}
}
});
}
});
this function call to renewKeyRecaptcha(); that generated key, but i need to do click login twice and before i´m login... i need to do once click in login and generate key and login... But i can´t. I don´t know if i´m doing well or i would do to another way.
My function that generate key:
function renewKeyRecaptcha(){
// add key google to input
var key = config.url.recaptchaGoogle;
grecaptcha.ready(function() {
grecaptcha.execute(key, {action: 'login'}).then(function(token) {
$("#recaptchaResponse").val(token);
$("#recaptchaResponseRegister").val(token);
});
});
}
this function run ok.
Thanks for help.
I resolve my question with:
$("#submitLogin").on("click", function(e){
renewKeyRecaptcha();
e.preventDefault();
setTimeout(function(){
$(this).find('input').removeClass('is-invalid');
$(this).find('.error').html('');
$this = $('#main-login-form');
var data = $this.serializeArray();
data.push({name: 'currentName', value: config.url.currentName});
$.ajax({
type: $this.attr('method'),
url: $this.attr('action'),
data: data,
dataType: $this.data('type'),
success: function (response) {
if(response.success) {
$(location).attr('href', response.redirect);
}
console.log(response);
},
error: function (jqXHR) {
var response = JSON.parse(jqXHR.responseText);
if (response.errors.password) {
$($this).find('input[name="password"]').addClass('is-invalid');
$($this).find('.password-error').html(response.errors.password);
} else if (response.errors.email) {
$($this).find('input[name="email"]').addClass('is-invalid');
$($this).find('.email-error').html(response.errors.email);
} else if (response.errors.gRecaptchaResponse) {
$($this).find('input[name="g-recaptcha-response"]').addClass('is-invalid');
$($this).find('.g-recaptcha-response-error').html(response.errors.gRecaptchaResponse);
}
}
});
}, 3000);

I want to send form and some text to another file with ajax or json or whatever. Currently it is not working

So I have an onclick function which sends a message to another php file which sends the message to the database. I want to send to the php file, the whole form and a specific chat_index value. So far I have:
$(".comin").keypress(function(event) {
if (event.which == 13) {
event.preventDefault();
var item_id = this.id;
alert(item_id);
if($.get('sendcom.php?q=' + item_id, $('#comform').serialize())) {
var a = $(".comin").val();
alert(a);
document.getElementById(item_id).value = "";
//sent and cleared
}
}
});
post your data in json format,
$(".comin").keypress(function(event) {
if (event.which == 13) {
event.preventDefault();
var chatData = {
q: item_id,
formData:$('#comform').serialize()
}
$.ajax({
url: 'sendcom.php',
type: 'post',
dataType: 'json',
data: chatData,
success: function (data) {
$('#target').html(data.msg);
}
});
}
});

Custom Autocomplete With Ajax/jQuery

I'm creating custom autocomplete with help of Ajax, jQuery and I have hard-coded one database which is created in PHP as I am getting correct output. But when I click on any text in the autocomplete box it does not get selected.
$(document).ready(function () {
$("#search_Textbox").keyup(function () {
var searchbox_Value = $("#search_Textbox").val();
$("#serach_Result").show();
if ($("#search_Textbox").val() == null || ($("#search_Textbox").val() == "")) {
$("#serach_Result").hide();
}
$.ajax({
url: "custom_database.php",
type: "GET",
data: {
text_Value: searchbox_Value
},
success: function (server_Response) {
$("#serach_Result").html(server_Response);
}
});
});
$('a').bind('click', function () {
alert("yes");
var achor_tag_text = $(this).val();
alert(achor_tag_text);
$("#search_Textbox").text(achor_tag_text);
});
});
You could use .on() function it is more preferable from jquery 1.7
$(document).on('click','a', function() {
alert("yes");
//do your stuff
var achor_tag_text = $(this).val();
alert(achor_tag_text);
$("#search_Textbox").text(achor_tag_text);
});
but don't bind common element to click event give an class name to an element then bind your event with that class
You are binding to the <a> tags which are present at the initial load of the page, not those that are present when the ajax returns.
Change your $('a').bind('click', function() { to $(document).on('click', 'a', function() {.

jquery post with $.ajax, how to avoid multiple post?

still looking for a solution but not find yet, I have a function to manage different forms on same/differents pages
function formStantardAction(correctAnswer,addCustomData){
addCustomData = (typeof addCustomData == "undefined")?'':addCustomData;
correctAnswer = (typeof correctAnswer == "undefined")?'Saved.':correctAnswer;
$('form.standard').submit(function(event){
event.preventDefault();
var modalWin = $(this).parent();
var values = $('form.standard').serialize() + addCustomData;
$.ajax({
url: "inc/gateway.php",
data: values,
type: "POST",
success: function(data){
if (data == "OK"){
$(modalWin).html(correctAnswer).delay(500).fadeOut(500);
setTimeout(function() {
mw_close();
}, 1000);
}else{
alert(data);
}
}
});
});
}
after loaded the page and form with an input type="button" named SEND
$('form.standard [name="SEND"]').click(function(){
var str = $('#sortableTo').serializelist();
formStantardAction('New train inserted.',str);
$('form.standard').submit();
});
all the values reach a php page via POST that made all the things (validating, insert in db, update log...) and answer with 'OK' if all OK (so the form in the modal window is substituted with custom message and fade out) or... if there is an error, php answer with some text that js popups with an alert keeping the modal window open with the form.
It's all ok BUT, if php answer with an error, with second click of button SEND the post is sent 2 times.
And if I make another error on second send, and click again the send button, the post values is sent three time... and so on.
What can I do? Where is my error?
thanks.
Try excluding submit block:
function formStantardAction(correctAnswer,addCustomData){
addCustomData = (typeof addCustomData == "undefined")?'':addCustomData;
correctAnswer = (typeof correctAnswer == "undefined")?'Saved.':correctAnswer;
//$('form.standard').submit(function(event){
// event.preventDefault();
//change 'this' to form.standard
var modalWin = $('form.standard').parent();
var values = $('form.standard').serialize() + addCustomData;
$.ajax({
url: "inc/gateway.php",
data: values,
type: "POST",
success: function(data){
if (data == "OK"){
$(modalWin).html(correctAnswer).delay(500).fadeOut(500);
setTimeout(function() {
mw_close();
}, 1000);
}else{
alert(data);
}
}
});
});
// }
and after loaded page:
$('form.standard [name="SEND"]').click(function(){
var str = $('#sortableTo').serializelist();
formStantardAction('New train inserted.',str);
//excluding submit event
// $('form.standard').submit();
});
Because $.ajax {} with type:"Post" is already a submit process and then when script call submit then it re-submit.
Hope this right and help
Is it possbile that somewhere in your code you bind the submit event to the form everytime you get the data back from the ajax-request?
I can't check this in the code you submitted here.
Create a global variable as flag
var flag = 0;
and check this flag while posting and reset it after completed
function formStantardAction(correctAnswer,addCustomData){
**if(flag == 1){
return false;
}
flag = 1;**
addCustomData = (typeof addCustomData == "undefined")?'':addCustomData;
correctAnswer = (typeof correctAnswer == "undefined")?'Saved.':correctAnswer;
$('form.standard').submit(function(event){
event.preventDefault();
var modalWin = $(this).parent();
var values = $('form.standard').serialize() + addCustomData;
$.ajax({
url: "inc/gateway.php",
data: values,
type: "POST",
success: function(data){
**flag = 0;**
if (data == "OK"){
$(modalWin).html(correctAnswer).delay(500).fadeOut(500);
setTimeout(function() {
mw_close();
}, 1000);
}else{
alert(data);
}
}
});
});
}
I put some custom code at the beginning of your submit function - basically if a submit is in progress nothing should be done, but otherwise return an error message as usual.
var submitting = false; //initialise the variable, this needs to be out of the function!
function formStantardAction(correctAnswer,addCustomData){
addCustomData = (typeof addCustomData == "undefined")?'':addCustomData;
correctAnswer = (typeof correctAnswer == "undefined")?'Saved.':correctAnswer;
$('form.standard').submit(function(event){
if (submitting) {
return false; //if a submit is in progress, prevent further clicks from doing anything
} else {
submitting = true; //no submit in progress, but let's make one now
}
event.preventDefault();
var modalWin = $(this).parent();
var values = $('form.standard').serialize() + addCustomData;
$.ajax({
url: "inc/gateway.php",
data: values,
type: "POST",
success: function(data){
if (data == "OK"){
$(modalWin).html(correctAnswer).delay(500).fadeOut(500);
setTimeout(function() {
mw_close();
}, 1000);
}else{
alert(data);
}
}
});
});
}

something wrong with this jquery?

i have these two jquery scripts on my html page, one of them loads more results(like pagination), and the other one replies to users messages, just like twitter!
the replies works(inserts username into textbox), when the page is on default, but when i load more results, the loaded results wnt insert the username into the textbox!! these are the two scripts,
the replies jquery:
function insertParamIntoField(anchor, param, field) {
var query = anchor.search.substring(1, anchor.search.length).split('&');
for(var i = 0, kv; i < query.length; i++) {
kv = query[i].split('=', 2);
if (kv[0] == param) {
field.val(kv[1]);
return;
}
}
}
$(function () {
$("a.reply").click(function (e) {
insertParamIntoField(this,"status_id",$("#status_id"));
insertParamIntoField(this,"reply_name",$("#reply_name"));
insertParamIntoField(this, "replyto", $("#inputField"));
$("#inputField").focus()
$("#inputField").val($("#inputField").val() + ' ');
e.preventDefault();
return false; // prevent default action
});
});
the loadmore jquery script:
$(function() {
//More Button
$('.more').live("click",function()
{
var ID = $(this).attr("id");
if(ID)
{
$("#more"+ID).html('<img src="moreajax.gif" />');
$.ajax({
type: "POST",
url: "ajax_more.php",
data: "lastmsg="+ ID,
cache: false,
success: function(html){
$("ul.statuses").append(html);
$("#more" + ID).remove();
}
});
}
else
{
$(".morebox").html('The End');
}
return false;
});
});
EDIT: when i load more posts, and i click reply the page is refershed, so that ends up with loaded data being hidden again!!
If the reply button is being replaced by the ajax, this might be a workaround.
$(function () {
$("a.reply").live(click, function (e) {
insertParamIntoField(this,"status_id",$("#status_id"));
insertParamIntoField(this,"reply_name",$("#reply_name"));
insertParamIntoField(this, "replyto", $("#inputField"));
$("#inputField").val($("#inputField").val() + ' ').focus();
e.preventDefault();
});
});
Also... If the status_id, reply_name , replyto info is contained within your reply button, make sure these data exists for each reply button after the more button is clicked.

Categories