I am using a PHP script, but say I had two radio buttons, right?
How could I actually execute code, such as (main intention | display a messagebox) upon selection of one or the other?
Say I had a radio button named RadioButton1, Once checked/selected, a message box would appear saying RadioButton1 Selected?
Is this possible through PHP alone? Or do I need to integrate an html page which posts to the PHP page?
Use Javascript for client side interaction like that. The code below listens for the onchange event and shows an alert().
jsFiddle Demo
<input type="radio" name="myradio" value="RadioButton1" />
<input type="radio" name="myradio" value="RadioButton2" />
<input type="radio" name="myradio" value="RadioButton3" />
<script>
window.onload = function()
{
var radios = document.getElementsByName("myradio");
for(var i=0; i<radios.length; i++)
{
radios[i].onchange = function()
{
if(this.checked)
{
alert(this.value + " selected");
}
}
}
}
</script>
The first 3 lines are the radio buttons HTML. After that we have the <script> tag which denotes Javascript code. The Javascript is adding some code to the onload event, which simply means: execute this code when the page is loaded. Next we get all of the radio button elements into an array called radios - for that we use getElementsByName() passing the radio button group name which is myradio. Next we loop through each radio button in the array and assign an onchange handler, which means: execute this code when each radio button is changed. Within that, we check if the radio button is checked and if it is, we show the alert, showing the radio button's value which will be RadioButton1, RadioButton2, RadioButton3.
Not possible with just php! Try using Jquery as the easiest was to do this
$(document.body).on('click', '#radio-btn', function(){
$.get( 'file1.php' , function (data) {
//whatever you want to do after fetching the data from a php file
});
});
Selecting a form element is done in the client's browser, while PHP is a server-side language. It is absolutely unaware of what the user clicks until some data is actually sent back to the server, e.g., via a POST request upon submitting a form.
So no, PHP isn't capable of achieving what you are after.
There's an easy way though. JavaScript is executed on the client side, so you can easily attach an event listener to your radio buttons and display a message box if needed.
Using php alone its not possible, but you can do it using Jquery ajax. To do this make a ajax request on click of radio button, and populate the message box with the data comming in response.
Let me explain with an example:
<div id='msg_box'>Message will be displayed here</div>
on click of radio button call a function of javascript say ajaxCallForMessage()
<script type="text/javascript">
function ajaxCallForMessage(){
$.ajax({
url: "Url of the page which contain message/?btn_name=xy",
mthod: "GET"
}).done(function ( data ) {
$('#msg_box').append(data);
});
}
</script>
make sure you included jquery.
If I understood your question properly, I would suggest to do it simply via Javascript.
Once the user selects the RadioButton1, the "click" event is triggered in the page. I guess you know that you can capture it adding the onClick attribute like:
<input type="radio" name="Radio1" value="RadioOption1" onclick="showMessage()"> Option 1
Then all you need to do is to create a Javascript funcion showMessage that adds some html to the page (maybe a paragraph) with the message you want to display. You can do this in Javascript easily, using for example the jQuery append or html functions.
function showMessage() {
// Example displaying an alert
alert("Message to be displayed here")
}
I would only introduce PHP here if there is really a need to obtain information from the server. In this case what you should be doing is probably a GET / POST from the page to the server (e.g. using AJAX via jQuery get or post method). You will call a PHP script that returns some information that then will be displayed in the page through Javascript.
But if all you need is to display a simple message like "Option 1 selected" you should do it in Javascript without server interaction.
I hope this helps.
Regards,
Romén
Related
Ok, this is less of a question than it is just for my information (because I can think of about 4 different work arounds that will make it work. But I have a form (nothing too special) but the submit button has a specific value associated with it.
<input type='submit' name='submitDocUpdate' value='Save'/>
And when the form gets submitted I check for that name.
if(isset($_POST['submitDocUpdate'])){ //do stuff
However, there is one time when I'm trying to submit the form via Javascript, rather than the submit button.
document.getElementById("myForm").submit();
Which is working fine, except 1 problem. When I look at the $_POST values that are submitted via the javascript method, it is not including the submitDocUpdate. I get all the other values of the form, but not the submit button value.
Like I said, I can think of a few ways to work around it (using a hidden variable, check isset on another form variable, etc) but I'm just wondering if this is the correct behavior of submit() because it seems less-intuitive to me. Thanks in advance.
Yes, that is the correct behavior of HTMLFormElement.submit()
The reason your submit button value isn't sent is because HTML forms are designed so that they send the value of the submit button that was clicked (or otherwise activated). This allows for multiple submit buttons per form, such as a scenario where you'd want both "Preview" and a "Save" action.
Since you are programmatically submitting the form, there is no explicit user action on an individual submit button so nothing is sent.
Using a version of jQuery 1.0 or greater:
$('input[type="submit"]').click();
I actually was working through the same problem when I stumbled upon this post. click() without any arguments fires a click event on whatever elements you select: http://api.jquery.com/click/
Why not use the following instead?
<input type="hidden" name="submitDocUpdate" value="Save" />
Understanding the behavior is good, but here's an answer with some code that solved my problem in jquery and php, that others could adapt. In reality this is stripped out of a more complex system that shows a bootstrap modal confirm when clicking the delete button.
TL;DR Have an input dressed up like a button. Upon click change it to a hidden input.
html
<input
id="delete"
name="delete"
type="button"
class="btn btn-danger"
data-confirm="Are you sure you want to delete?"
value="Delete"></input>
jquery
$('#delete').click(function(ev) {
button.attr('type', 'hidden');
$('#form1').submit();
return false;
});
php
if(isset($_POST["delete"])){
$result = $foo->Delete();
}
The submit button value is submitted when the user clicks the button. Calling form.submit() is not clicking the button. You may have multiple submit buttons, and the form.submit() function has no way of knowing which one you want to send to the server.
Here is another solution, with swal confirmation. I use data-* attribute to control form should be send after button click:
<button type="submit" id="someActionBtn" name="formAction" data-confirmed="false" value="formActionValue">Some label</button>
$("#someActionBtn").on('click', function(e){
if($("#someActionBtn").data("confirmed") == false){
e.preventDefault();
swal({
title: "Some title",
html: "Wanna do this?",
type: "info",
showCancelButton: true
}).then(function (isConfirm) {
if (isConfirm.value) {
$("#someActionBtn").data("confirmed", true);
$("#someActionBtn").click();
}
});
}
});
i know this question is old but i think i have something to add... i went through the same problem and i think i found a simple, light and fast solution that i want to share with you
<form onsubmit='realSubmit(this);return false;'>
<input name='newName'/>
<button value='newFile'/>
<button value='newDir'/>
</form>
<script>
function getResponse(msg){
alert(msg);
}
function realSubmit(myForm){
var data = new FormData(myForm);
data.append('fsCmd', document.activeElement.value);
var xhr = new XMLHttpRequest();
xhr.onload=function(){getResponse(this.responseText);};
xhr.open('POST', 'create.php');
// maybe send() detects urlencoded strings and setRequestHeader() could be omitted
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
xhr.send(new URLSearchParams(data));
// will send some post like "newName=myFile&fsCmd=newFile"
}
</script>
summarizing...
the functions in onsubmit form event are triggered before the actual form submission, so if your function submits the form early, then next you must return false to avoid the form be submitted again when back
in a form, you can have many <input> or <button> of type="submit" with different name/value pairs (even same name)... which is used to submit the form (i.e. clicked) is which will be included in submission
as forms submitted throught AJAX are actually sent after a function and not after clicking a submit button directly, they are not included in the form because i think if you have many buttons the form doesn't know which to include, and including a not pressed button doesn't make sense... so for ajax you have to include clicked submit button another way
with post method, send() can take a body as urlencoded string, key/value array, FormData or other "BodyInit" instance object, you can copy the actual form data with new FormData(myForm)
FormData objects are manipulable, i used this to include the "submit" button used to send the form (i.e. the last focused element)
send() encodes FormData objects as "multipart/form-data" (chunked), there was nothing i could do to convert to urlencode format... the only way i found without write a function to iterate formdata and fill a string, is to convert again to URLSearchParams with new URLSearchParams(myFormData), they are also "BodyInit" objects but return encoded as "application/x-www-form-urlencoded"
references:
https://developer.mozilla.org/en-US/docs/Web/API/Document/activeElement
https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/send
https://developer.mozilla.org/en-US/docs/Web/API/FormData
https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams/URLSearchParams
https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/requestSubmit#usage_notes (proves that form.submit() does not emulate a submit button click)
Although the acepted answer is technicaly right. There is a way to carry the value you'd like to assign. In fact when the from is submited to the server the value of the submit button is associated to the name you gave the submit button. That's how Marcin trick is working and there is multiple way you can achive that depending what you use. Ex. in jQuery you could pass
data: {
submitDocUpdate = "MyValue"
}
in MVC I would use:
#using (Html.BeginForm("ExternalLogin", "Account", new { submitDocUpdate = "MyValue" }))
This is actually how I complied with steam requirement of using thier own image as login link using oAuth:
#using (Html.BeginForm("ExternalLogin", "Account", new { provider = "Steam" }, FormMethod.Post, new { id = "steamLogin" }))
{
<a id="loginLink" class="steam-login-button" href="javascript:document.getElementById('steamLogin').submit()"><img alt="Sign in through Steam" src="https://steamcommunity-a.akamaihd.net/public/images/signinthroughsteam/sits_01.png"/></a>
}
Here is an idea that works fine in all browsers without any external library.
HTML Code
<form id="form1" method="post" >
...........Form elements...............
<input type='button' value='Save' onclick="manualSubmission('form1', 'name_of_button', 'value_of_button')" />
</form>
Java Script
Put this code just before closing of body tag
<script type="text/javascript">
function manualSubmission(f1, n1, v1){
var form_f = document.getElementById(f1);
var fld_n = document.createElement("input");
fld_n.setAttribute("type", "hidden");
fld_n.setAttribute("name", n1);
fld_n.setAttribute("value", v1);
form_f.appendChild(fld_n);
form_f.submit();
}
</script>
PHP Code
<?php if(isset($_POST['name_of_button'])){
// Do what you want to do.
}
?>
Note: Please do not name the button "submit" as it may cause browser incompatibility.
I'm trying to figure out a way to load 1 single tab(tabs by jQuery) without reloading all the others.
The issue is that I have a submit button and a dropdown that will create a new form, and when on this new form 'OK' or 'CANCEL' is clicked, it has to get the original form back.
The code to load a part of the page that I found is this:
$("#tab-X").load("manageTab.php #tab-X");
But now I would like to know how to use this in combination with the $_POST variable and the submit-button
Clarification:
I have a .php(manageTab.php) which contains the several tabs and their contents
I have in each of these tabs a dropdown containing database-stored information(code for these dropdowns is stored in other pages)
for each of these dropdowns, there exists a submit button to get aditional information out of the DB based on the selection, and put these informations in a new form for editing
this new form would ideally be able to be submitted without reloading everything except the owning tab.
Greetings
<script>
$(document).ready(function() {
$("#form1").submit(function(){
event.preventDefault();
$.post('data.php',{data : 'dummy text'},function(result){
$("#tab-X").html(result);
});
});
});
</script>
<form id="form1">
<input id="btn" type="submit">
</form>
I am not totally understand your question, but as per my understanding you can't load one tab with form submit. Its normally load whole page.
What you can do is, use ajax form submit and load the html content as per the given sample code.
$.ajax({
url: url, // action url
type:'POST', // method
data: {data:data}, // data you need to post
success: function(data) {
$("#tab_content_area").html(data); // load the response data
}
});
You can pass the html content from the php function (just need to echo the content).
AJAX is what you are looking for.
jQuery Ajax POST example with PHP
Also find more examples about ajax on google.
Example: Let me assume you have a select menu to be loaded in the tab.
You will need to send a request to your .php file using jquery, and your php file should echo your select menu.
In your jQuery,
<script>
$.post(url, { variable1:variable1, variable2:variable2 }, function(data){
$("#tab-X").html(data);
//data is whatever php file returned.
});
});
$("#form_id").submit(function(){
return false;
});
</script>
I mean whatever your options are, you will need to do the following in your .php file,
Echo that html code in your PHP script.
echo "<select name='".$selector."'>
<option value='".$option1."'>Option1</option>
<option value='".$option2."'>Option2</option>
<option value='".$option3."'>Option3</option>
</select>";
This would be returned to jQuery, which you may then append wherever you want.
Do you know a way to display a php result inside a div dynamically, without refreshing the page?
For example, we have 2 divs: one on the top half of the page and one on the bottom of the page. The top one contains a form with 3 input fields. You type some values inside, then press a button. When you press the button, the bottom div displays the values without refreshing the page.
You can't do it with pure PHP because PHP is a static language. You have to use Javascript and AJAX. I recommend using a library like Zepto or jQuery to make it easy to implement like this:
<form>
<input name="search" />
<input type="submit" />
</form>
<div id="div2"></div>
<script>
// When the form is submitted run this JS code
$('form').submit(function(e) {
// Post the form data to page.php
$.post('page.php', $(this).serialize(), function(resp) {
// Set the response data into the #div2
$('#div2').html(resp);
});
// Cancel the actual form post so the page doesn't refresh
e.preventDefault();
return false;
});
</script>
You can accomplish it using AJAX. With Ajax you can exchange data with a server, make asynchronous request without refreshing the page.
Check this out to see how it can be implemented using Jquery:- http://api.jquery.com/jQuery.ajax/
I have a webpage that generates a table from mysql. I have a button at the beginning of each row. I would like it so if the user decides to press on the button, the contents of that individual row are written to a new table in MySQL.
Currently I am thinking of just having the button be an href to another php script that connects to mysql and inserts the row into a table; however, I think that will redirect my current page.
I would like the button to run the script, without redirecting my current page. That way, the user can continue analyzing the table without having the page have to reload every time.
This is what my current table looks like. This is just a snippet, and the table can be very large (hundreds of rows)
In order to do this client side, there are a couple of ways I can think of off hand to do this:
Javascript
You can include a Javascript library (like the ever popular JQuery library), or code it yourself, but you could implement this as an XMLHTTPRequest, issued from a click handler on the button. Using a library is going to be the easiest way.
An iframe
Create a hidden iframe:
<iframe style="display:none;" name="target"></iframe>
Then just set the target of your tag to be the iframe:
...
Whenever someone clicks on the link, the page will be loaded in the hidden iframe. The user won't see a thing change, but your PHP script will be processed.
Of the two options, I'd recommend the Javascript library unless you can't do that for some reason.
You need to insert a record into mysql table upon click of button without reloading the page.
For accomplishing the above task you need to use AJAX which will send http request to server in background using xmlhttprequest object and thereby updating web page without reloading the web page.
So you will have to create a function in javascript which will send http request to server using xmlhttprequest object and also you need to define server side handler for processing http request sent using ajax.
For implementation details of ajax with php ,please refer the example mentioned in below link
http://www.w3schools.com/php/php_ajax_php.asp
It's easy to do using jQuery:
<script>
$(function(){
$('#your_button_dom_id').click(function(){
$.ajax({
url: 'your_php_script_url',
type: 'POST', // GET or POST
data: 'param1=value1¶m2=value2', // will be in $_POST on PHP side
success: function(data) { // data is the response from your php script
// This function is called if your AJAX query was successful
alert("Response is: " + data);
},
error: function() {
// This callback is called if your AJAX query has failed
alert("Error!");
}
});
});
});
</script>
You can read more about AJAX in jQuery here: http://api.jquery.com/jQuery.ajax/
You can use another input tag after your submit button with hidden type.
<input class="ButtonSubmit" type="Submit" name="Submit" id="Submit" value="Submit"/>
</p>
<input type="hidden" name="submitted" id="submitted" value="true" />
after that use in top of your code this
if (isset($_POST['submitted'])) {
// your code is here
}
it's work for me. you can use it in wordpress template as well
I am currently working on a php e-mail system. I created a javascript pop-up page where I can add users (mail addresses). Now I want to post the selected user('s) from the javascript pop-up window to open the website of course I get the page where you want to post in the pop up to see.
Now I want to now, if there is click on the submit than close the popup and allows the data to the open web page whit post?
How can i do this??
you might want to look to the overlay plugin at jquery tools. Pop-ups are blocked by the browser most of the times. And imo an overlay is a more elegant solution. Furthermore, you can just post your form as you would normal do on a webpage, nu extra js needed there!
--- edit; when reading your question more closely; you don't even need to post the page! Just assign a click event to the submit button (which doesn't necessarily needs to be a submit button). In your event function you can read out the filled in addresses (or other information), paste it into the desired fields (whether it be a form field or just a regular div) and close the overlay again. Now you don't even need a page refresh!
You'll want to use AJAX to post the form asynchronously so the user doesn't have to wait for it to process or view the processing page. jQuery makes it very easy to use AJAX as shown here.
Also, after the work is done in the popup window you can access and refresh the parent window using the window.opener function:
<script language="JavaScript">
function refreshParent() {
window.opener.location.href = window.opener.location.href;
window.close();
}
</script>
<script>
$("a[href=#myModal]").click(function() {
var str = $(this).attr("data-phpvar");
var substr = str.split('||');
$("[name=textinput1]").val(substr[0]);
$("[name=textinput2]").val(substr[1]);
});
</script>
<form>
<table>
<tr>
<td>
</td>
</tr>
</table>
</form>
OnClick of the href link or button you will send the data-php-var to the jQuery function. This function will send the values into the popup. In the popup is a text-field with the same name the jQuery function will put your values into de field.