How can I pass multiple data from PHP to jQuery/AJAX? - javascript

I have a main select list of courses which drives various things on a page. When a course is selected another select list will be repopulated with the start date of that course up to 6 months in advance. Also, I have a table on the page with the students name and phone number, when a course is selected, the table will be repopulated with all the students enrolled onto that course. My problem is I will be getting various different things from PHP via JSON i.e. the students and the starting date. How can I therefore pass more than one thing to jQuery? What if the course select list affected not just 2 things but 3, 5 or even 10? How would we handle that with PHP and jQuery?
foreach($m as $meta)
{
$metaCourse = $this->getCourseInfo($meta['parent_course']);
//populate the select list with the name of each course
$metaSelectList .= '<option id="select'.$count.'" value="'.$metaCourse['id'].'">'.$metaCourse['fullname'].'</option>';
$count++;
//get only the first course's dates
if($count3 == 1)
{
$startDate = intval( $course->getStartDate(50) );
$endDate = strtotime('+6 month', $startDate);
//populates the select list with the starting date of the course up to the next six months
for($date = $startDate; $date <= $endDate ; $date = strtotime('+1 day', $date))
{
$dateSelectList .= '<option id="select'.$count2.'" value="'.$date.'">'.date('D d F Y', $date).'</option>';
$count2++;
}
$count3++;
$students = $s->getStudents($metaCourse['id']);
$content = $this->createStudentTable($students);
}
}
This is my handler for the AJAX...FOR NOW (I haven't implemented the students table yet as I'm still trying to figure out how to pass multiple pieces of data to jQuery). Basically each time a course is selected, PHP creates a new select list with the appropriate dates and then passes it to jQuery. I'm not sure if I should do this in JavaScript or in PHP.
if (isset($_GET['pid']) && (isset($_GET['ajax']) && $_GET['ajax'] == "true"))//this is for lesson select list
{
$pid = intval( $_GET['pid'] );
$c = new CourseCreator();
$startDate = intval( $c->getStartDate($pid) );
$endDate = strtotime('+6 month', $startDate);
$dateSelectList = '<select name="dateSelect" id="dateSelect">';
//populates the select list with the starting date of the course up to the next six months
for($date = $startDate; $date <= $endDate ; $date = strtotime('+1 day', $date))
{
$dateSelectList .= '<option id="select'.$count2.'" value="'.$date.'">'.date('D d F Y', $date).'</option>';
$count2++;
}
$dateSelectList .= '</select>';
echo json_encode($dateSelectList);
exit;
}
My jQuery handler:
$('#metaSelect').live('change', function()
{
$.getJSON('?ajax=true&pid='+$('#metaSelect').val(), function(data)
{
alert(data);
$('#dateSelectDiv').html(data);
});
});

You can easily pass ALOT of data from PHP to your HTML via JSON (which you seem to of put in basic already)
However to expand on what you have - heres a quick example
<?php
$arrayOfStuff = array("theKey" => "theEntry", 123 => "Bob Dow", 56 => "Charlie Bronw", 20 => 'Monkey!', "theMyID" => $_POST['myID']);
echo json_encode($arrayOfStuff);
?>
On your HTML side.
<script>
$.post("/theurl/", {type: "fetchArrayOfStuff", myID: 24}, function(success) {
//your success object will look like this
/*
{
theKey: 'theEntry',
123: 'Bob Dow',
56: 'Charlie Bronw',
20: 'Monkey!',
theMyID: 24
}
so you can easily access any of the data.
alert(success.theKey);
alert(success[123]);
alert(success[56]);
alert(success[20]);
alert(success.theMyID);
*/
//we can iterate through the success JSON!
for(var x in success) {
alert(x + "::" + success[x]);
};
}, "json");
</script>
In the long run - your MUCH better of letting the backend do the backend stuff, and the front end doing the front-end stuff.
What this means is, try keep the HTML generation as far away as possible from the back-end, so instead of constantly passing
for($date = $startDate; $date <= $endDate ; $date = strtotime('+1 day', $date))
{
$dateSelectList .= '<option id="select'.$count2.'" value="'.$date.'">'.date('D d F Y', $date).'</option>';
$count2++;
}
You could perhaps
$date = $startDate;
$myJson = array()
while($date <= $endDate) {
$myJson[] = array("date" => $date, "formattedDate" => date('D d F Y', $date));
$date += 86400; //86400 is the value of 1 day.
}
echo json_encode($myJson);
And you can just do a simple iteration on your HTML code.
<script>
$.get("/", {ajax: true, pid: $('#metaSelect').val()}, function(success) {
//we can iterate through the success JSON!
var _dom = $('#dateSelectDiv').html(''); //just to clear it out.
for(var x in success) {
_dom.append("<option value='"+success[x].date+"'>"+success[x].formattedDate+"</option>");
};
}, "json");
</script>
So as you can see - you can pass alot of data using JSON
Maybe look at some of the documentation to - http://api.jquery.com/jQuery.get/ , http://api.jquery.com/jQuery.post/ - might give you more ideas.
Best of luck to you

