How to select the clicked form in Jquery [ $(this) ] - javascript

This is my code:
function onsubmitlogin(token)
{
$(document).ready(function()
{
$("form.formajax").submit(function(e)
{
e.preventDefault();
var data = $(this).serialize();
var url = $(this).attr("action");
var form = $(this);
$.post(url, data, function(data)
{
$(form).children(".signupresult").css("opacity", "1");
$(form).children(".loginresult").html(data.loginresult);
$(form).children(".loginresult").css("opacity", "1");
});
return false;
});
$(this).submit();
});
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<form action="abc.com" method="post" class="formajax" >
<input type="text">
<input type="submit">
</form>
<form action="xyz.com" method="post" class="formajax" >
<input type="text">
<input type="submit">
</form>
The problem is with this line $(this).submit(); (last 3rd line of jquery code)
I want to submit only the clicked form. What is the problem?
$(this); is working on the above code

Try following:
function onsubmitlogin(token){
$(document).ready(function(){
$("form.formajax").each(function(e){
$(this).submit(function(e){
e.preventDefault();
var data = $(this).serialize();
console.log(data);
var url = $(this).attr("action");
console.log(url);
var form = $(this);
$.post(url, data, function(data){
$(form).children(".signupresult").css("opacity", "1");
$(form).children(".loginresult").html(data.loginresult);
$(form).children(".loginresult").css("opacity", "1");
});
$(this).submit();
return false;
});
});
});
};

Related

Ajax call is not working when selecting checkboxes in the form

I am developing a form using django framework. I have a form where i have a table followed by some check boxes in the form. I am collecting that data into a dictionary and passing that to my django function. If i am submitting my form without selecting checkboxes it is working fine. But when i select checkboxes that data is not getting posted to views.py file. I see that data is being populated in the dictionary by using console.log.
Require guidance regarding this.
my html:
<table>
.....
.....
</table>
<div class="checkbox">
<label><input type="checkbox" name="run_prep" value="">Run Prep</label>
</div>
<div class="checkbox">
<label><input type="checkbox" name="run_post"value="">Run Post</label>
</div>`enter code here`
<div class="checkbox">
<label><input type="checkbox" name="run_reports" value="">Run Reports</label>`enter code here`
</div>
Below is my js code:
$(document).ready(function(){
$("form").submit(function(e){
e.preventDefault();
var data = {};
form_data = []
$("tr", "tbody").each(function(row){
var count_row = true;
$("input", this).each(function(idx, inp){
if (!($(this).val())){
count_row = false;
}
});
$("select", this).each(function(idx, inp){
if (!($(this).val())){
count_row = false;
}
});
if (count_row){
row_data = {};
$("input", this).each(function(idx, inp){
row_data[$(this).attr("name")] = $(this).val();
});
$("select", this).each(function(idx, inp){
row_data[$(this).attr("name")] = $(this).val();
});
var id = $(this).attr("id");
data[id] = row_data;
form_data.push(data);
data = {};
}
});
run_check = {};
$("input[type=checkbox]", this).each(function () {
if (this.checked) {
run_check[$(this).attr("name")] = 1;
}
});
var chkname = "run-check"
data[chkname] = run_check;
form_data.push(data);
var csrftoken = Cookies.get('csrftoken');
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
}
});
console.log(JSON.stringify(form_data))
$.ajax({
type: "POST",
contentType: 'application/json',
data: JSON.stringify(form_data)
}).then(function(data){
console.log(data);
location.replace(data.redirect);
});
});
});

JavaScript validation before AJAX submission

