I am attempting to clean up my website code and looking at trying to reduce page reload when acquiring new data from MySQL queries.
Currently I have a form that allows the user to select categories which are then passed to the same page using action = "currentpage.php" which are picked up by a second html script that accesses a database and produces a template of articles that match the conditions.
Unfortunately as it currently is, the entire page reloads which seems very sloppy considering its only 2 script I need changing.
How would I go about having the script that runs the query update when it detects a button press?
I've read that AJAX is the way to go but I cant get my head around it from the examples I've seen. No data actually leaves the page, it just cycles round.
I think I need to have the MySQL script that shows the results separate and have it called, but again, I'm not sure how to call an entire script like that.
I'm very new to php and not sure what exactly I'm looking for so trying to Google for a solution is like taking shots in the dark.
What am I actually looking for to accomplish this task? and if possible a source to read how to do it :D
Thanks
Yes you're right. Ajax would be the best way to move forward. So you could do something like this:
$(function(){
$('#your_select_id').change(function () {
var select_value = $(this).val();
if ($.trim(select_value) != '') {
$.ajax({
type: 'post',
url: 'somepage.php',
data: {
selected_value: select_value
},
success: function (returned_data) {
$("#your_result_div_id").html(returned_data);
}
});
}
});
});
So what are we doing here?
onchange
event of the select tag. somepage.php
and sending the value of the select tag to it. somepage.php
, you can query the database based on that value ( $_POST['selected_value']
) and return back the HTML. success
function, we are displaying the returned HTML from somepage.php
into a empty div that you need to place somewhere in your document. Note: You'd need the jQuery library that needs to be included on the page before using the $.ajax
function.
With ajax you make a request back to the server. With jquery this is really easy: What you do
Example PHP:
<?php echo json_encode(array("firstname"=>"mark","lastname"=>"smit"));?>
Example javascript:
$("#button").click(function(){
$.get( "test.php", function( data ) {
$(".firstname").html(data.firstname);
$(".lastname").html(data.lastname);
}, "json" );
});
You can mfind more documentation about get in jquery here: http://api.jquery.com/jQuery.get/
You can find more about json here: http://www.php.net/manual/en/function.json-encode.php
The solution is simple, but you'll need support from javascript, ajax and json.
Here's what you need to do:
1) First you will need to setup your form like this:
<form action="yourpage.php" method="POST">..</form>
2) Then you will have to intercept click on submit button, and prevent default behavior that would be sending the form to php and reloading the whole page, like this:
I assume you are using jQuery framework:
$("#yourbutton").on("click", function (e) {
var obj, $this;
//wrap the button with jquery object for future convenience
$this = $(this);
//prevents default browser behavior
e.preventDefault();
//collects data from forms
obj= collectData($this)
//sends data through ajax, and wait for the callback
sendData($this,obj)
});
3) Then you'll have to collect all the data from the inputs in the form and save them into an object, like in this example:
function collectData(obj){
var inputs, i, len, cache, ret = [];
inputs = $obj.find("input");
for(i = 0, len = inputs.lenght; i < len; i = i + 1) {
cache = obj.eq(i);
//You can insert any attribute you like in the object, and you should pay attention
//to the differents parameters you need to save, for example when you handle
//textareas etc.
ret.push = {id: cache.attr("id"), name: cache.attr("name"), value:
cache.val()};
}
return ret;
}
function sendData(source, obj){
var json, settings, url;
//encode the obj using json, and prepare it for php
json = JSON.stringify(obj);
//get the url of the php page where you'll handle the data
url = source.attr("action");
//set up the ajax connection
settings = {
//this is the big thing! you will receive the response of PHP here
success: function (data) {
var result;
//data is the result of your php script
result = JSON.parse(data);
},
//You can reference jQuery ajax docs to better understand why i've used this settings
cache: false,
type: "POST",
//in the jdata var, you will find your form object in php
data: {jdata: json},
dataType: "json",
contentType: "application/json; charset=utf-8",
async: false
};
$.ajax(url, settings);
}
Finally PHP script:
yourpage.php
if(isset($_POST["jdata"])){
$request = $_POST["jdata"];
$id = $request -> id;
//[....] treat all your data and so on
//In the end return the data from your PHP script.
echo json_encode($array);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.