Related

FullCalendar: Changing event colors with comparing dates

Recently, ive started tyring out arshaw's fullcalendar. Along the developing journey, i was searching through websites on solution to get the event color to change based on the dates of the event and the current date. This code is written with HTML and PHP with Javascript.
This is an answer to my own questions posts based on what i achieve as there is no similar questions with solutions to this.
So below is my answer and how the FullCalendar looks like.
To clarify, i am using odbc with microsoft Access as database.
My way of doing this is as below:
Events at fullcalendar script
events: [
<?php
include 'connect.php'; //connect to database
function getColor($date) {
$currentDate = date('Y-m-d');
$oneweekDate = date('Y-m-d',strtotime('-1 week')); // this part is to compare with the date 1 week ago
$eventColor = '';
if ($date == $currentDate) {
$eventColor = '#fb8c00';
} else if($date > $oneweekDate && $date < $currentDate){
$eventColor = '#ff0000';
} else if($date < $oneweekDate){
$eventColor = '#696969';
} else {
$eventColor = '#008000';
}
return $eventColor;
}
$sql="SELECT * FROM masterlist1";
$result=odbc_exec($conn,$sql);
while($row=odbc_fetch_array($result)){
$newEnd = date("Y-m-d", strtotime($row['Calibration_Due_Date']));
$color = getColor($newEnd); //store the date from database into a PHP variable and then call the PHP function getColor to get return result
?>
{
title: '--title--', <!--u may get info from fullcalendar.io on the documentations for these parts-->
start: '--start date--',
end: '--end date--',
description : '--description--',
color : '<?php echo $color?>' <!-- this part is where we get the return result from the getColor function and store it into $color variable and then echo it out here for the event color.-->
},
<?php } ?>
],

Get data from database using php,ajax

