How to find a sibling element's value using jQuery upon click - javascript

I'm trying to find the value of the userid and password in the below HTML using the following jQuery code, but it doesn't return any value. What am I doing wrong?
<div id='mainpane'>
<form id='login' method='post' action='#'>
<p>User Id:<input id='userid' type='text' name='userid'></input></p>
<p>Password:<input id='password' type='text' name='password'></input></p>
<p><input id='submit' type='submit' name='Submit' value='Submit'></input></p>
</form>
<div id="message"></div>
<p>Not a member? Signup</p>
</div>
Here's the jQuery code:
$(document).ready(function() {
$('#login').delegate('input#submit','click',function(){
alert('user id is: '+$(this).parent().parent().find('#userid').html());
var request = $.ajax({
type:"POST",
url:"/login",
data: {userid:$('#userid').text(), password:$('#password').text}
});
});
The alert comes back with an empty data. Appreciate any pointers on what am I doing wrong.
Thanks, Kalyan.

use .val() to retrieve an input's value.
var userid = $("#userid").val();
var pass = $("#password").val();

Just do:
$.post('/login', $('#login').serialize(), function() {});
in place of your $.ajax call :), the .serialize() takes all the form inputs' values and pass them to the server, encoded for you as well :)

You have quite a few issues so here's the corrected code with notes:
jQuery
$(function() {
// same as document.ready
$('#login').submit(function(event){
// runs whenever the form is submitted - either enter or submit button is clicked
event.PreventDefault();
// since the form is submitted via ajax you wil want to keep the page from changing
alert('user id is: '+$('#userid').val());
// no need to reach back through the DOM with .parent() use the ID its the fastest, also you get input values with .val()
$.ajax({
type:"POST",
url:"/login",
data: $('#login').serialize()
// serialize() creates an object of all the form data based on the name attribute and values - very clean
});
});
});
HTML
<div id='mainpane'>
<form id='login' method='post' action=''>
<p>User Id:<input id='userid' type='text' name='userid'/></p>
<p>Password:<input id='password' type='text' name='password'/></p>
<p><input id='submit' type='submit' name='Submit' value='Submit'/></p>
</form>
<div id="message"></div>
<p>Not a member? Signup</p>
</div>
Inputs are self closing.

you try this code
$(document).ready(function() {
$('#login').delegate('input#submit','click',function(){
alert('user id is: '+$(this).parent().parent().find('#userid').val());
var request = $.ajax({
type:"POST",
url:"/login",
data: {userid:$('#userid').val(), password:$('#password').val()}
});
});
});

Related

php $POST[] empty after Ajax call from jquery

Form :
<form method="post" id="loginForm">
<div class="form-group">
<label for="email-signin">Email address:</label>
<input type="email" class="form-control" id="email-signin" name="email-signin">
</div>
<div class="form-group">
<label for="pwd-signin">Password:</label>
<input type="password" class="form-control" id="pwd-signin" name="pwd-signin">
</div>
<div class="checkbox">
<label>
<input type="checkbox"> Remember me</label>
</div>
<button type="submit" class="btn btn-default" id="signIn" name="signIn">Sign In</button>
<div id="error">
<!-- error will be shown here ! -->
</div>
</form>
jquery :
$("#signIn").on("click", function(e) {
e.preventDefault();
var values = $("#loginForm").serialize();
console.log( values );
$.ajax({
type: "POST",
url: "../php/BusinessLayer/User.php",
data: values,
beforeSend: function() { $("#error").fadeOut() },
success : function(response)
{
console.log("Success");
if(response=="ok"){
}
else{
$("#error").fadeIn(1000, function(){
$("#error").html('<div class="alert alert-danger"> <span class="glyphicon glyphicon-info-sign"></span> '+response+' !</div>');
});
}
}
});
php:
<?php
session_start();
include ("../DataLayer/VO/UserVO.php");
include ("../DataLayer/DAO/UserDAO.php");
// Database Execution for User Related Request
$userDAO = new UserDAO();
print_r($_POST);
if(isset($_POST['signIn']))
{
echo 'test2';
$user = new UserVO();
$user->setEmail(trim($_POST['email-signin']));
$user->setPassword(trim($_POST['pwd-signin']));
// Request signin
$userDAO->signIn($user);
}
Using this code, my if(isset($_REQUEST['signIn'])) in my php file never returns true. I have tried multiple things, and nothing seems to work.
PS : I am using Jquery 1.12.4
Also, my print_r($_POST); returns an empty Array.
jQuery's serialize function does not encode the values of buttons. Taken from here
NOTE: This answer was originally posted by slashingweapon
jQuery's serialize() is pretty explicit about NOT encoding buttons or submit inputs, because they aren't considered to be "successful controls". This is because the serialize() method has no way of knowing what button (if any!) was clicked.
I managed to get around the problem by catching the button click, serializing the form, and then tacking on the encoded name and value of the clicked button to the result.
$("button.positive").click(function (evt) {
evt.preventDefault();
var button = $(evt.target);
var result = button.parents('form').serialize()
+ '&'
+ encodeURIComponent(button.attr('name'))
+ '='
+ encodeURIComponent(button.attr('value'))
;
console.log(result);
});
As far as the var dump being empty on the PHP side, try using jQuery's .click instead of the .on event.
$('#signIn').click(function(){});
Also, remove the method from your form. It looks like the form may be submitting as soon as you click the button. Also, remove
e.preventDefault();
and place
return false;
at the VERY END of the on click function. return false does 3 things
e.preventDefault()
e.stopPropigation();
return immdediatly

jQuery ajax post data with javascript submit form

This is my code:
<html>
<body>
<?php
include('header.php');
?>
<div class="page_rank">
<form name="search" id="searchForm" method="post">
<span class="my_up_text">ENTER THE WEBSITE TO CHECK GOOGLE PAGE RANK:</span>
<br /><br />
<input type="text" name="my_site"/></form></div>
<div class="p_ity">
PAGE RANK</div>
<div id="my_pass"></div>
<script>
function sub_form()
{
document.forms["search"].submit();
}
$(function () {
$('form#searchForm').on('submit', function(e) {
$.ajax({
type: 'post',
url: 'check-google-page-rank.php',
data: $('form').serialize(),
success: function (data) {
$('#my_pass').html(data);
}
});
e.preventDefault();
});
});
</script>
</body>
</html>
The problem is the ajax post works perfect if I use a submit button in the form.It doesn't work if I use a sub_form() method to submit the form after on click event.My doubt is will the java script sub_form() method trigger the jquery ajax function or not?
Note:
The data returned by the post url is
echo "<img width=\"165\" height=\"55\" src=\"./images/page-rank/pr".$rank.".gif\" />"
document.forms[].property
This returns an array of all the forms in the current document.
Since it is a array, you should pass the index value as integer.
document.forms[0].submit();
this will submit the form, if you have this form as your first form in the html page from top.

Stop 2 Instances of an Ajax form on the same page interfering with each other

I've the following form twice on my homepage:
<form id="get-consultation-form" action="javascript:alert('success!');" >
<h3 class="sub-heading">Book a Consultation</h3>
<div id="message"></div>
<div id="fields">
<input type="text" maxlength="" name="Consultation[name]" placeholder="NAME" />
<input type="text" maxlength="" name="Consultation[number]" placeholder="NUMBER" />
<input type="text" maxlength="" name="Consultation[email]" placeholder="EMAIL" />
<button type="submit" class="btn">Submit</button>
</div>
</form>
The form uses jQuery/Ajax/PHP to forward the data via email:
$(document).ready(function() {
$("#get-consultation-form").submit(function() {
var str = $(this).serialize();
$.ajax({
type: "POST",
url: "http://novicecoder.co.uk/priestley/consultation-process.php",
data: str,
success: function(msg) {
$(document).ajaxComplete(function(event, request, settings) {
NProgress.set(0.0);
if (msg === 'OK') {
result = '<div class="thanks" id="thanks">Thank you, we will contact you <span>shortly.</span></div>';
$(this).find("#fields").hide();
NProgress.set(0.5);
$("#message").hide();
$("#message").html(result).slideDown(100);
$("#message").html(result);
}
else
{
result = msg;
$("#message").hide();
$("#message").html(result).slideDown(200);
$("#message").html(result);
}
NProgress.set(1.0);
});
}
});
return false;
});
});
The first form is working perfectly, however as you'll see in my working example, the 2nd is not:
My website
Any ideas why this is happening????
IDs are unique.
Try to change form elements to diferent ids.
Or instead use classes.
If you use classes you can use $('.messages-class').closest() inside the form submit() for only interact in the current form.
You can't have an element with the same ID on a page twice. Replace your #get-consultation-form ID with a class, that should solve your issue. This also applies to the elements within the form like #fields and #message.

Multiple show/hide forms in jquery

Hello I want to have list of files in directory and a form below each of them that allows my users to name them.
That's all clear - I made it in php, but now I want to have this list and hidden forms, and when I'm clicking on one of my file's name, the form shows under the clicked name.
Something like here: http://papermashup.com/demos/jquery-sliding-div/#
Here is the code: http://papermashup.com/simple-jquery-showhide-div/
But it works in a way, that when i click on one of files, all forms shows or all hides. How to fix it to work only for clicked file?
JSFIDDLE EXAMPLE: http://jsfiddle.net/qbNrR/
#UPDATE - SIMILAR PROBLEM
Hey, I've got similar problem with submitting ajax forms - using this tutorial: http://net.tutsplus.com/tutorials/javascript-ajax/submit-a-form-without-page-refresh-using-jquery/
my forms are in div id=#upform and when i'm trying to submit any of them via $.ajax it submits only the first one, here's the code:
<script>
$(function() {
$(".button").click(function() {
var txt = $(".tekst#test").val();
var dataString = 'tekst=' + tekscior;
$.ajax({
type: "POST",
url: "upload/base",
data: dataString,
success: function() {
$('#upform').html("<div id='message'></div>");
$('#message')
.html("<h2>described!</h2>")
.append("<p>thanks!</p>")
.hide()
.fadeIn(1500, function() {
$('#message')
.append("<img id='checkmark' src='http://artivia-dev2/i/check.png' />");
});
}
});
return false;
});
});​
</script>
AND Here are my forms:
// ONLY THIS ONE IS SUBMITTED, EVEN WHEN I'M SUBMITTING THE SECOND ONE!
<div class="slidingDiv">
<div id="upform">
<form name="contact" action="">
<input type="text" value="TESTFORM" class="tekst" id="test">
<input type="submit" name="submit" class="button" id="submit" value="Send" />
<form>
</div>
<div class="slidingDiv">
<div id="upform">
<form name="contact" action="">
<input type="text" value="TESTFORM" class="tekst" id="test">
<input type="submit" name="submit" class="button" id="submit" value="Send" />
<form>
</div>
You can use the next() jQuery method. Then your code will look something like:
$(document).ready(function() {
$(".slidingDiv").hide();
$(".show_hide").show();
$('.show_hide').click(function(e) {
$(e.target).next(".slidingDiv").slideToggle();
});
});​
Try event.currentTarget to get the form that triggered the click event
on click event use jquery like
$(this).show(); // or hide();
as in example
$('.show_hide').click(function(){
//$(".slidingDiv").slideToggle();
$(this).slideToggle();
});

Multi form submit in the page with ajaxform()

how to get the parent div id of current submit form with the ajaxform plugin
I am not having any problems with the success state
Thank you.
below is my code.
<script type="text/javascript" charset="utf-8">
$('.formsubmit').ajaxForm( {
beforeSubmit: function() {
// here want form parent div display loading..
var id = $(this).parent().id; // my problem here how to get current action form parent div id
$('div#'+id).html("Loading...");
},
url: '/post.php',
success: Response,
datatype: ($.browser.msie) ? "text" : "xml"
});
function Response(xml) {
// let say XML return is equal 1
var id = xml;
$('div#'+id).html("Success");
}
</script>
<html>
<body>
<div id="1">
<form class='formsubmit' action='/post.php' method='post'>
<input name='url' value='stackoverflow.com'>
</form>
</div>
<div id="2">
<form class='formsubmit' action='/post.php' method='post'>
<input name='url' value='jquery.com'>
</form>
</div>
<div id="3">
<form class='formsubmit' action='/post.php' method='post'>
<input name='url' value='google.com'>
</form>
</div>
</body>
</html>
From what I can see in the docs, beforeSubmit method is invoked with three params:
the form data in array format
the jQuery object for the form
the Options Object passed into ajaxForm/ajaxSubmit
Given that if you change your before submit to
beforeSubmit: function(formData, formObj, options) {
var id = formObj.parent().attr('id');
$('div#'+id).html("Loading...");
}
This should work although I haven't tested it.

Categories