Show PHP result in div without refresh - php

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/

Related

Stop form from refreshing on submit

I've got this problem that the form refreshes on submit, i dont want it to refresh but i do want it to submit. any of you know what i could do ?
click this link to an older post about this.
<form method="post" id="radioForm">
<?
foreach($result as $radio):
printf('
<button type="submit"
href="#radio"
name="submitRadio"
value="'.$radio['id'].'">
Go!
</button>
');
endforeach;
?>
</form>
<script type="text/javascript">
$('#radioForm').submit(function(event) {
event.preventDefault();
$.ajax({
url:'index.php',
data:{submitRadio:[radiovalue]},
type:'POST',
success:function(response) {
/* write your code for what happens when the form submit */
});
});
</script>
</div>
Use submit() handler and pass the value of your button to your other script
First set the id on the form.
<form method="post" id="formId">
Then bind a listener
$( "#formId" ).submit(function( event ) {
event.preventDefault();
//This is where you put code to take the value of the radio button and pass it to your player.
});
To use this you need jQuery.
You can read more about this handler here: http://api.jquery.com/submit/
This is the default behavior of a HTML <form> on submit, it makes the browser POST data to the target location specified in the action attribute and loads the result of that processing to the user.
If you want to submit the form and POST the values behind the scenes without reloading the page, you have to disable the default behavior (the form submit) and employ the use of AJAX. This kind of functionality is available readily within various JavaScript libraries, such as a common one called jQuery.
Here is the documentation for jQuery's AJAX functionality http://api.jquery.com/jquery.ajax/
There are lots of tutorials on the interwebs that can introduce you to the basic use of jQuery (Including the library into your HTML pages) and also how to submit a form via AJAX.
You will need to create a PHP file that can pick up the values that are posted as a result of the AJAX requests (such as commit the values to a database). The file will need to return values that can be picked up within your code so that you know if the request was un/successful. Often the values returned are in the format JSON.
There are lots of key words in this answer that can lead you on your way to AJAX discovery. I hope this helps!
use ajax like this of jquery
$('form').submit(function(event) {
event.preventDefault();
$.ajax({
url:'index.php',
data:{submitRadio:[radiovalue]},
type:'POST',
success:function(response) {
/* write your code for what happens when the form submit */
}
});
});

load part of html using php/jQuery

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.

PHP - Display message directly after selecting a Radio Button

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

Button that runs a php script without changing current page

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&param2=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

Javascript pop-up

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.

Categories