I have a simple section in which I am displaying data from the database, my database looks like this.
Now I have four buttons looks like this
When a user clicks one of the above buttons it displays this
So now when user eg select construction and next select eg Egypt' in the console and clicks buttonconfirmdisplays [855,599075], user can select multiple countries, this works as expected forconstruction ,power,oil`,
Now I want if user eg clicks All available industries button in those four buttons and next select eg Egypt and click confirm it should display
the sum of egypt total projects in construction, oil, power sector 855+337+406 =1598 and the sum of total budgets in both sectors 1136173
Here is my solution
HTML
<div id="interactive-layers">
<div buttonid="43" class="video-btns">
<span class="label">Construction</span></div>
<div buttonid="44" class="video-btns">
<span class="label">Power</span></div>
<div buttonid="45" class="video-btns">
<span class="label">Oil</span></div>
<div buttonid="103" class="video-btns">
<span class="label">All available industries</span>
</div>
</div>
Here is js ajax
$("#interactive-layers").on("click", ".video-btns", function(){
if( $(e.target).find("span.label").html()=="Confirm" ) {
var selectedCountries = [];
$('.video-btns .selected').each(function () {
selectedCountries.push( $(this).parent().find("span.label").html() ) ;
});
if( selectedCountries.length>0 ) {
if(selectedCountries.indexOf("All available countries")>-1) {
selectedCountries = [];
}
} else {
return;
}
var ajaxurl = "";
if(selectedCountries.length>0) {
ajaxurl = "data.php";
} else {
ajaxurl = "dataall.php";
}
$.ajax({
url: ajaxurl,
type: 'POST',
data: {
countries: selectedCountries.join(","),
sector: selectedSector
},
success: function(result){
console.log(result);
result = JSON.parse(result);
$(".video-btns").each(function () {
var getBtn = $(this).attr('buttonid');
if (getBtn == 106) {
var totalProjects = $("<span class='totalprojects'>"+ result[0] + "</span>");
$(this).append(totalProjects)
}else if(getBtn ==107){
var resultBudget = result[1]
var totalBudgets = $("<span class='totalbudget'>"+ '&#36m' +" " + resultBudget +"</span>");
$(this).append( totalBudgets)
}
});
return;
}
});
}
});
Here is php to get all dataall.php
$selectedSectorByUser = $_POST['sector'];
$conn = mysqli_connect("localhost", "root", "", "love");
$result = mysqli_query($conn, "SELECT * FROM meed");
$data = array();
$wynik = [];
$totalProjects = 0;
$totalBudget = 0;
while ($row = mysqli_fetch_array($result))
{
if($row['Sector']==$selectedSectorByUser ) {
$totalProjects+= $row['SumofNoOfProjects'];
$totalBudget+= $row['SumofTotalBudgetValue'];
}
}
echo json_encode([ $totalProjects, $totalBudget ] );
exit();
?>
Here is data.php
<?php
$selectedSectorByUser = $_POST['sector'];
$countries = explode(",", $_POST['countries']);
//var_dump($countries);
$conn = mysqli_connect("localhost", "root", "", "meedadb");
$result = mysqli_query($conn, "SELECT * FROM meed");
$data = array();
$wynik = [];
$totalProjects = 0;
$totalBudget = 0;
while ($row = mysqli_fetch_array($result))
{
if($row['Sector']==$selectedSectorByUser && in_array($row['Countries'],$countries ) ) {
// array_push($data, $row);
$totalProjects+= $row['SumofNoOfProjects'];
$totalBudget+= $row['SumofTotalBudgetValue'];
}
}
// array_push($wynik, $row);
echo json_encode([ $totalProjects, $totalBudget ] );
//echo json_encode($data);
exit();
?>
Now when the user clicks All available industries btn and selects a country I get [0,0] on the console.
What do I need to change to get what I want? any help or suggestion will be appreciated,
in you dataAll.php
If you have select All available industries
you shold not check for sector because you need all sector (eventually you should check for countries )
so you should avoid the check for this condition
<?php
$conn = mysqli_connect("localhost", "root", "", "love");
$result = mysqli_query($conn, "SELECT * FROM meed");
$data = [];
$wynik = [];
$totalProjects = 0;
$totalBudget = 0;
while ($row = mysqli_fetch_array($result)) {
$totalProjects += $row['SumofNoOfProjects'];
$totalBudget += $row['SumofTotalBudgetValue'];
}
echo json_encode([$totalProjects, $totalBudget]);
You can use the SQL JOIN operator, or in this case an implicit join would be cleanest:
$result = mysqli_query($conn, "SELECT * FROM construction, power, oil_and_gas, industrial WHERE construction.Countries = power.Countries AND power.Countries = oil_and_gas.Countries AND oil_and_gas.Countries = industrial.Countries");
You need the WHERE conditions so it knows how the rows of each different table are related to each other. You can shorten it a bit with aliases for the tables:
$result = mysqli_query($conn, "SELECT * FROM construction as C, power as P, oil_and_gas as G, industrial as I WHERE C.Countries = P.Countries AND P.Countries = G.Countries AND G.Countries = I.Countries");
In this case, however, I think you may want to consider changing the structure of your database. It seems like you repeat columns quite a bit across them. Perhaps these can all be in a single table, with a "type" column that specifies whether it's power, construction, etc. Then you can query just the one table and group by country name to get all your results without the messy joins across 4 tables.
The single table looks OK.
(The rest of this Answer is not complete, but might be useful.)
First, let's design the URL that will request the data.
.../foo.php?industry=...&country=...
But, rather than special casing the "all" in the client, do it in the server. That is, the last button for industry will generate
?industry=all
and the PHP code will not include this in the WHERE clause:
AND industry IN (...)
Similarly for &country=all versus &country=egypt,iran,iraq
Now, let me focus briefly on the PHP:
$wheres = array();
$industry = #$_GET['industry'];
if (! isset($industry)) { ...issue error message or use some default... }
elseif ($industry != 'all') {
$inds = array();
foreach (explode(',', $industry) as $ind) {
// .. should test validity here; left to user ...
$inds[] = "'$ind'";
}
$wheres[] = "industry IN (" . implode(',', $inds) . )";
}
// ... repeat for country ...
$where_clause = '';
if (! empty($wheres)) {
$where_clause = "WHERE " . implode(' AND ', $wheres);
}
// (Note that this is a generic way to build arbitrary WHEREs from the data)
// Build the SQL:
$sql = "SELECT ... FROM ...
$where_clause
ORDER BY ...";
// then execute it via mysqli or pdo (NOT mysql_query)
Now, let's talk about using AJAX. Or not. There were 2 choices:
you could have had the call to PHP be via a GET and have that PHP display a new page. This means that PHP will be constructing the table of results.
you could have used AJAX to request the data. This means that Javascript will be constructing the data of results.
Which choice to pick probably depends on which language you are more comfortable in.

