I'm sending form to server and when I receive it back I need to access its elements
Here goes code.
some html
<here is the form>
<div style='border-style:solid' id='user_pic_n_1'></div>
and javascript
pic_type=($(this).attr('pic_type'));
pic_number=($(this).attr('pic_number'));
explanation : pic_type gets > user_pic and pic_number gets > 1
so the form is user_pic_form_n_1
$('#'+pic_type+'_form_n_'+pic_number).ajaxSubmit({
success: function(responseimage)
{
$('#'+pic_type+'_n_'+pic_number).html(responseimage);
now when the form gets into div, I need to get it's inputs values.
please write code sample of how can I Access it
In my example i'm trying to get values by alert like this but probably I write with mistakes
alert($(\"#'+pic_type+'_form_n_'+pic_number+' input[name=error]\").val());
elements name is 'error' so I'm trying to get it from the form.
UPDATE
Here is HTML form which I get from AJAX
<form id='user_pic_form_n_1' name='user_pic_form_n_1' action='/serv/pic_processor.php' method='POST'>
<input type='hidden' name='error' value='456'/>
</form>
So when it gets from server into responseimage variable, I put that into Div and then I want to access this form and alert value of tag named 'error'
You can pass the element contain the response html as a context along with selector.
selectorElem = '#'+pic_type+'_n_'+pic_number;
$(selectorElem).html(responseimage);
$('form[name=A] #B', $(selectorElem))
Edit, based on comments
Live demo
Html
<form id='user_pic_form_n_1' name='user_pic_form_n_1' action='/serv/pic_processor.php' method='POST'>
<input type='hidden' name='error' value='456'/>
</form>
Javascript
pic_type = 'user_pic';
pic_number= '1';
selectorElem = pic_type+'_form_n_'+pic_number;
selectorElem = 'form[name='+selectorElem +'] :hidden[name=error]';
alert($(selectorElem).val());
After you have done this:
$('#'+pic_type+'_n_'+pic_number).html(responseimage);
and you are looking for val of #b inside form with class a, it would be as:
$('#'+pic_type+'_n_'+pic_number+ ' form.a #b').val()
Related
Have a Java based web application with a page where a feed of posts is dynamically generated with the help of JSTL. The user can currently 'like' any post in the feed but this has proved much more difficult to implement using AJAX. I know i'm really close here but can't quite figure out what's wrong.
It works but only for the first item in the array.. So any like button that is pressed in the feed, only updates the first like button in the feed. Why is it that the dynamically assigned div value (input name=likesDivCount) only registers the first assignment?
index.jsp
<c:forEach items="${idFeedArray}" var="posts" varStatus="count">
...feed item (such as image, text etc..)...
<form id="likesform" action="../AddLike" method="post" style="display:inline;">
// the value of this input below is supposed to change...(i.e. #likesSize0,#likesSize1,#likesSize2)
<input name="likesDivCount" value="#likesSize${count.index}" type="hidden">
<input name="postUser" value="${userpost[count.index]}" type="hidden">
// this button sends the AJAX request
<button style="padding-right: 0;" type="submit" class="btn btn-link"><span class="glyphicon glyphicon-thumbs-up"></span></button>
</form>
// The span in the button below updates with the response from the AJAX
<button style="padding-left: 0;" class="btn btn-link"><span id="likesSize${count.index}">${likesArraySize[count.index]}</span></button>
</c:forEach>
<script>
$(document).on("submit", "#likesform", function(event) {
var $form = $(this);
var likesDivCount = $("input[name=likesDivCount]").val();
//this alert below is for testing, everytime the like button is pressed it displays '#likesSize0' and i need it to spit #likesSize1,#likesSize2,#likesSize3 etc...
alert(likesDivCount);
$.post($form.attr("action"), $form.serialize(), function(response) {
// only updates the first item :( (#likesSize0)
$(likesDivCount).text(response);
});
event.preventDefault(); // Important! Prevents submitting the form.
});
</script>
Looks like you have multiple forms with the same ID: '#likesform'. This is because your forms are generated in a loop.
I suggest you to remove the ID, replace it with a css class (or something else) and rewrite the JS to search for elements inside the target form, e.g.:
var $form = $(this);
var likesDivCount = $form.find("input[name=likesDivCount]").val();
Once you have valid html it will be easier to troubleshoot
I have a popup modal that displays on page load that has the following form in it:
<form class="enterForm">
<label class="modalFields" id="userName" style="display: none;">
<span>user Number :</span>
<input type="text" name="userNum" placeholder="User Number" required/>
</label>
</form>
<label>
<span> </span>
<input type="submit" value="Submit" class="submitButton">
<input type="hidden" id="hiddenInput">
</label>
And on user submission of the form, I want to hit a certain API via an AJAX call, which returns a JSON that looks like:
{
"results":[
{
"person":{
"firstName":"John",
"lastName":"Smith"
},
"userNumber":"12345"
}
]
}
If the userNumber matches the value that the user submitted, I then want to update the nav bar to say the person's first name. In terms of process flow I want it to go: user types in user number -> submits form -> AJAX call hits API -> checks to see if user input matches userNumber value in JSON --> if match, selects the firstName value and updates it in the nav bar. How could I go about achieving this?
Considering you know how to do AJAX calls and you're using an API, integrating jQuery to facilitate the thing shouldn't be too hard (if it is, I included additional information after the solution).
Solution
JavaScript
//On form submit
$('#enterForm').submit(function(){
var userNum = $('[name="userNum"]').val();
//AJAX call to your API
$.ajax({
url: 'myAPICall.php',
/* data: {userNumber: userNum}, //If necessary */
success: function(data) {
// Note: this code is only executed when the AJAX call is successful.
if(data.results.userNumber == userNum){
$('#navBarFirstName').text(data.results.person.firstName);
}
},
error: function (err) {
//If the AJAX call fails, this will be executed.
console.error(err);
}
dataType: 'JSON'
});
return false; //Prevents the page refresh if an action is already set on the form.
});
Explanation
You use jQuery to bind a function (event listener) to the submit event of your form.
When the submit event is triggered, the function runs:
It gets the value of your DOMElement with the name attribute "userNum"
It makes an AJAX call to your API (with/without the userNum value, you choose if you want to check that on the server side or not)
On success, (when the call is done successfully), it updates the navbar content using .text() with the firstName attribute of your JSON response.
Including jQuery
You can integrate jQuery by including the script within your HTML page. You can either download it or use a CDN:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js">
/* Don't put your code in here it won't be parsed */
</script>
<!-- the following tag could also be <script src="link/to/your/script.js"></script> -->
<script>
/* Your actual script */
</script>
Make sure to put this line before your actual javascript file containing the script written above, otherwise jQuery won't be initialized and the script won't work.
I am having an issue with this login system, when ever I click the log in button, or the sign up button it re-directs me to a white page with writing on it, That being said it is interfering with my log in action.
Here is the code that I think is causing the issue,
<form method="POST" action="" accept-charset="UTF-8">
on line 16 of the HTML code, I tried to take that code out and it stopped the re-directing but the text boxes went out of place, and the white background/background-box was not there either,
Link, HERE
You want to use preventDefault() if this is a purely Javascript: you should be able to pass the button press event into the listener when you create it:
$('.login').on('click', function(e) {
e.preventDefault();
// Will be executed on press
}
<form method="POST" class="login" accept-charset="UTF-8">
If there's no JS involved in this scenario, then you want to get rid of the action parameter entirely – leaving it as the empty string will still cause it to redirect in some cases.
As Jonathan Lonowski explained above, when the log in / sign up button is clicked, the form will post the data to the page mentioned in the action= attribute. Since this attribute is empty in your form tags, it will re-load the same page, posting the data to itself.
The data will arrive in key=value variable pairs. The variable value will be the contents of the field, the variable name will be the value of the name="" attribute on the element.
For e.g., for this field:
<input id="fname" name="first" value="Bobby" />
The data will be received like this:
$fn = $_POST['first']; //value is Bobby, or whatever user enters
On your page containing the form, add a section at the top like this:
<?php
if (isset($_POST['fname']) == true){
$fn = $_POST['fname'];
echo "Received First Name: " . $fn;
die();
}else{
?>
//Your current page, in its entirety, goes here
<?php
} //close the PHP if statement
?>
That is how you deal with a normal HTML <form> construct.
However, if you wish to use AJAX to communicate with a PHP file without changing the page, then:
(1) There is no need to use a <form> construct, just use a DIV with an input button: <input type="button" id="sub_btn" value="Submit" />
(2) Trap the button press using standard js/jQuery:
$('sub_btn').click(function(){
var fn = $('#first').val();
//etc.
$.ajax(function(){
type: 'post',
url: 'my_php_processing_file.php',
data: 'fname=' +fn+ '&lname=' etc
});
});
In your PHP processor file, the data will be received thus:
<?php
$fn = $_POST['fname'];
$ln = $_POST['lname'];
//Do your MySQL lookup here...
echo 'Received ' .$fn. ' ' .$ln;
(3) IF you do use the form construct, you can still do everything as above, but you will need to suppress the default form action of navigating to the page specified in the action= attribute (an attribute setting of action="" will post data to and reload the same page you are on).
To suppress navigating to the page specified in action= (involves page refresh, even if just action=""), use event.preventDefault(), as follows:
$('#buttonID').click(function(event){
event.preventDefault();
//remainder of button click code goes here
});
I have a form coded like below. Basically the href value for the anchor tag is determined by the value selected in a dropdown.
<form name=xyz method=post>
//random stuff
<a href="#" onclick="setAnchor()">
//some image
</a>
</form>
I am setting the href property of the form in javascript like this:
if(dropdown.option selected = "x")
windows.location.href = some URL;
else
windows.location.href = another URL;
The problem I am having is that using windows.location causes the form to use the GET method. The code expects a POST method to continue.
How can I fix this? I am not married to the above method. Any way I can set the form action URL, based on the option selected by the user, would work for me.
If you have this form:
<form id="myForm" action="page.php" method="POST">
You can submit it (with a POST method) (that is, instead of window.location...) like so:
document.getElementById("myForm").submit();
You can also set the URL to be submited like this
document.getElementById("myForm").action = "page.php";
You should submit your form:
document.xyz.submit();
document.xyz.action=page1.php; (or page2.php based on dropdown selection)
document.xyz.submit();
I'm currently working on a problem that basically involves processing all data in a form, saving it, and replacing the entire form with a text link. My primary goal is to convert a form, with some data using the POST method, and a submit button, into a standard text link that can then take the saved/serialized data and POST it to the server as if it were the original form; and when JS is disabled, the standard form and submit button is presented, i.e. a graceful degradation. I'm currently using jQuery, I know it's possible to process form data by serializing it, but I'm not sure how to go about removing or hiding (whichever one is possible) a form completely so it doesn't interfere with the layout of surrounding HTML element.
In summary:
-Is it possible to remove or hide an entire form field with jQuery?
-When jQuery serializes form data, where is it saved to?
-Can that saved data be referenced by a text link (i.e. Submit") somehow and POSTed as if it were a standard form?
Thank you.
UPDATE: Ok, I implemented Franz's code in a separate JS file I call from my test.html page. The content of the JS file is as follows:
$(document).ready(function() {
//Store form data before removing
var tempStorage = $('.postLink').serialize();
// Remove form:
$('.postLink').remove();
//Assign onClick event to anchor tag
$('.submit').click(function(){
$.ajax({
//aspx page
url:"doSomethingImportant/10",
//Using POST method
type: "POST",
//The data object
data: tempStorage,
//No caching
cache: false,
//Alert on success
success: function(html) {
alert('great');
}
});
});
});
The only difference here is I'm using the class attribute as an identifier for the forms I want removed as opposed to id. Again, this is what I'm tasked with, not by choice. For some reason, however, it doesn't make it to the alert message, i.e. it doesn't work. Below is the snippet of html I'm having the script act on:
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<style type="text/css">
h1.intro {color:blue;}
p.important {color:green;}
h2.outro {color:DarkGreen;}
</style>
<script type="text/javascript" src="jQuery/jquery-1.3.2.js"></script>
<script type="text/javascript" src="Form2Link.js"></script>
<title>Form Remover demo</title>
</head>
<body>
<h1 class="intro">Hello World!!</h1>
<p>How's it going??</p>
my First Link
<form id = "myForm" name="myForm" action="doSomethingImportant/10" class="postLink" method="post">
<input type="submit" id="submitThis" name="submitThis" value="clickThisLink"></input>
<input type="hidden" id="antiCSRF" name="antiCSRF" value="12345"></input>
</form>
<a class="submit" href="">Submit Link</a>
my Second Link
my Third Link
<br>
<br>
<form action="doSomethingImportant/10" method="post">
<input type="submit" id="submitThis" value="clickThisLink"></input>
<input type="hidden" value="12345" name="antiCSRF"></input>
</form>
<form action="doSomethingImportant/11" method="post">
<input type="submit" value="clickThisLink"></input>
<input type="hidden" value="12345" name="antiCSRF"></input>
</form>
<h2 class="outro">That's nice, gotta go.</h2>
</body>
</html>
UPDATE 11/10/09:
Ok, I've found an alternate way of going about this problem by hiding the form and adding an anchor tag immediately after the form. I then attach a click operation to the anchor that acts on the submit button in the hidden form. My problem now is that this only works with one form defined in the DOM, I want to come up with a generalization of this function so that it works with several forms. How can I traverse each form and replace it with its own unique link?
Code for my current script:
/**
* Hide forms on page load.
* Call submit button within a form from a link
*/
$(document).ready(function() {
//Hide form:
$('.postLink').hide();
//Append a anchor tag after each form that is replaced
$('.postLink').after("<a class=\"submitLink\" href=\"#\">Submit Link</a>");
//Submit button in hidden form
$('.submitLink').click(function(){
$('#myForm').find('input#submitThis').click();
return false;
});
});
Part 1 is easy:
$('#yourform').hide();
EDIT: (to the best of my understanding - using ScottE's step-by-step idea)
Part 2:
Save the form in a local variable:
var tempStorage = $('#yourform').serialize();
Part 3:
Assign a function to the onClick event of your link that sends the data via an AJAX request:
$('#yourbutton').click( function() {
$.ajax({
// Your PHP processing script goes here
url: "yourfile.php",
// You wanted to use POST, right?
type: "POST",
// The data object (I hope, it's accessible here)
data: tempStorage,
// We don't need caching
cache: false,
// A function that gets executed on success
// Note that you have the response of the script in the html variable
success: function(html) {
alert('great');
}
});
});
If I understand what you're looking for, you could do the following:
handle the submit event of the form.
store the form data in a local variable in js - look to http://docs.jquery.com/Ajax/serialize
hide the form
show the link that will submit the form (again), and handle it's click event, initiating an ajax call where you pass in the local variable created in step 2.
This seems like an odd request...
Ok all, I went the route of hiding all my forms and appending anchor tags following each form based with class="postLink", I added a conditional statement that adds a unique ID if a form doesn't already have one, the script then adds an anchor tag with the unique ID and the value of the submit button to the end of the hidden form. A separate click function the processes the submit button in the hidden form that is tied to an anchor tag by the unique ID. Code follows:
/**
* Hide all forms with class="postLink" on page load.
* Call submit button within a form from an anchor tag
*/
$(document).ready(function() {
//Hide form(All forms with class="postLink" will be hidden):
$('.postLink').hide();
var num = 0;
//Loop over each form with a postLink class
$("form").each(function(){
//Add value of submit button as name of text link
if($(this).hasClass("postLink")){
//Get value attribute from submit button
var name = $(this).find('input#submitThis').val();
//Add a uniqueID if the form has no id
if($(this.id).length == 1){
this.id='uniqueID'+num;
num++;
}
var id = $(this).attr('id');
//Append a anchor tag after each form that is replaced
$(this).after("<a id="+id+" class=\"submitLink\" href=\"#\">"+name+"\</a>");
}
});
//Submit button in hidden form by clicking associated anchor tag
$('.submitLink').click(function(){
var anchorID = $(this).attr('id');
//Find the form id that matches the anchor id
$("form").each(function(){
if(this.id == anchorID){
$(this).find('input#submitThis').click();
}
});
return false;
});
});