Get id of parent div from clicked form submit - javascript

Okay so I have multiple forms on the page, the difference is their id, also each one has a parent box, all of which also have a different id.
The html of one of the box:
<div class="center-block" id="box2">
<form action="/login" id="form2" method="post" novalidate="novalidate">
<input data-val="true" data-val-number="The field Id must be a number." data-val-required="The Id field is required." id="Id" name="Id" type="hidden" value="2">
<input id="Name" name="Name" type="hidden">
<input type="submit" value="Submit">
</form>
</div>
I submit the forms with ajax, and what I want to do is find the id of the box that had its form submitted.
This is the script:
<script type="text/javascript">
$(document).ready(function() {
$('form').submit(function () {
$.ajax({
url: $(this).data('url'),
type: 'POST',
data: $(this).serialize(),
success: function (data) {
if (data !== "0") {
window.location.href = data;
} else {
//Here I would like to alert the id of the parent box.
//Something like this:
alert($(this).closest('div').attr('id'));
//Which returns undefined
}
},
error: function () {
alert("No idea what went wrong");
}
});
return false;
});
});
</script>
Any idea how I would do that?

$(this) won't work in success callback. $(this) is relative, the scope of $(this) will be of success callback. You need to assign a variable first & then use it in success callback
<script type="text/javascript">
$(document).ready(function() {
$('form').submit(function () {
var curr_form = $(this);
$.ajax({
url: $(this).data('url'),
type: 'POST',
data: $(this).serialize(),
success: function (data) {
if (data !== "0") {
window.location.href = data;
} else {
//Here I would like to alert the id of the parent box.
//Something like this:
curr_form.closest('div').attr('id')
//Which returns undefined
}
},
error: function () {
alert("No idea what went wrong");
}
});
return false;
});
});
</script>

Just use the JQuery parent() method:
alert($(this).parent().attr('id'));
Also, as others have pointed out, you have a different issue in that this isn't pointing to the form when you use it in the success callback. You should cache that value and then use the cache variable. You can read more about how this works in JavaScript in another post of mine.
$(document).ready(function() {
$('form').submit(function () {
// Cache the object that "this" is bound to because
// in the success function, the invocation context
// changes and "this" won't point to the same object
// it does now.
var theForm = this;
$.ajax({
url: $(this).data('url'),
type: 'POST',
data: $(this).serialize(),
success: function (data) {
if (data !== "0") {
window.location.href = data;
} else {
//Just use the JQuery parent() method with the cached object
$(theForm).parent().attr('id')
}
},
error: function () {
alert("No idea what went wrong");
}
});
return false;
});
});

Related

validating ajax data values