Fullcalendar give the cell background color dynamically

There is a fuvar_status field in my sql table. Now, the fullcalendar cells have a static color.
What i want is: if the fuvar_status is 0, the background will be #ff0000, or the fuvar_status is 1, the bg will be an another color.
How to write this in the, and javascript file?
My php, that gets the records from sql:
<?php
include_once("connect.php");
$sql =
"
SELECT
fuvar.fuvar_id,
fuvar.fuvar_date,
fuvar.fuvar_status,
fuvar.fuvar_kerulet,
gyarto.gyarto_nev,
Varosok.VarosNev
FROM fuvar
LEFT JOIN gyarto ON fuvar.fuvar_honnan = gyarto.gyarto_id
LEFT JOIN Varosok ON fuvar.fuvar_hova = Varosok.VarosID
LIMIT 50
";
// WHERE status != Lezárt fuvar
$get = mysqli_query($kapcs, $sql) or die("SQL ERROR 1 - " . mysqli_error($kapcs));
if(mysqli_num_rows($get) > 0 )
{
$VarosNev = array();
$gyarto_nev = array();
$fuvar_date = array();
$fuvar_id = array();
while( $e = mysqli_fetch_array($get))
{
if($e['fuvar_kerulet'] == "0" ) { $VarosNev[] = $e['VarosNev']; }
else { $VarosNev[] = $e['VarosNev'] .' '. $e['fuvar_kerulet']; }
$gyarto_nev[] = $e['gyarto_nev'];
$fuvar_date[] = $e['fuvar_date'];
$fuvar_id[] = $e['fuvar_id'];
}
$res = array
(
'VarosNev' => $VarosNev,
'gyarto_nev' => $gyarto_nev,
'fuvar_date' => $fuvar_date,
'fuvar_id' => $fuvar_id,
);
echo json_encode($res);
}
?>
Javascript, generate events:
for (i = 0; i < hossz; i++)
{
if (eventArray.fuvar_id[i] != '')
{
valami.push({
title: eventArray.gyarto_nev[i] +'\n'+eventArray.VarosNev[i],
backgroundColor: '#03674e',
start: eventArray.fuvar_date[i],
url: '/fuvar-szerkesztes/' + eventArray.fuvar_id[i]
});
}
else
{
valami.push({
title: eventArray.gyarto_nev[i] +'\n'+eventArray.VarosNev[i],
backgroundColor: '#03674e',
start: eventArray.fuvar_date[i],
});
}
}
There seems to be no particular reason to do half of your processing in PHP and half in JavaScript. You could just make what PHP produces compatible with fullCalendar. You've also using a bizarre arrangement of redundant parallel arrays in PHP, and then relying on the index values to match the values up. Perhaps you aren't aware of PHP's support for associative arrays? You can do it all with one array to create actual events, directly:
$get = mysqli_query($kapcs, $sql) or die("SQL ERROR 1 - " . mysqli_error($kapcs));
if(mysqli_num_rows($get) > 0 )
{
$events = array();
while( $e = mysqli_fetch_array($get))
{
$VarosNev = ($e['fuvar_kerulet'] == "0" ? $e['VarosNev'] : $e['fuvar_kerulet']);
$evt = array(
"title" => $e['gyarto_nev']."\n".$VarosNev,
"backgroundColor" => ($e["fuvar_status"] == 0 ? "#ff0000" : "#03674e"),
"start": $e["fuvar_date"]
);
if ($e['fuvar_id'] != "") { $evt["url"] = "/fuvar-szerkesztes/".$e["fuvar_id"]; }
$events[] = $evt;
}
echo json_encode($events);
}
Then you shouldn't need the for loop in JavaScript at all - you can just send the JSON from the server direct into fullCalendar.
N.B. Obviously I could not test this fully without your data, so apologies for any small errors - point them out if you can't fix them and I will amend the answer if necessary.