I'm trying to validate a form before allowing my ajax submission,however I have two problems. The first problem being I don't know how to best go about validating before submission (most professional process). The second problem being, what is preventing my validation code I currently from working? Looking to become more efficient so all input is welcome. Thanks a ton.
$('#form-reg').on('submit', function(){
var bool = false;
var name = document.getElementById('#name-reg');
var email = document.getElementById('#email-reg');
console.log(name);
console.log(email);
if(!/[^a-zA-Z]/.test(name)){
bool = true;
}
else{
bool = false;
}
if(bool == true){
console.log(document.getElementById('#name-reg'));
$('#form-reg').slideUp('slow');
// serialize the form
var formData = $(this).serialize();
console.log(formData);
$.ajax({
type : 'POST',
url : 'register.php',
data : formData,
success: function() {
alert("Success");
},
error: function(xhr) {
alert("fail");
}
})
.done(function (data) {
document.getElementById('form-reg').reset();
})
.fail(function (error) {
alert("POST failed");
});
//return false;
}
else {
alert('try again');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js" type="text/javascript">
<form id = "form-reg">
<label id ="x" for="name">Name</label>
<input id="name-reg" name="name"></br>
<label id = "y" for="email">Email</label>
<input id="email-reg" name="email"></br>
<input type="submit" value="submit" id = "submit-reg">
</form>
The issue with your code is you have to stop the form submit like:
$('#form-reg').on('submit', function(e){
e.preventDefault();
and after checking the validation, submit the form if validation succeeds.
Although it is a minor answer, I will post it anyway. The problem looks like the use of
var name = document.getElementById('#name-reg');
the # is causing the first problem and should be
var name = $('#name-reg').val();
$('#form-reg').on('submit', function(){
var bool = false;
var name = $('#name-reg').val();
var email = $('#email-reg').val();
console.log(name);
console.log(email);
if(!/[^a-zA-Z]/.test(name)){
bool = true;
}
else{
bool = false;
}
if(bool == true){
console.log($('#name-reg').val());
$('#form-reg').slideUp('slow');
// serialize the form
var formData = $(this).serialize();
console.log(formData);
$.ajax({
type : 'POST',
url : 'register.php',
data : formData,
success: function() {
alert("Success");
},
error: function(xhr) {
alert("fail");
}
})
.done(function (data) {
document.getElementById('form-reg').reset();
})
.fail(function (error) {
alert("POST failed");
});
//return false;
}
else {
alert('try again');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js" type="text/javascript">
<form id = "form-reg">
<label id ="x" for="name">Name</label>
<input id="name-reg" name="name"></br>
<label id = "y" for="email">Email</label>
<input id="email-reg" name="email"></br>
<input type="submit" value="submit" id = "submit-reg">
</form>

How to send multiple variables through ajax?

The code below sends the id of item to more.php to load more content. It works fine. Now to add some more features I need to send one more id to more.php through the same code.
<script type="text/javascript">
$(document).ready(function(){
$(document).on('click','.show_more',function(){
var ID = $(this).attr('id');
$('.show_more').hide();
$('.loding').show();
$.ajax({
type:'POST',
url:'more.php',
data:'id='+ID,
success:function(html){
$('#show_more_main'+ID).remove();
$('.display').append(html);
}
});
});
});
</script>
Suppose second id is var catid = '<?php echo $cat ?>'; how to send this catid through the same ajax code. data : {id : id, catid : catid} is something I should do but can't get how to deal in current situation when my data carries data:'id='+ID,.
your should look like. specify your data as an object:
<script type="text/javascript">
$(document).ready(function () {
$(document).on('click', '.show_more', function () {
var ID = $(this).attr('id');
$('.show_more').hide();
$('.loding').show();
$.ajax({
type: 'POST',
url: 'more.php',
data: { id:ID, userid: userid },
success: function (html) {
$('#show_more_main' + ID).remove();
$('.display').append(html);
}
});
});
});
To retrieve multiple input's I suggest combining them in a Form:
first embed your inputs in an form with a submit button, you should also not use the same name twice because it won't work now, create unique names
<form action="GET" id="myForm">
<input id="string" type="text" name="string" />
<input id="string2" type="text" name="string" />
<input type="submit" value="Go" />
</form>
and write code to submit the ajax way
$('#myForm').submit(function(event) {
// Stop form from submitting normally
event.preventDefault();
var $form = $(this);
$.ajax({
type: "GET",
url: "retrieve.php",
data: $form.serialize(), //make it JSON
success: function() {
console.log("it worked");
}
});
});

Why javascript press enter button no function?

I am working on a text field which is pressable with "enter" button but unfortunately it does not work. I am trying following code inside my project.
This is my JavaScript code:
<script>
$(document).ready(function() {
// Live Search
// On Search Submit and Get Results
function search() {
var query_value = $('input#search').val();
$('b#search-string').html(query_value);
if(query_value !== ''){
$.ajax({
type: "POST",
url: "search.php",
data: { query: query_value },
cache: false,
success: function(html){
$("ul#results").html(html);
}
});
}
return false;
}
$("input#search").live("keyup", function(e) {
var theSearch = $('#search');
// Set Timeout
clearTimeout($.data(this, 'timer'));
// Set Search String
var search_string = $(this).val();
// Do Search
if (search_string == '') {
$("ul#results").fadeOut();
$('h4#results-text').fadeOut();
}else{
$("ul#results").fadeIn();
$('h4#results-text').fadeIn();
$(this).data('timer', setTimeout(search, 0));
};
});
});
$("#search").on('keyup',function(e){
var text = document.getElementById("search").value;
if(text !== ""){
if (e.which == 13){
$("#btnSearch").click();
}
}
});
function doSomething(){
var text = document.getElementById("search").value;
window.location.assign("search.php?value = " + text);
}
});
</script>
This is my HTML code:
<input type="text" id="search">
<input type="button" id="btnSearch" onclick="doSomething();" />
use unique selector id
$("#search").on('keyup',function(e){
if (e.which == 13){
alert('abc');
}
});
demo jsfiddle
use input type selector
$('input[type=text]').each(function(i,e) {
$("#"+e.id).on('keyup',function(e){
if (e.which == 13){
alert('abc');
}
});
});
another demo
Place $("input[type=text]").on... inside $(document).ready and make sure you are using JQuery version before 1.7 If you wish to use live
change your html to
<form onsubmit="doSomething();" >
<input type="text" id="search">
<input type="submit" id="btnSearch" />
</form>
while using this you don't have to listen enter key event your doSomething() function will be called automatically on enter press in input field
DEMO

Highlight live search results

I'm trying to highlight the text that matches the query in a live search using jquery.highlight. The live search works fine but the styling for the highlighting applies then it disappears. Am I doing something wrong?
JQuery
$(document).ready(function() {
$("#search").bind("keyup", function() {
var form = $(this).parents("form");
var query = $(this).val();
var formData = form.serialize();
$.post("/questions/new/search", formData, function(html) {
$("#questionList").html(html);
});
$(".question").highlight(query);
});
});
HTML
<form action="/questions" method="get">
<input id="search" name="search" type="text" />
</form>
<div id="questionList">
<div class="question">What is the 1 + 1?</div>
<div class="answers">2</div>
</div>
Yes, you should execute $(".question").highlight(query) in the http request response handler right after $("#questionList").html(html) this way:
$(document).ready(function() {
$("#search").bind("keyup", function() {
var form = $(this).parents("form");
var query = $(this).val();
var formData = form.serialize();
$.post("/questions/new/search", formData, function(html) {
$("#questionList").html(html);
$(".question").highlight(query);
});
});
});

Categories