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
Related
I'm displaying data from DB like this:
<?php foreach ($r as $k => $v):?>
<div data-role="collapsible" data-mini="true" class="collapsible">
Name: <?=$v['name']?>
</div>
<?php endforeach; ?>
Now when I add new data to DB and the form is submitted, my script redirects back to this page. How do I show the new data immediately without manually refreshing the browser? I usually don't have this issue if I'm not using Jquery Mobile.
You could send the form with jquery ajax
$('form[name="myform"]').submit(function(evt){
evt.preventDefault();
$.post('/my_form_handler.php', $(this).serialize())
.done(function(data){
//Populate dom elements here with new data
}).fail(function(data){
//Handle failed ajax post.
});
});
And then on successful post change the content of the dom-elements.
Not 100% sure i got the right syntax for it but i think it should give you a general idea on how to do it.
The problem here is that the data is hard coded into the page's HTML. After your form submission it's jQueryMobile that's changing the page/view, and no refresh of the page takes place so you're still seeing the same data.
You should refactor to create the loop with JSON data (loaded via AJAX). If the data is cached in a local variable, you can either add to it with the form's data, or make a fresh AJAX call to the server (recommended if you need sorting or filtering).
After reloading the data, the rendering code can be called, showing the new list.
it is easy.
you can send the request to the server using ajax.
and on the server side, you have to make the function to return the data added.
the ajax function will get the success or fail function.
the success function will run if it works.
on the success function , you have to add the content using javascript jquery with the returned data.
Thanks
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 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
Currently I have a button:
<ul>
<li><button onclick="display('1')">1</button></li>
<li><button onclick="display('2')">2</button></li>
<li><button onclick="display('3')">3</button></li>
</ul>
That when pressed, calls a javascript function, and displays PHP based on which button is pressed using AJAX. I figured this out all on my own. The AJAX gets a PHP file with a postgres query that outputs a table of data to a div.
Now I want to be able to add, via form, new data and have it refresh (without reloading the page, yannknow?). I've tried a couple of things, and have hit roadblocks every time.
My initial idea was to have the form submit the data using a javascript function and AJAX, then call my "display()" function after the query to reload the content. I just can't figure it out using GoogleFu.
Based on my current idea, I'd like help with the following:
How do I pass the form data to a javascript function.
How do I use POST to pass that data to PHP using AJAX?
I'm super new to javascript and AJAX. I've looked into jquery as it seems like that's the way to go, but I can't figure it out. If there's a better way to do this, I'm open to suggestions. Please forgive any misuse of nomenclature.
EDIT: Once I solve this problem..., I'll have all the tools needed to finish the project preliminarily.
This example is copied directly from the jQuery API docs for $.post. When in doubt, first place to look is in the API
http://api.jquery.com/jQuery.post/
Example: send form data using ajax requests
$.post("test.php", $("#testform").serialize(), function(data){
/* success- do something with returned data*/
});
Now extend the concept further and wrap the post in a submit handler for the form
$("#testform").submit(function(){
/* code from above, changing form selector to "this" */
$.post("test.php", $(this).serialize(), function(data){
/* success- do something with returned data*/
});
/* prevent browser default submit*/
return false;
})
Refer to jQuery.post method. It does what you want (sends AJAX request with POST data).
To grab values from inputs, use val() method for nodes that have value (textarea, input, .. )
I have a working PHP registration form that goes through $_POST[] requests to check user inputs.
Username length (3-20)
Username availability
Username /^[A-Za-z0-9_]+$/
etc.
Rather than have it take you to a whole new page to display errors, I want a live request to call for the errors from register.php so they will appear in a div on the registration.
<div id="errors">" . $usernameErrors . "</div>
I've been trying to read up on AJAX but have noticed most codes involve utilizing $_GET[].
What will I have to do to get my current forms integrated with AJAX?
My Current Basic Registration Form Logic:
<form method="post" action="register.php">
<input type="text" name="username" id="username" required />
$usernameErrors
</form>
And register.php contains all of the checks already.
If you're using jQuery, it's pretty simple.
<script type='text/javascript'>
$.post('/register.php',
{username: $('#username').val()
// insert values of other fields here
},
function(response) {
// update your div with errors
$('#errors').html(response);
})
</script>
You should invoke this code, for example, when user changes username in registration form. It will happen in background and update page asynchronously.
Your register.php script should, in this case, emit only errors, not the whole page, or you will see unexpected results. :-)
In order to simplify ajax, you can use jQuery (a very powerful JS lib).
Add jquery***.js to your project and refer it on your page:
<< script type="text/javascript" src="#js/jquery-ui-1.8.16.custom.min.js" />
Then, you create the javascript function that will make the ajax call.
On the ajax call, you specify the php file to call and the function to handle the return of php(callback). On this callback function, you add the error message to body.
function verifyForm(){
$.ajax({
type: "POST",
url: "register.php",
data: "username=NAME_GOT_FROM_FORM_&location=Boston"
}).done(function( returned ) { //the callback
$('#errors').html(returned); // add the string returned to div id=errors
});
}
So, the crux of the problem as you're asking it seems to be that you're (correctly) using a POST request on your register form, but your tutorials all want to use GET. Here's a discussion about the difference between the two methods:
http://thinkvitamin.com/code/the-definitive-guide-to-get-vs-post/
If you're actually registering the user with AJAX (rather than just validating) you should be submitting the AJAX request as a POST. If you're using jQuery, the answer has already been given. If you're not using jQuery, then look for the XMLHttpRequest object in your tutorial, and where its "open" method is called (reference here: http://www.w3.org/TR/XMLHttpRequest/). The first parameter of that function is a request method--change it to "post" rather than "get", and the request will be treated like a POST, which register.php expects.
That being said, it sounds like you just want AJAX to validate the form. In that case, GET is the correct verb to use--all you want to do with AJAX is check data against the database, not actually make a change to data. I would suggest that you actually write a new PHP script like validate_registration.php that will perform only the validation logic in register.php, and then return a JSON array of errors (which would be empty if no errors occurred). You can activate/deactivate your form submit button based on that return value, and let the user submit the form just like your old workflow if everything is okay.
The tl;dr here is that you should read up on what makes $_GET and $_POST different, and then write an AJAX-specific validation script so that you're separating the data-retrieval part of your process from the data-insertion part. Once you understand the difference, the rest should follow.