Getting values from a PHP associative array using jQuery

I Have a html select element generated in PHP from an array as follows
$countries = array(
array('iso' => 'AF', 'name' => 'Afghanistan', 'key' => 'Red'),
array('iso' => 'AX', 'name' => 'Åland Islands','key' => 'Yellow'),
array('iso' => 'AL', 'name' => 'Albania', 'key' => 'Blue')
);
$select = '<select id="country_select" onchange="countryfind()">';
foreach($countries as $country) {
$select .= '<option value="'.$country['key'].'">'.$country['name'].'</option>';
}
$select = '</select>';
return $select;
The select box uses a small javascript function to displays the country key of the selected country:
function countryfind(){
jQuery('#countrykey').text(
jQuery('#country_select option:selected').val()
)};
I want to now use that key to interface with another PHP array which contain information about the country and display that country in the #countrykey div instead of the selected value:
$si_federations = array(
'Red' => array('name'=>'A Red Country', 'url'=>'http://www.redcountry.com'),
'Blue' => array('name'=>'A Blue Country', 'url'=>'http://www.soroptimisteurope.org'),
);
Is this something that can be easily achieved, or is my approach entirely wrong?
You're on the right track here. So, here's how to get this to do what you want
Within your <script> block we want to output that array in JSON
var federations = <?php echo json_encode($si_federations); ?>;
Now, when you run countryfind we want to pull the value out of that object and display it as well. So let's modify your function
function countryfind(){
var fed;
var selected = jQuery('#country_select option:selected').val();
if(federations[selected] !== undefined) fed = federations[selected];
else fed = {"name":"Default Name", "url":""}; //placeholders if it's not defined
jQuery('#countrykey').text(
selected + ' - ' + fed.name + ' ' + fed.url;
)};
I don't know how you want it displayed (I just dumped it as text for simplicity), but this gets you the data you need so you can take it from there
You have to convert your php associative array into js object for further reference. As php runs on server and you are doing every action on client side so right after page loads, your php is useless. You need js var so that you can reference it further.
Like this:
<script>
var countries = [];
var country = {};
<?php foreach($si_federations as $k => $country): ?>
<?php foreach($country as $key=>$val): ?>
country['<?php echo $key; ?>'] = '<?php echo $val; ?>';
<?php endforeach; ?>
countries['<?php echo $k; ?>'] = country;
<?php endforeach; ?>
function countryfind(){
var keyVal = jQuery('#country_select option:selected').val();
jQuery('#countrykey').text('name: '+countries[keyVal]['name']+' url: '+countries[keyVal]['url']);
}
</script>
I hope it helps

how to load more images from a folder using php jquery ajax