Is it possible to validate if there empty input?
I want to check if data has gotten values from html. If true then should disable button. If not then don't disable button.
This the sample html
<!DOCTYPE html>
<html>
<head>
<title>Untitled Document</title>
</head>
<body>
<form method="post">
<label>email
<input type="text" name="email" />
</label>
</form>
</body>
</html>
thats the sample html
<script>
$(document).ready(function () {
$("#Submit").click(function(event) {
Execute();
});
function Execute(){
$.ajax({
type: 'POST',
url: 'test.php',
data: { 'email': $("input[name='email']").val() },
success: function(res) {
if (data) {
$("#Submit").attr("disabled", true);
$('#success').text(res.response);
} if (!data) {
$("#Submit").attr("disabled", false);
$('#error').text(res.error_msg);
} else { // do nothing }
},
error: function(resp) {
alert("failed");
}
});
};
});
</script>
U can validate the values before triggering an ajax request. As u can serialize your form data and then validate your required values for the request and if they validate then trigger the ajax call with required data
function Execute(){
// Contains all the inputs that are present in your form
var formData = $('form').serializeArray();
// Validate your values
// If values does not matches your requirements, return false with error like
alert('All required values not filled');return false;
// If code reaches here, means you have all your required values.
// So, making ajax request makes more sense now as it can be executed successfully as values are first validated then ajax is triggered
$.ajax({
// Your code for ajax request
})
}
Try this one. I just modified your code. Hope it helps you out. Basically ajax call is not called untill you validate youe values and once you validated your values you can proceed with ajax and handling your button state using ajax lifecycle functions ( I don't know the exact term for these (beforeSend, complete, success etc) ) :)
LOL it was more easy like this
i got fixed D:)
only Before send was the solution
<script>
$(document).ready(function () {
$("#Submit").click(function(event) {
Execute();
});
function Execute(){
$.ajax({
type: 'POST',
url: 'test.php',
data: { 'email': $("input[name='email']").val() },
beforeSend: function(){
if ($("form input[name='email']").val() == "") {
alert("Text-field is empty.");
return false;
}
},
success: function(response) {
$("#Submit").attr("disabled", true);
$('#resp').text(response.feedback);
},
error: function() {
alert("failed");
}
});
};
});
</script>

Uncaught TypeError is not a function

I have a form that I'm trying to submit via ajax and I'm having some issues that I don't understand.
So I have the following function defined at the top of my main.js:
function formSubmit() {
var valid = true;
$(this).find('input, select, textarea').each(function(index, el) {
if(valid)
{
if($(el).is(':hidden'))
{
$(el).removeAttr('required');
}
if(!el.checkValidity())
{
valid = false;
//el.focus();
}
}
});
if (!valid)
return; // not ready to submit
var options = {
url: document.location.origin + 'update.php',
type: 'post',
dataType: 'json',
beforeSubmit: showRequest, // pre-submit callback
success: showResponse, // post-submit callback
error: showError // post-submit callback
};
// bind form using 'ajaxForm'
$(this).ajaxSubmit(options);
};
Later in my main.js I have the following line that is run when I click a button:
$('#contact-form').formSubmit();
Also in my main.js I have:
$('body').on('change', '#contact-form', formSubmit);
In my HTML:
<form name="contact" id="contact-form">
<input type="text" name="name" value="" required>
<input type="hidden" name="page" value="contact">
</form>
When I run the $('#contact-form').formSubmit(); line, I get the error:
Uncaught TypeError: $(...).formSubmit is not a function
However, when I simply edit the name field (triggering the "on change" line) it updates and runs the function just fine.
What am I missing?
EDIT: It looks like the outcome I'm looking for is not apparent, probably because I'm not super familiar with javascript.
What I was trying to do was have a button that ran the formSubmit() function such that the $(this) element in that function was the form element.
I thought I could just run $('#contact-form').formSubmit() to do that but apparently not?
How would I go about running the formSubmit() function such that $(this) in that function refers to the element with an id of '#contact-form'?
Replace
$('#contact-form').formSubmit();
With
$('#contact-form').submit();
https://api.jquery.com/submit/
Try on submit.
$('#contact-form').submit(function(){
}
Since you are using jQuery, try something like this:
+function ($) {
$.fn.formSubmit = function() {
var valid = true;
$(this).find('input, select, textarea').each(function(index, el) {
if(valid)
{
if($(el).is(':hidden'))
{
$(el).removeAttr('required');
}
if(!el.checkValidity())
{
valid = false;
//el.focus();
}
}
});
if (!valid)
return this; // not ready to submit
var options = {
url: document.location.origin + 'update.php',
type: 'post',
dataType: 'json',
beforeSubmit: showRequest, // pre-submit callback
success: showResponse, // post-submit callback
error: showError // post-submit callback
};
// bind form using 'ajaxForm'
$(this).ajaxSubmit(options);
return this;
}
}(jQuery);
That way, you should be able to use it like this: $("#contact-form").formSubmit();

Inject a form with Ajax, get its input value

Main page div is updated with an Ajax request. The updated html contains a form with input fields, a button, and another Ajax script to submit that form. While it is possible to initiate the second script by pressing the button in the injected form, the script does not seem to find form inputs by id.
I read about the .on() method of JQuery, but it only seems to provide access to dynamically updated functions, not elements.
How do I get the input element by ID, after this element got injected into the code with an Ajax request?
Main page:
<div id="output"></div>
<span id="call_account">Account</span>
$("#call_account").click(function(){
$.get('/accounts/login/', {}, function(data){
$('#output').html(data);
});
});
Injected into #output html:
<input id="id_username" name="username" type="text">
<input id="id_password" name="password" type="password">
<span id="account_submit">Submit</span>
$("#account_submit").on("click", function() {
var id_username = $('#id_username').val();
var id_password = $('#id_password').val();
$.ajax({
type:"POST",
url:"/accounts/login/",
data: {
'username': id_username,
'password': id_password,
},
success: function(data){
$('#output').html(data);
}
});
});
});
id_username and id_password are undefined when I try to submit the form.
edit:
Thanks to answers from the guys below I was able to get it to work. I also made a jsfiddle simulation of the problem in the process: https://jsfiddle.net/hn1Lrkzs/
Hope it helps someone in the future, I had trouble finding a direct answer, and lacked understanding to get the thing from help files.
Enclose your js inside document.body
<script>
$(document.body).on("click", "#account_submit", function() {
var id_username = $('#id_username').val();
var id_password = $('#id_password').val();
$.ajax({
type:"POST",
url:"/accounts/login/",
data: {
'username': id_username,
'password': id_password,
},
success: function(data){
$('#output').html(data);
}
});
});
</script>
Try to delegate the event to the document:
$(document).on("click", "#account_submit", function() {
var id_username = $('#id_username').val();
var id_password = $('#id_password').val();
$.ajax({
type: "POST",
url: "/accounts/login/",
data: {
'username': id_username,
'password': id_password,
},
success: function (data) {
$('#output').html(data);
}
});
});
Example:
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script>
$(document).on("click", "#account_submit", function() {
console.log('delegated event: works');
});
$("#account_submit").on("click", function() {
console.log('direct event: works');
});
</script>
<input id="id_username" name="username" type="text">
<input id="id_password" name="password" type="password">
<span id="account_submit">Submit</span>

How to show php passed results to ajax without refreshing

