Refreshing dynamic select boxes without reloading page - php

I have a jquery mobile app that on page load, reads data from the database and populates select boxes on the page with user specific data like their favorite addresses.
Ive implemented an ajax script that deletes the selected option which works well. But I need to find a way refresh the select boxes without reloading the page.
I gather AJAX is the way I need to go, but I wouldn't know where to start.
I assume I'll need to re-run the php file that reads the database and then the javascript that takes the returned data and populates the select boxes.
index.php (First Part)
<?php
$show_faves_pass=true;
$show_faves_cctr=true;
include('../includes/favourites.inc');
?>
favorites.inc
$js_str='';
if ($show_faves_addr){
// Postgres sql statement here
$addr_json=json_encode($addr_rows);
$js_str.="var fave_addresses=$addr_json;\n";
}
if ($show_faves_cctr){
// Postgres sql statement here
$cctr_json=json_encode($cctr_rows);
$js_str.="var fave_costcentres=$cctr_json;\n";
}
if (strlen($js_str)>0){
echo "<script type='text/javascript'>\n$js_str\n</script>\n";
}
index.php (Second Part)
//populate favourites pickers
function findFave(arr,key,val){
var found=null;
$.each(arr,function(i,v){
if (v[key]==val){
found=v;
}
});
return found;
}
var pass_fave_sel=$('select#pass_fave_picker');
$.each(fave_passengers,function(i,fave){
pass_fave_sel.append("<option value='"+fave.passenger_details_id+"'>"+fave.passenger_nickname.replace("'","\'")+"</option>");
});
var cctr_fave_sel=$('select#cctr_fave_picker');
$.each(fave_costcentres,function(i,fave){
cctr_fave_sel.append("<option value='"+fave.cost_centre_id+"'>"+(fave.cost_centre_code+" ("+fave.cost_centre_nickname+")").replace("'","\'")+"</option>");
});
Hopefully this all makes sense, any help at all will be appreciated,
Thanks heaps in advance!

Every jQM element has its own refresh method used for restyling.
For example:
Listview has a:
$('#listviewID').listview('refresh');
Here's an example: http://jsfiddle.net/Gajotres/AzXdT/. This is a listview dynamically generated from XML data.
Button elements have a:
$('#buttonID').button('refresh');
Here's an example: http://jsfiddle.net/Gajotres/K8nMX/
Slider has a:
$('#sliderID').slider('refresh')
And you are going to use this one:
Selectmenu has a:
$('select').selectmenu('refresh', true);
By now you can see a pattern here. To refresh always use a component name as s function with 'refresh' parameter.
In case you are doing a whole page restyle you should use this method.
EDIT :
$.ajax({url: server_url,
data: save_data,
beforeSend: function() {
$.mobile.showPageLoadingMsg(true);
},
complete: function() {
$.mobile.hidePageLoadingMsg();
},
success: function (result) {
// Here delete elements from select box
},
error: function (request,error) {
// Throw an error
}
});

Related

Best practice for using jquery to interact with php classes?