i have multiple folders and all folders contain some images upto 20 images.
in my html page i want to show first 5 images and show click to view more 15
and when the user click that link it will show next 15 images
but till now i can only fetch all the images at a time
here is my code
<?php
$dirname = "img/outlets/".$service_type."/". $outlet_name ."/snaps/";
$images = glob($dirname."*.jpg");
foreach($images as $image)
{
?>
<a href="<?php echo $image ?>" class="imageHover">
<img src="<?php echo $image ?>" class="img-responsive" />
</a>
<?php
}
?>
I am sorry for not being supportive or all but I think you should ask or research about "pagination". What you are asking is a definition of pagination.
Actually you are asking , "How do I implement pagination ?"
http://codular.com/implementing-pagination
http://code.tutsplus.com/tutorials/how-to-paginate-data-with-php--net-2928
and here is some code you can try to implement simple pagination
try {
// Find out how many items are in the table
$total = $dbh->query('
SELECT
COUNT(*)
FROM
table
')->fetchColumn();
// How many items to list per page
$limit = 20;
// How many pages will there be
$pages = ceil($total / $limit);
// What page are we currently on?
$page = min($pages, filter_input(INPUT_GET, 'page', FILTER_VALIDATE_INT, array(
'options' => array(
'default' => 1,
'min_range' => 1,
),
)));
// Calculate the offset for the query
$offset = ($page - 1) * $limit;
// Some information to display to the user
$start = $offset + 1;
$end = min(($offset + $limit), $total);
// The "back" link
$prevlink = ($page > 1) ? '« ‹' : '<span class="disabled">«</span> <span class="disabled">‹</span>';
// The "forward" link
$nextlink = ($page < $pages) ? '› »' : '<span class="disabled">›</span> <span class="disabled">»</span>';
// Display the paging information
echo '<div id="paging"><p>', $prevlink, ' Page ', $page, ' of ', $pages, ' pages, displaying ', $start, '-', $end, ' of ', $total, ' results ', $nextlink, ' </p></div>';
// Prepare the paged query
$stmt = $dbh->prepare('
SELECT
*
FROM
table
ORDER BY
name
LIMIT
:limit
OFFSET
:offset
');
// Bind the query params
$stmt->bindParam(':limit', $limit, PDO::PARAM_INT);
$stmt->bindParam(':offset', $offset, PDO::PARAM_INT);
$stmt->execute();
// Do we have any results?
if ($stmt->rowCount() > 0) {
// Define how we want to fetch the results
$stmt->setFetchMode(PDO::FETCH_ASSOC);
$iterator = new IteratorIterator($stmt);
// Display the results
foreach ($iterator as $row) {
echo '<p>', $row['name'], '</p>';
}
} else {
echo '<p>No results could be displayed.</p>';
}
} catch (Exception $e) {
echo '<p>', $e->getMessage(), '</p>';
}
Simple PHP Pagination script
If I understood you correctly, you want your first page to display 5 images. Then, after clicking on a link, you want the same page to show the remaining images (from 5 up until the number of images in the folder – maybe 20 in your case).
I've been a bit verbose just so that it's clear. I've also left you echoing file paths as your code specifies, but presumably you're going to want to turn these into URLs. I'll leave that to you.
Try something like this:
<?php
$dirname = "img/outlets/".$service_type."/". $outlet_name ."/snaps/";
$images = glob($dirname."*.jpg");
$initial_images = 5; // However many you want to display on the inital load
// Get the starting image and the end image array keys
if($_GET['show_all_images']){ // Check the the browser sent a query parameter
// We've been asked to display more
// Get the array index of the first image. Remember that arrays start at 0, so subtract 1
$first_image_index = $initial_images - 1;
// Get the array index of the last image
$last_image_index = count($images);
}
else{
// We're on the inital load
$first_image_index = 0;
$last_image_index = $initial_images - 1;
}
// Iterate the glob using for. We want to specify an array key, so it's easier here to use for rather than foreach (which is the right solution most of the time)
for ($i=$first_image_index; $i < $last_image_index; $i++):?>
<a href="<?php echo $images[$i] ?>" class="imageHover">
<img src="<?php echo $images[$i] ?>" class="img-responsive" />
</a>
<?php endfor;?>
<?php if($_GET['show_all_images']): // Display a 'show less' link?>
Show less
<?php else: ?>
Show more
<?php endif; ?>
A simple way is to name images to end with indexed. Example being img_1.
You can then use ajax to fetch the last 15 images when user clicks on view more.
But this approach is very basic and is not scalable. As other answers suggest you can mix pagination with indexed image name approach

Categories

Resources