I want to do is when a user type an email to the inputbox ajax will pass the value automatically to php.
My problem is the result only show if I try to refresh the page
html:
<input type="text" id="email" name="email" />
script:
$(document).ready(function(){
var countTimerEmailName = setInterval(
function ()
{
emailName();
}, 500);
var data = {};
data.email = $('#email').val();
function emailName(){
$.ajax({
type: "POST",
url:"Oppa/view/emailName.php",
data: data,
cache: false,
dataType:"JSON",
success: function (result) {
$("#imageLink").val(result.user_image);
$("#profileImage").attr('src', result.user_image);
$("#emailNameResult").html(result.user_lname);
$("#emailCodeResult").val(result.user_code);
}
});
};
});
You can try with:
Because you dont need declare function in ready() and you need yo get the email value after any change. Now you only get the value when the page is ready.
function emailName( email ){
$.ajax({
type: "POST",
url:"Oppa/view/emailName.php",
data: 'email=,+email,
cache: false,
dataType:"JSON",
success: function (result) {
$("#imageLink").val(result.user_image);
$("#profileImage").attr('src', result.user_image);
$("#emailNameResult").html(result.user_lname);
$("#emailCodeResult").val(result.user_code);
}
});
};
$(document).ready(function(){
$('#email').change(function(e) {
emailName( this.val());
});
});
You're handling it wrong. jQuery has particular events to do these things.
Take this for example:
$(document).ready(function(){
$(document).on('keyup', '#email', function(e) {
e.preventDefault();
val = $(this).val();
console.log("Value: " + val);
});
});
It will look what is in the below input field as the user types. (which is what I presume you're trying to do?)
<input type="text" id="email" name="email" />
Example
You could simply remove that console.log() and replace it with your ajax request. (The above example will run as the user types.)
Alternatively you could use change() like this:
$(document).ready(function(){
$(document).on('change', '#email', function(e) {
e.preventDefault();
val = $(this).val();
console.log("Value: " + val);
});
});
Which will run after the value of the text box has changed. (When the user clicks out of the text box or moves somewhere else on the page.)
Example

Javascript only working when placed below HTML

I couldn't find a solution for the following problem I'm having. I'm using some javascript code to make my (live) search work (via ajax). The problem is that the Javascript only works when I place it below the HTML:
<form action="filter.php" name="filter" method="get" id="filter">
<input type="text" id="search_bar" name="s" placeholder="Type hier je zoekterm..." />
</form>
<ul id="result"></ul>
Javascript
$("#filter").submit(function(event) {
event.preventDefault();
$("#result").html('');
var values = $(this).serialize();
$.ajax({
url: "tracks_content.php",
type: "get",
data: values,
success: function(data){
$('#result').html(data);
},
});
});
$(this).mouseup(function() {
document.getElementById('result').style.display='none';
});
$("#result").mouseup(function(){
return false;
});
$("#filter").bind('input',(function(event){
var query = document.getElementById('search_bar').value;
if(query!=""){
$("#filter").submit();
document.getElementById('result').style.display='block';
}
else{
$('#result').html('');
document.getElementById('result').style.display='none';
}
}));
How can I make it work when putting the Javascript in front of the HTML?
This is because you are referring to HTML that doesn't exist yet when the JavaScript is on top.
Wrap your code in $( document ).ready(). Thi smakes the browser wait until the DOM is loaded before firing the JavScript.
$( document ).ready(function() {
$("#filter").submit(function(event) {
event.preventDefault();
$("#result").html('');
var values = $(this).serialize();
$.ajax({
url: "tracks_content.php",
type: "get",
data: values,
success: function(data){
$('#result').html(data);
},
});
});
$(this).mouseup(function() {
document.getElementById('result').style.display='none';
});
$("#result").mouseup(function(){
return false;
});
$("#filter").bind('input',(function(event){
var query = document.getElementById('search_bar').value;
if(query!=""){
$("#filter").submit();
document.getElementById('result').style.display='block';
}
else{
$('#result').html('');
document.getElementById('result').style.display='none';
}
}));
});
FYI, why are you uisng document.getElementById() when you have jQuery available to you and are already using it?
If you put that before the HTML, then you are trying to add a submit event to a form which doesn't exist at the time the JavaScript runs.
Wrap the script in a function, then use that function as an event handler for the ready or load event.
Passing a function (instead of a selector, DOM element or strong of HTML) as the argument to jQuery will bind as the ready handler.
jQuery(bind_form_event_handler);
function bind_form_event_handler() {
$("#filter").submit(function(event) {
// etc etc
}
Change you javascript to this
wrap with $(function(){}
like this
$(function(){
$("#filter").submit(function(event) {
event.preventDefault();
$("#result").html('');
var values = $(this).serialize();
$.ajax({
url: "tracks_content.php",
type: "get",
data: values,
success: function(data){
$('#result').html(data);
},
});
});
$(this).mouseup(function() {
document.getElementById('result').style.display='none';
});
$("#result").mouseup(function(){
return false;
});
$("#filter").bind('input',(function(event){
var query = document.getElementById('search_bar').value;
if(query!=""){
$("#filter").submit();
document.getElementById('result').style.display='block';
}
else{
$('#result').html('');
document.getElementById('result').style.display='none';
}
}));
})

Categories