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
Related
I've recently changed my searching page to a searchable datatable page due to my employer's request for easier data management. The problem is that it is taking too long to load.
I'm wondering it there is a way to only load like a portion of the table and finish loading the page first. Then finish off loading the rest of the table after that, e.g. while the user actually attempt to search for the data.
This was requested because the user might want to navigate to other parts of the page instead of using the datatable.
Extra info : The page is in .php and the data is loaded using php do-while loop. Maybe we can do a workaround using php functions?
Using the AJAX method recommended in the comments, the following is similar to how you could handle the page-load. You would need the jQuery library for the below.
Initial page
<script type="text/javascript">
// when the page is done loading,
// let's send a call to load more data
$(document).ready(function(){
myFunction();
});
// function to handle AJAX request to gather data
function myFunction(){
$.ajax({
type: "POST",
url: "./linkToMyPHP.php?loadData=1",
success: function(data){
// handle the data using the "data" variable
}
});
}
</script>
AJAX Page
<?php
if(isset($_GET["loadData"])){
// call query here and echo information
}
It may be recommended, to actually use a PHP function called json_encode() to echo back the information from your AJAX page in JSON form. This would allow you to transmit an array of information, instead of raw data. You would then need to update your AJAX request function similar to below.
$.ajax({
type: "POST",
url: "./linkToMyPHP.php?loadData=1",
dataType: "json",
success: function(data){
$("#myDivToChange").html(data);
}
});
You can read up on JSON at this highly rated question.
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);
}
});
I have a table which has user names. When I click a user I need to retrieve their information from mysql database and this information will be populated into the relevent textboxes. I am totally stumped on how I go about doing this? Can someone please help
You can use jquery to achieve this in ajaxed way. In test.php write your php mysql code.
The below code a javascript code used to get data from a different page where you can process and get the information about any particular user. Read about ajax.
$.ajax({
url: 'ajax/test.php',
data: 'id=<?php echo $id?>',
type: 'POST',
success: function(data) {
//you can get data as an array and parse it to get fields and you can put them whever you want.
$('.result').html(data);
alert('Load was performed.');
}
});
Here is the jquery code which will solve your issue. Write this code in a javascript function. onclick event of that button should call this function. Write all your db coding in yourpage.php.
url = "yourpage.php";
$.get
(
url,
{
'act' :'getdata'
},
function(responseText)
{
strData = responseText;
$('#div_id').html(strData);
},
"html"
);
Place all your html code inside DIV and call the div in jquery code. It will work.
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);
I am working on a project for reserving classrooms. One way of reserving a room is to select a room, see if the things it has (# of seats, # of computers, etc.) is ample for whatever the person needs it for, and then make a reservation.
I have a page that displays all of the available rooms as links in an HTML table, created dynamically in PHP/MySQL. My goal is when a user clicks on a room name, the AJAX request executes a query and returns the necessary data, and then displays it in a DIV on that same page.
Right now, I'm calling an external PHP file that gets the ID of the room that's clicked and executes the query. I'm still very much a novice at jQuery, and I'm pretty sure the problem is in my jQuery script:
<script type="text/javascript">
$(document).ready(function()
{
$('table.roomNums td a.rm-details').click(function()
{
var id = $(this).attr('id');
$.ajax(
{
type: 'POST',
url: 'roomInfo.php',
data: {
roomID: id
},
dataType: 'json',
cache: false,
success: function(result)
{
$('#room-details').empty();
$('#room-details').append("<ul>\n\t<li>Seats: " + result.numOfSeats + "</li>\n</ul>");
}
});
});
});
</script>
As of now, when I click on one of the room number links, nothing happens. I'm assuming that my problem resides in this script, but I'm not sure where or what. I've been reading into the ajax function in jQuery and I'm pretty sure I understand what's going on, but I'm having no luck at the moment.
You want to troubleshoot the following four things:
The HTTP Request Does the browser even issue an ajax request? If so, does it contain the form parameter you are trying to make it contain?
The HTTP Response Does your php script return the data you are expecting in JSON format so JQuery can automatically parse it for you? Copy and paste the response from the server into a test javascript file and see if it compiles as a valid JSON object in a javascript debugger.
AJAX success function Does your javascript error out? Can you step through each line of execution in a javascript debugger like firebug?
Click Event Handler Does your click handler properly return false so the page does not reload? Does your click event handler function fire at all upon click?
Somewhere in the above four things lies your issue. It looks to me like you just need to return false in your click handler so the page does not reload.