Passing a value to a hidden input with jQuery - php

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.

Related

Forcing form to go website.com/test/ instead of website.com?name=

So im trying to create a search for a name but when i click the sumbit button it goes to websitelink.com?=name=Nighel but i want it to go like this websitelink.com/Nighel/
Yes i'm already using htacces thats why the ?= doesnt work for me
I cant seem to figure out how to sort this out.
This is for searching based on name in my logs
What i use for grabbing the name
$name = isset($_GET['playername']) ? $_GET['playername'] : "";
<div class="ironman-nav">
<form>
<span class="ironman-nav__option">Search for username</span>
<input class="ironman-nav__option" type="text" name="playername" placeholder="Username..." autocomplete="off">
<input class="ironman-nav__option" type="submit" value="Submit">
</form>
</div>
You can solve this with javascript changing dynamically the form action attribute with the input value when a key is pressed over it or before submit the form.
The client side is not aware of your server rewrite rule
For the client test in website.com/test/ is just part of the URL, so if you want the browser to submit the form to website.com/test/ then set the action attribute of the form as website.com/test/
if you want the test part to be variable then you have to build the URL of the form dynamically. something like this
<div class="ironman-nav">
<form action="https://website.com/<?=$name?>">
<span>Search for username</span>
<input type="text" name="playername">
<input type="submit" value="Submit">
</form>
</div>
I'll break down my response into two parts, the first explaining the behavior of the original code, and the second will contain possible implementation routes.
HTML forms, by default, will take collate all the input tags (<input>, <textarea>, <select>, etc) as a dictionary, where the key is the node's name (the attribute) and the value is the node's value (also the attribute).
So in your case,
$name = isset($_GET['playername']) ? $_GET['playername'] : "";
<div class="ironman-nav">
<form>
<span class="ironman-nav__option">Search for username</span>
<input class="ironman-nav__option" type="text" name="playername" placeholder="Username..." autocomplete="off">
<input class="ironman-nav__option" type="submit" value="Submit">
</form>
</div>
Will do the following, on submit:
Create a dictionary containing the following key-value pairs: playername=VALUE_FROM_PLAYERNAME_INPUT
Make a GET request to the current page with the above parameters: GET /thispage?playername=VALUE_FROM_PLAYERNAME_INPUT
Since you wanted the request to go to /thispage/VALUE_FROM_PLAYERNAME_INPUT instead, you will need to modify the submission event handler for that form. Unfortuneatly it appears that Accountant م's won't worry for you since you don't have the target username at the time the search page is loaded (so the action attribute of the form tag cannot be pre-populated with the target user).
var searchForm = document.querySelector('.ironman-nav form');
searchForm.addEventListener('submit', function(evt) {
searchForm.action = '' + searchForm.querySelector('input[name="playername"]').value;
});
The reason I put an empty string in the search form action is in case you needed to prefix the action URL with anything. For example, if your search page and results page was called search.html, then searchForm.action = 'search.html' + searchForm.querySelector('input[name="playername"]').value;. You have to do this because it is a relative URL (action URL does not begin with a protocol or slash), and as such the browser will search for that resource starting from the parent of the current page.

How to not refresh page's previous field input values after press submit

I have an input like this:
<input value="<?php echo $formdata['title'] ?>" type="text" name="title" id="Editbox2">
This is an edit page, I load database data into fields with echo, replace them, and hit submit to update them.
But when I hit submit it refreshes the old data onto browser's fields, how can I prevent this?
Submit your form using ajax request with jquery submit.
Use action="javascript:;" for the form tag
You need to handle the script with javascript, then prevent the default behaviour, which is refreshing the page. Here is an example:
*I haven't tested this, but from what I recall this is what I used to do. Let me know if it doesn't work, I'll give other suggestions.
<form>
<!-- elements inside -->
<input type="submit" id="submit-btn" value="Submit"/>
</form>
and in your javascript have the following:
<script>
$("#submit-btn").click(function(e){
e.preventDefault();
// handle form here with your JS
});
</script>

Change iframe from entered value in a textbox

I want to make a page that allows the user to enter his Minecraft name, the entered name will be changed in this link:
http://www.minecraft-skin-viewer.net/3d.php?layers=true&aa=true&a=0&w=330&wt=10&abg=330&abd=40&ajg=340&ajd=20&ratio=13&format=png&login=<NAME>&headOnly=false&displayHairs=true&randomness=708
How can i do this?
You can do that with jQuery.
For example, you have this html code:
<input type="text" id="name">
<input type="button" id="dostuff" value="View your Skin!">
<hr>
<iframe width="290" height="433" id="SkinViewer"></iframe>
Where the tags used only contain relevant information for the script to work.
And the following jQuery code will work when the button is pressed. It create's the url with the value of the input field in it. And then sets the source of the iframe with the created url.
$(document).ready(function(){
$('#dostuff').click(function(){
var url = 'http://www.minecraft-skin-viewer.net/3d.php?layers=true&aa=true&a=0&w=330&wt=10&abg=330&abd=40&ajg=340&ajd=20&ratio=13&format=png&login=' + $('#name').val() + '&headOnly=false&displayHairs=true&randomness=930';
$('#SkinViewer').attr('src',url);
});
});
Keep in mind: for the jQuery to work you should load the jQuery library first!

PHP code regarding multiple submit button on single form

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

Submitting forms and using the value (JavaScript)

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 :)

Categories