I have a dropdown selector on a page that allows a user to select a template type (for example, "human" or "dog").
Based on what template is selected, different fields will need to populate below the dropdown (for example, text fields for "parents names" or a dropdown list for "breed") that are unique to each template.
I will have a button that the user will click once the data fields are put in that will output data to an "output div" section of the same page when clicked (no POSTing data as it's not being saved). The output will have different output logic based on the selected template (for example, "I'm a human named X" or "I'm a dog, my breed is Y").
My real program will be more complex and each template will have a php class that stores all of the logic. Since I will be dealing with both php objects and variables gathered by jquery, what's the best way to let them interact?
For 1., I know I can do something easy like -
var selected_template = $('#my-template-dropdown :selected').text();
if (selected_template == 'Human'){
$('#my-fields').html('<?php echo HumanTemplate::render_fields(); ?>');
}
which is easy enough, but for 2. I need to pass variables from jquery to php, then return output back to jquery.
I would like some advice on the easiest way to do this before I start down the wrong path.
HTML
Allow the user to select the template type:
<form>
<select id="my-template-dropdown" name='template'>
<option value="dogs">Dogs</option>
<option value="humans">Humans</option>
</select>
</form>
<div id="my-fields"><div>
<div id="output"><div>
jQuery
Any time the user changes the template selection, request new content to display via AJAX, and insert it on the current page so the page does not have to refresh:
$('#my-template-dropdown').on('change', function() {
var template = $(this).val();
$.ajax({
url: 'http://your-site/path/to/' + template,
success: function(resp) {
$('#my-fields').html(resp);
}
});
});
PHP
http://your-site/path/to/template simply generates the HTML you want to display for that template, eg (just an example, don't know if this is suitable for your app):
if ($template == 'humans') {
echo HumanTemplate::render_fields();
} else if ($template == 'dogs') {
echo DogTemplate::render_fields();
}
For part 2, assuming all the logic you refer to is in the template rendered by PHP, you could then handle it with jQuery. This is pretty crude, you probably need something more sophisticated (eg a full template which you swap variables into?), but you get the idea:
$('#output').on('click', 'button', function(e) {
e.preventDefault();
// fields in your template which the user will fill
var species = $('#species').val(),
title = $('#title').val();
// Probably better to have this text as a template in your source
$('#output').html("I'm a " + species + ' named ' + title);
});
NOTE the gotcha in the event handler. Event handlers will only attach to elements that exist at the time the handler is defined. Since the content is injected after page load, an event handler like $('#button).on('click', function() {... would have no effect when clicking a button inserted via AJAX. The syntax here attaches to the parent #output div, which does exist at page load, and filters for clicks on a button. See the jQuery event delegation docs for more info.
Another option would be to POST the submitted data to some PHP controller, which generates and returns the output. This way all your logic is in the one place. For example, here the user's click will query the same PHP file which generated the initial template, this time including the values the user has entered. It could then generate the required output and return it, to be inserted on the page. You'd need to update the PHP so it can determine which of these cases it is handling (eg hidden field?); alternatively if you wanted to keep those separate you could hit another PHP file all together.
$('#output').on('click', 'button', function(e) {
var template = $('#my-template-dropdown').val(),
$form = $('form'),
data = $form.serialize(); // Values from all fields user has entered
$.ajax({
url: 'http://your-site/path/to/' + template,
data: data,
success: function(resp) {
$('#output').html(resp);
}
});
});
The best way to pass data from jQuery to PHP, is by using AJAX.
Mozilla has an excellent guide on getting started, that i recommend you follow.
An example of how you can achieve what you are requesting, is by trying the following:
var selected_template = $('#my-template-dropdown :selected').text();
var ajaxurl = 'ajax.php',
data = {'select_template': selected_template };
$.post(ajaxurl, data, function (response) {
console.log(response);
});
On the PHP end (Ajax.php in my example) It could look something like this
if(isset($_POST['select_template'])) {
// do something with the input from jQuery
$selected_template = $_POST['select_template'];
// return the result back to the client
echo $seleted_template;
}
?>
$selected_template will be sent back to the client, and response in the AJAX function will be whatever the server returned. So the console.log(response) should display whatever was being sent to the server
You can have a look to the function wp_localize_script.
This function make available PHP datas to JS files on the page load through the wp_enqueue_scripts action.
This will not work like an Ajax request and only populate data for a specific handle on page load. But you can mix this method with ajax in the same script.
Hope it helps even it doesn't seems to fit to your case.
As your class not fires on page load, you can use the action wp_ajax_{custom _action} and wp_ajax_nopriv_{custom_action} . For example, that's usually used to populate multiple dropdown, each time an event is trigger by the user, a php function returns result the js script.

Using JQuery to refresh an HTML form (located on a PHP page)

I'd like to update a form, more exactly I wish to display an extra scroll menu, depending on the user's choice in a first scroll menu.
I have a page, mypage.php page on which there is a form. Here it is :
<form method="post" action="wedontcare.php" enctype="multipart/form-data">
<label for="base">3 - Select a DB </label><br />
<?php
include 'functions.php';
offers_choice_DB();
if (isset($_POST['base_name_choice'])){
offers_choice_table($_POST['base_name_choice']);
}
I have a separated file "functions.php" where are declared all the functions I use here. offers_choice_DB() displays a scroll menu where I can select a database (actually, this function performs a MySQL query and echoes the result in a scroll menu). If the user selects a database, then $_POST['base_name_choice'] exists. And it does, because when i only work with PHP/HTML, all is doing fine.
My purpose is to allow the user to select a database, then for this database I'd like to display a second scroll menu that displays some tables from this DB. This scroll menu will only be displayed if a POST value has been set. The offers_choice_table($_POST['base_name_choice']) function takes this value as an argument, then echoes the HTML for the scroll menu, containing the tables. Here we are !
Oh, and the submit button is not important here, because I want to have my second scroll menu displayed before the user clicks on the submit button, so we just disregard the target page, ok ?
Before, everything was OK : I used tests, conditions (isset...) but it was not dynamic, I had to call other pages, ...etc. And now I want, as you guessed, to use jQuery to refresh mypage.php as soon as the user selects a database so that an extra menu appears.
I started to listen to a change in my scroll menu, but then I don't know what to do to refresh my page with a POST parameter containing the selected database. Anyway, here is my code :
<script type="text/javascript">
$( '#base_name_choice' ).change(function() {
var val = $(this).val(); //here I retrieve the DB name
alert( val ); //I notify myself to check the value : it works
$.ajax({
type: 'POST', //I could have chosen $.post...
data: 'base_name_choice='+val, //I try to set the value properly
datatype: 'html', //we handle HTML, isn't it ?
success: function(){
alert( "call ok" ); //displays if the call is made
//and here...???? I don't know whatto do
}
})
});
</script>
Here it is...any help will be appreciated ! Thanks :)
Regards
The issue here is that your page is rendered first (html + php preprocessing). That means that once your page is rendered, you won't be able to make direct php method calls such as offers_choice_table or change the $_POST parameters.
How you normally do this, is by making an AJAX call from your javascript to a PHP script/method which than generates the second menu based on the parameter that the user chose.
So, you don't need this part:
if (isset($_POST['base_name_choice'])){
offers_choice_table($_POST['base_name_choice']);
}
because you will call "offers_choice_table" method with an ajax call.
You make the ajax call to a url which will return the second menu
$.ajax({
type: "GET",
url: "generate_second_menu.php",
data: { base_name_choice: val},
success: function(data){
alert( "call ok" ); //displays if the call is made
// here you can append the data that is returned from your php script which generates the second menu
$('form').append(data);
}
})
You should use GET instead of POST, in your new PHP file:
if (isset($_GET['base_name_choice'])) {
offers_choice_table($_GET['base_name_choice']);
}
You SHOULD check if the variable has a value set, especially if your function is expecting one. You can use whatever functions you want in this file, it is like any other PHP file you would write. Include any files that you want.
You should make sure to avoid SQL injection when using a GET or POST value in a query: How can I prevent SQL injection in PHP?
In the .ajax() call, there is a callback function success, this runs if the server response is good (i.e. not a 404 or 500). There first parameter in that function is what the server returned. In your case, it would be the HTML you echoed out. You can use jQuery to append the response to an element:
$.ajax({
type: "GET",
url: "generate_second_menu.php",
data: { base_name_choice: val},
success: function(data) {
// it looks like you're only returning the options of the select, so we'll build out the select and add them
var $newSelect = $('<select></select>');
$newSelect.append(data);
// and then add the select to the form (you may want to make this selector for specific)
$('form').append($newSelect);
}
});

run a query code to retrieve array from database without page refresh

Am kind of not into ajax or json requests, but it seems i might be needing it now or any alternative means, am working on a school management software, i have a page with forms in which when i select a class on the form, it loads all subjects attributed to the class from the database, i already have a php code that would query that, but since php is a server-side language, i would have to reload the page to get the list of subjects from the selected class.. please how can i go about it using any means; here is my code to get classes based on class selected into an array... how can i make this run without a reload
$subjects = $this->crud_model->get_subjects_by_class(class_id);
Basic ajax call:
<script>
$('#button').click( function () {
$.ajax({
type:"POST",
url: "phpsite.php",
data: {
postdata: variable
},
success: function(data){
$('#divtochange').html(data);
}
});
} );
</script>
In phpsite.php, just put the code you would usually refresh. You will need to include jQuery.
Here is a tutorial

Update php generated content without page refresh

I've created a php function (called "category_page" in "category-page.php") which reads data from a file into an associative array and then generates some html to display the information on products.php (the page calling the "category_page" function)
My aim is to allow the user to select from a drop down in order to sort the displayed information without refreshing the page.
I have so far managed to achieve this using document.formname.submit on change of the dropdown and then using $_GET to choose which key in the array to sort by, however, this causes the page to reload.
I have a little knowledge of php, javascript/jquery and have done a fair bit of searching/reading on AJAX to enable an update without refresh/reload, but can't seem to put all the pieces together.
So, in products.php, I have the following javascript/jquery:
function sort_products() {
queryString = "?sort_list="+$("#sort_list").val();
$.ajax({
type: 'GET',
url: 'category-page.php',
data: 'sort_list='+queryString
})
}
$("#sort_list").on("change", function() { sort_products() });
and then in category-page.php:
if(isset($_GET['sort_list'])) {
$sort = $_GET['sort_list'];
}
else {
// set default sort order
}
I've verified in Chrome's network panel that a request for category-page.php?sort_list=price is being sent, but the page isn't updating. Any help would be appreciated!
Change this line of code:
$("#sort_list").on("change", function(e) { sort_products(); e.preventDefault(); e.stopPropagation(); });
Once the query is sent, you need to make something with what is returned.
$.ajax({
type: 'GET',
url: 'category-page.php',
data: 'sort_list='+queryString
})
.done(function(data) {
// if your php code returns the html you can make something like this
// the var data will be the html code
$('#your-container').html(data)
})

onclick -> mysql query -> javascript; same page

I need button to begin a mysql query to then insert the results into a javacript code block which is to be displayed on the same page that the button is on. mysql queries come from the values of drop-down menus.
Homepage.php contains
two drop down menus
div id='one' to hold the results javscript code block
a button to stimulate the mysql query to be displayed in div id ='one' through Javascript
flow of the process is as such
1. user chooses an option from each drop down
2. when ready, the user clicks a button
3. the onclick runs a mysql query with selections from the drop down menu.
4. send the results as array from the mysql query into the javascript code block
5. display the results in div id ='one'
all of this needs to happen on the same page!
The problem I am having is that as soon as the page is loaded, the javascipt is static. I am unable to push the mysql results into the javascript on the page which I need it to appear on. Having everything on the same page is causing trouble.
I'm not looking for the exact code laid out for me, just a correct flow of the process that should be used to accomplish this. Thank you in advance!
I've tried
using both dropdowns to call the same javascript function which used httprequest. The function was directed towards a php page which did the mysql processing. The results were then return back through the httprequest to the homepage.
I've tried to save the entire Javascript code block as a php variable with the mysql results already in it, then returning the variable into the home page through HTTPRequest, thinking I could create dynamic javascript code this way. Nothing has worked
You need to use a technology called AJAX. I'd recommend jQuery's .ajax() method. Trying to do raw XHR is painful at best.
Here is how you'll want to structure your code:
Load the page.
User chooses an option.
An onChange listener fires off an AJAX request
The server receives and processes the request
The server sends back a JSON array of options for the dependent select
The client side AJAX sender gets the response back
The client updates the select to have the values from the JSON array.
Basically, HTTP is stateless, so once the page is loaded, it's done. You'll have to make successive requests to the server for dynamic data.
Use AJAX,
example
$.ajax({
type: "POST",
url: "yourpage.php",
data: "{}",
success: function(result) {
if(result == "true") {
// do stuff you need like populate your div
$("#one").html(result);
} else {
alert("error");
}
}
});
For this purpose you need to learn ajax.This is used to make a request without reloading the page.so that you can make a background call to mysql
your code will be something like that
$("#submitbutton").live("click",function(){
$.ajax({url:"yourfile"},data:{$(this).data}).done(function(data){
//this data will in json form so decode this and use this in div 2
var x =$.parseJSON(data);
$("#div2").html(x.val());
})
})
and "yourfile" is the main file which connect to server and make a database request
here is how I used an onchange method to stimulate a MYSQL query and have the Highchart display the result. The major problem was that the returned JSON array was a string that needed to be converted into an INT. The resultArray variable is then used in the data: portion of the highChart.
$(function(){
$("#awayTeam").change(function(){
$.ajax({
type: "POST",
data: "away=" + $("#awayRunner").val(),
dataType: "json",
url: "/getCharts.php",
success: function(response){
var arrayLength = response.length;
var resultArray = [];
var i = 0;
while(i<arrayLength){
resultArray[i] = parseInt(response[i]);
i++;
}
In the PHP code, the array must be returned as JSON like this
echo json_encode($awayRunner);

Categories