I have recently just begun using JQuery and AJAX. I am practicing using JQuery to grab form values upon form submit and using AJAX to process the data with a PHP script. It all works really good, that is, until I add another form to the page. No matter what form I submit, the data from the first form on the page gets submitted. How can I select only the form and values from the form that is being submitted?
Here is my code:
<html>
<head>
<title> JQUERY and AJAX </title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<!-- JQUERY script to submit the form without page refresh !-->
<script>
$(document).ready(function() {
$("form").submit(function() {
var name = $("input#name").val();
var dataString = 'name='+ name;
$.ajax({
type: "POST",
url: "ajax_submit.php",
data: dataString,
});
$("input#name").val("");
return false;
});
});
</script>
</head>
<body>
<form name="form" action=""/>
<input type="text" name="name" id="name" autocomplete="off"/>
<input type="submit" name="submit" id="submit"/>
</form>
<form name="form" action=""/>
<input type="text" name="name" id="name" autocomplete="off"/>
<input type="submit" name="submit" id="submit"/>
</form>
</body>
</html>
Thanks!
Do you know how to use css selectors? You can use css selectors as jquery selectors. Meaning, if you give each form an id attribute, you can choose it later like this :
$('#the_forms_id').submit();
Where form id is an html attribute you chose for the form, like this
<form name="form" action="" id = "the_forms_id"/>
Just use php to set different form id's
Also, note you can use almost any css selector you can think of, and also jquery specific selectors. You can see them here.
If you don't know how to use basic selectors, use this guide.
If you want to choose a dynamically created form (like you commented),
implementation depends on which way the form is added and how it needs needs to be captured.
You can use php to give them different ids, dynamically (use a counter for example).
Also, you can use jquery selectors to choose the first or last element (or any other), when there are a few elements present. Check out the :last selector :
$('form :last').serialize().submit()
Related
I am trying to send a form to 2 different processors. One is a 3rd party cloud database that I do not control nor have the code for. The other my simple contact form processor. I was trying something like:
<form action="mail.php" method="POST">
<input name="name" type="text" />
<input type='submit' name='submit' onclick="this.form.action="//3rdpartcloud.com";" />
From what I understand this wont work because it leaves the page on the 1st action and cant do the 2nd action.
I have seen Ajax suggestions, but no clear example. But as I will be sending the same variables to both files, I was thinking it would be easier to POST all variables to my php form, and then from my php to automatically POST them to the 3rd party server. I do not know how they process the data so I want to send it as form values not as variables.
Is there a simpler way to achieve this? What is the correct syntax? I'm guessing something like this in the php:
<form action="site.com" method="POST">
<input name="name" value=$name>
But even if that works - how do I auto send it to an action url?
First sumit your form using ajax to your own site - then submit the form to the other site as usual.
Your Ajax - something look something like this:
<form id="form" action="theothersite.php" method="POST">
<input name="name" type="text" />
<input type='submit' id="submitbutton" />
</form>
<script type="text/javascript" >
$('#submitbutton').click(function(e){
e.preventDefault(); //stops form submission
$.ajax({
type: "POST",
url : '/yoursiteurl.php',
data: $('#form').serialize(),
success: function(data){
$('#form').submit(); //now submit the form
}
});
})
</script>
In your PHP do a:
print_r($_POST);
To see the submitted values
As opposed to Dropbox Chooser V2, V1 used a hidden input field making it easy for PHP to get POSTed data from form.
Using V2, however, the input fiels is gone. How do I get the POST data to further process it?
Basically two main options:
You could make an AJAX call and include the URL in there.
You can include a hidden input tag in your form and put the URL in there.
Rough example of the latter (completely untested, sorry for typos/bugs):
<form method="POST" action="...">
<input id="url" name="url" type="hidden" />
<div id="container"></div>
</form>
<script>
var button = Dropbox.createChooseButton({
linkType: 'direct',
success: function (files) {
document.getElementById('url').value = files[0].link;
}
});
document.getElementById('container').appendChild(button);
</script>
i have two submit button on my index page namely International and Domestic. i want that two different button to point to different pages namely int.php and dom.php when i click on the buttons. can you help me out. thank
while it is allowed only to define single action = "" for form element. but if i have to do that, i would do it this way.
<form action ="somepage.php" method="post">
<!--all your input elements-->
<input type="submit" name ="international" value="international"/>
<input type="submit" name ="domestic" value="domestic"/>
</form>
determine which button have been clicked and act accordingly.
if(isset($_POST['domestic']) {
//include dom.php
}
else if(isset($_POST['international']) {
//include int.php
}
and then you can include the necessary file.
or the other way is to go with AJAX/jQuery way
you can just use switch in php for differ or
use javascript
Do it with jquery! First, dont create submit buttons just create
<input type="button" />
Than give them an id like:
<input type="button" id="InternationalBTN" />
<input type="button" id="DomesticBTN" />
and with jquery bind the action
$(document).ready(function(){
$("#InternationalBTN").bind('click',function(){
$('#idOfYourForm').attr('action','setTheDestinationPageHere');
document.forms['nameOfYourForm'].submit();
});
});
That will not be possible since your form's action attribute can only point to one location at a time and both buttons are in the same form(but possible if you use AJAX).
If you wanted to use pure PHP (i.e. no Javascript involved), you'd have to write two different handlers for the different button clicks, like below:
if(isset($_POST["name_of_international_button"])){
//actions to perform for this --
}
if(isset($_POST["name_of_domestic_button"])){
//action to perform for this
}
In the actions part of each of the handlers, you could then do a redirect, with the URL containing the data to be processed either in the int.php or dom.php scripts
You can do it in this way:
In form tag please leave empty action action=""
2 buttons to send:
<input class="btnSend" type="submit" name="International" value="International" id="International"/>
<input class="btnSend" type="submit" name="Domestic" value="Domestic" id="Domestic"/>
and use ajax:
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<script>
$(document).ready(function(){
$('#International ').click(function() {
// send to file 1 using ajax
});
$('#Domestic').click(function() {
// send to file 2 using ajax
});
});
</script>
Here is how to send data using ajax:
http://net.tutsplus.com/tutorials/javascript-ajax/submit-a-form-without-page-refresh-using-jquery/
Your form action would have to contain some sort of conditional statement to redirect users based on which submit button is clicked
<form action="<?php if(isset($_POST['international'])){echo 'international.php';}else{echo 'domestic.php';}?>" method="post">
<input type="text" name="field1" />
<input type="text" name="field2"/>
<input type="submit" value="international "name="international"/>
<input type="submit" value="domestic "name="domestic"/>
</form>
Or you could set up your conditionals on a page specified by the form actionand have them redirect based on which button was clicked,
Just put a form tag, and set the action to the page. Then the submit button will navigate to that page where the action tag is pointing to...
Easy as that :D
I have a bunch of links with ID's 1 - n, and I want to pass that ID to a hidden input in my form (I have numerous links but want to only have one form rather than generating thousands of extra lines of HTML making a form for each ID).
The link looks like this:
Remove
The form with hidden input looks like this:
<form action="/php/removeSave.php" method="POST" id="removeSave">
<input type="hidden" name="ID" value=""/>
</form>
Any help?
This sets the value of the hidden input with the id ID to the id of the a element before it submits the form.
<a href='#' id='n' onclick='$("#ID").val(this.id);$("#removeSave").submit();'>Remove</a>
<form action="/php/removeSave.php" method="POST" id="removeSave">
<input type="hidden" name="ID" id="ID" value=""/>
</form>
You haven't provided the full context of the "Remove" link, wherein the ID would be noted, so I will presume a format, and you can adapt from there.
<!-- HTML //-->
<!-- Format for Each Element. "123" is the ID here //-->
<div id="element123">
This is Element 123 (ID#123)
Remove
</div>
<!-- The Form at the Bottom of the Page //-->
<form id="removeSave" method="POST" action="/php/removeSave.php">
<input type="hidden" name="ID" value="" />
</form>
The jQuery Segment
<script type="text/javascript">
$(document).ready(function(){
// Clicks of Links starting with "/php/removeSave.php?ID="
$('a[href^="/php/removeSave.php?ID="]').click(function(e){
// Don't let the Link act as a basic link
e.preventDefault();
// Get the Link HREF attribute
href = $(this).attr('href');
// Derive the Form ID and ID Value
bits = href.match(/^\/php\/([^\.]+)\.php\?ID=(\d+)/);
formID = bits[1];
elementID = bits[2];
// Set the Field Values and Submit the Form
$form = $('#'+formID);
$form.find('input[name="ID"]').val(elementID);
$form.submit();
});
});
</script>
Benefits of this method?
Graceful Degradation - so long as your PHP scripts can also handle GET variables, if this page is loaded from a browser which does not have Javascruipt enabled, or is unable to load jQuery, clicking on the "Remove" links will still perform the expected action.
Opportunity for AJAX-ification - instead of all those other actions inside the .click(function(e){ section, you could use jQuery's $.post() function and the query string segment of the link's HREF to pass this request straight to the handler and manipulate the page without having to do a full-page reload.
How do you use a value "submitted" by a form in javascript?
Facts:
It is a PHP document
I'm using JavaScript because I need some timing factors I don't think I can get from serverside-scripts :)
To simplify; what I want is, that when this form is submitted or a button is clicked:
<form method="POST" action="test.php">
<input type="text" name="foo" size="30">
<input type="submit" value="Click me"> //it doesn't have to be submitted
<input type="button" action="some_action" value="Click me"> //an alternative solution
</form>
the value of the text-input named "foo" is displayed elsewhere.
NOTE The form doesn't have to be submitted, what I realy want is, that when you press a button the value can be used elsewhere
Should I use GET instead? Can I just use the $_POST array? Should I use AJAX (which I am completely useless at)? I don't know what to do in this situation.
Since you mentioned that it does not depend fully upon whether the form is submitted or not, so it's more easier to catch the value w/o POSTing / GETing the form. After you have written your interface logic in the body section, you need to write the following code in the footer page at the end:-
anypage.php:-
<form method="POST" action="test.php">
<input type="text" name="foo" id="foo" size="30" />
<input type="submit" onclick="return writeFoo('foo_placeholder', 'foo');" value="Click me" /> //it doesn't have to be submitted
<input type="button" onclick="return writeFoo('foo_placeholder', 'foo');" action="some_action" value="Click me" /> //an alternative solution
</form>
The above code is your code only with some minor modifications, including calling a JS function "writeFoo()" on the "click" event of either a button / submit. This function takes 2 arguments:-
arg - It mentions the destination placeholder ID of the HTML element, in which the value is to be printed.
source - It mentions the source ID of the HTML element, from which the value is to be grabbed / taken.
rightpart.php:-
<div>
<span id="foo_placeholder"></span>
</div>
The above HTML code can be used for any panel, but must be included when the "anypage.php" page is to be shown to the user. This is because the placeholder element must be present when the "foo" element is being called. Be careful to use the same ID both in the "writeFoo()" function calling time & in this page.
footer.php:-
<script type="text/javascript"><!--
function writeFoo(arg, source) {
if(document.getElementById(arg) != null) {
document.getElementById(arg).innerHTML = document.getElementById(source).value;
}
}
// --></script>
And this page should contain the above JS code containing the definition of the "writeFoo()" function.
EDIT, as for #Latze:-
See you can include that "rightpart.php" page either in the same block of "anypage.php" page or in any block of any other page (like "header.php" / "footer.php" page). But the main logic is that both the source ID (from which the value is taken) & the target / placeholder ID (where the value is to be shown) must be present when you are viewing that particular page (in this case, it means when you are viewing the "anypage.php" page).
Hope it helps.
You can read the value from the $_POST or $_REQUEST array on the server side, and insert it into the output anywhere you like - even inside javascript, if you want to. Example:
<?php
$myValue = $_POST['foo'];
?>
<script type="text/javascript"><!--
function writeMyValue() { document.write('<?php echo $myValue; ?>'); }
// --></script>
PHP runs on the server. JavaScript runs on the browser. These two languages do not talk to each other; they don't even run at the same time, not to mention on the same machine. As soon as the user submits the form, the browser requests test.php from the server and the current page is gone forever, scripts and all.
It's really hard to figure out what you want to do exactly, so I'll provide you with some general hints:
JavaScript can intercept a form submission. You need to attach an onsubmit event handler to the <form> element. The function assigned to the event can do whatever it needs and then return true (and let the submission go on) or return false (and cancel the submission).
JavaScript can read and write almost any page element. You need to use the so called DOM methods.
PHP can generate whatever you need, including HTML input fields.
Example:
<?php
$foo_value = date('Y-m-d H:i:s');
?><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head><title></title>
<script type="text/javascript"><!--
window.onload = function(){
var documentForms = document.getElementsByTagName("form");
for(var i=0, len=documentForms.length; i<len; i++){
documentForms[i].onsubmit = function(e){
var currentForm = e.target;
var fooValue = currentForm.elements.foo.value;
var p = document.createElement("p");
p.appendChild(document.createTextNode("Aborted submission: " + fooValue));
currentForm.appendChild(p);
return false;
};
}
};
//--></script>
</head>
<body>
<form method="POST" action="test.php">
<input type="text" name="foo" value="<?php echo htmlspecialchars($foo_value) ?>" size="30">
<input type="submit" value="Tryk her">
</form>
</body>
</html>
Update
A little note about this:
documentForms[i].onsubmit = function(e){
};
When you assign an event handler, the spec requires that whenever the function gets called it will receive an event object as its first argument. That object represents the event that triggered the function call and it can be used to obtain additional information, such as the original DOM node that triggered the event. It doesn't matter how you call it inside your function; I use e because I never know how to name stuff :)