values of one combo box on basis of other combo box - php - php

i have two tables categories and sub-categories in database.
On my form i have two combo boxes category and sub categories. Now i want that when i change category, subcategories should change accordingly. I can do it if arrays are defined in javascript. but in my case subcategories are to load from database on the basis of value of category selected. i can fetch data from database using php. if data is in php array how will i pass it to javascript. how can i solve this problem without ajax? if the solution is JSON then how can i implement json as i never used it.

The PHP code is server-side and it's evaluated first, client-side code (like Javascript) is processed after. So you'd have to pre-fetch all the data you need to switch between through PHP so you can manipulate them via javascript.
EDIT:
example:
<?php
$arej[]="one";
$arej[]="two";
$arej[]="three";
$arej[]="four";
?>
<script type="javascript">
var jarray = new Array;
<?php
for($i=0;$i<count($arej); $i++){
echo "jarray[$i]='".$arej[$i]."';";
}
?>
</script>

Either you put all your subcategories in your JavaScript or you'll have to use Ajax.
It's very easy to pass data from PHP to JavaScript. If you have your subcategories in the array $subcategories you can use the result of json_encode($subcategories) safely in your JavaScript (it - o wonder - JSON encodes your array).
So either you make an Ajax service which returns a specific subcategory or you write a PHP script which generates a JavaScript array containing all subcategories.
A simple Ajax service could look like this:
$id = (int)$_GET['category']; // The id of the category
$subcategories = ... // Fetch array of subcategories from db
echo json_encode($subcategories);
So everytime the user click on another category, your JavaScript has to make an Ajax call to the script above, specifying the new category id.
If you use jQuery, doing Ajax is very easy.
$.ajax({
url: "subcategories.php?cat=123",
success: function(encoded){
$("#output").append(encoded);
}
});
(The example above more or less comes directly from the jQuery docs.) To parse JSON in JavaScript you could use eval(), but that function is evil. Better use JSON.parse() or the jQuery alternative.
var subcategories = JSON.parse(encoded);
Now the variable subcategories contains exact the same datastructure as your $subcategories in the PHP script contained.

Related

Get DB content into dropdown and show DB info from selected dropdown

My problem is that i have 2 dropdowns that get its content from my DB, a simple SELECT * with the category and then select a item from that category.
First dropdown : "dropdown_type" is the category.
Second dropdown : "dropdown_abo" is the item.
At the second dropdown, i am using a JQuery pluging that makes it possible to search inside the dropdown, to get the item faster then scrolling (theres gonna be a lot of items in it). You can see the plugin here
When you select a item from the second dropdown, a div(abo_info) below shall show all the info of the selected item.
My problem is that I'm stuck, and don't know how to proceed. How can i make it so, when i select a category, and then an item i get the content from that item shown in the div below?
I'm using PHP, JQuery and Mysql_*(to DB connect, know about PDO but im not that good at it).
Can i please get some help here, or some examples on how it can be done?
I have made a JSfiddle so you can see the complete code
You seem to be headed the correct way and doing a good job of it.
Please proceed further by using the following steps as a guideline,
Using jQuery.ajax() or jQuery.post() you can basically send a request to a PHP file.
In the PHP file you can connect to your DB using either PDO or normal mySQL connectors and return your required data back to the AJAX call.
The returned data can be rendered and displayed as required at the HTML sections.
Please use these following references that can give you a better idea code wise:
Beginner’s Guide to Ajax Development with PHP
jQuery Ajax POST example with PHP
as #WisdmLabs mentioned, you are on the right track...
The steps to continue shouls be:
Add a JS event once both dropboxes were selected (using onchange() or a submit button)
The event will fire an AJAX request for a PHP file with the POST
data of the item you want to get the data for.
On the PHP file you will run your SQL query and send back the information needed- preferable as in json.
On the JS AJAX function you will get the Json object and inserted neede info into the page DOM
JS Code
$(".dropboxClass").change(function(){ // you can use a button instead or any other event type
// here you can first check that bothdropboxes were selected
// now get the values of the dropboxes
drop1 = $("#dropbox1").val();
drop2 = $("#dropbox2").val();
// run the AJAX request for the PHP file
var request = $.ajax({
url: 'test2.php',
dataType: "json" ,
method: "POST",
data: { d1: drop1, d2:drop2 }
});
request.done(function(itemData){
// here you will get the Json object , get the data you need and insert into the DOM
console.log('Status:' + itemData['status']);
console.log('Name:' + itemData['name']);
alert('success');
});
request.fail(function(){
// AJAX call failed - do something.....
});
});
PHP Script
// connect to your DB and get the data you need into an array
$DB_data = array(
"status"=>"code",
"name"=>"item Name",
"desc"=>"Item Description"
);
echo json_encode($DB_data);

Implementing Filtering content using jquery ajax and php

I had implemented multiple checkbox filtering for a job portal using jQuery where in I was calling a function every time a checkbox is checked and that function contained an ajax call which would send the request with the checked values and I would do the querying of database and return the result.
But one of the developers I meet told me you should not hit the database continuously for filtering, it should be done client-side.
He also suggested to use AngularJS or Knockout(js) for the purpose, as they work on content, whereas jQuery works on DOM elements.
But if it has to be done client-side, all of the data must be loaded at once during the first visit to the page, which in turn would slow down the page.
And I cannot use class on each element and show/hide them based on the checkbox ID or value something like that, because there are a lot of checkboxes, which I think will be hectic to handle.
How to achieve the desirable result with good performance?
I'm a Newbie to jQuery, so if I have gone wrong anywhere bear with me.
Below is the sample way in which I have actually done:
HTML:
<input type="checkbox" name="location[]" value="Bangalore" onclick="loadresult()">Bangalore
JS:
function loadresult() {
location array value accessed and passed to ajaxcall
//ajax call to processresult.php
Displaying the DB returned Data
}
PHP (processresult.php):
<?php
//dbconnection + querying db and returning result
?>
There is significant difference. Angular is a framework and jQuery is a library.
With jQuery it much simpler to modify DOM elements deal with events and do some more cool stuff. But you define how you deal with data on your own. You can easily move your data to Js object or array of objects and render this data to your DOM tree.
For example:
//let's presume that you are searching something
var someUsers = [{id: 1,name:'User 1'},{id: 2,name:'User 2'},{id: 1,name:'User 3'}];
var usersTemplate = _.template("<h1>User name: <%= user.name %></h1>");
var $container = $('#someRenderContainer');
someInputFeild.on('keypress', function(){
var searchText = someInputFeild.text();
var foundUsers = someUsers.filter(function(item, index){
item.name.indexOf(searchText) !== -1
});
render($container,foundUsers);
})
function render($container,users){
users.forEach(function(item){
$container.append(usersTemplate(item));
})
}
Here is simple example where you can see that your manipulate with data in the memory but not in DOM. Similar things you can do with your checkboxes.
I would just make one ajax request in the beginning, fill the page with data, marking every row with class name
jQuery.each(d, function(i,data) {
$("table.content").append("<tr class=\""+data.city+"\"><td>" + data.tag + "</td><td>" + data.city + "</td><td>" + data.num + "</td><td>" + data.state + "</td></tr>");
});
and use checkboxes to hide and show marked rows using jQuery hide(), show() methods.
Rows can have multiple classes meaning filtered by multiple columns, but logic will get more complicated.
see example http://jsfiddle.net/elshnkhll/czdongkp/
I would use cache technique to improve my performance.
We can't load our full record on a single page. It will slow down the main page loading.
But we can save loaded data in a variable with some key combination for different filter and page no..
eg. if we are loading data fir index page with no filter, the my key will be index and my variable will be like var cachevar = {"index":{1:"<my response>"}}, here "1" is page number
And if data is using filter, then my variable index key will be combination of filter ids saperated by '-'.
eg var cachevar = {"index":{1:"<my response>"}, "index-2-5-3":{1:"my response"}}
If user request a page, I just have to check if that page is available in cache or no, if it's available in cache variable, then show it, else request it from server.

To perform ajax functioning with jquery

Simply, I have an <a> tag having values(ID) which will be posted to the same page in clicking,
I wanted to load data into the table based on the ID provided by the post method. On the other hand I am having a clock which is rested again and again when fired a post method.
I simply wanted to do the same via jQuery.
In short I wanted to Implement ajax using jQuery
Also I am using database MySQL, with PHP scripting
Any sort help will be appreciated.
<a class="D" href="?ID=<?php echo $rows[0]; ?>" onclick="">Question<?php echo $QNo; ?></a>
I wanted the same above and get ID for searching relevant data against the ID.
I might be wrong here, but you basically want to query a PHP page based on an ID and display relevant content in a div?
To make an AJAX call, setup a PHP page that will query your database and in turn return HTML data which you can then display in a DOM element.
A very simple example of this would be:
HTML
Load table 1
Load table 2
<div id="contentToPopulate"></div>
jQuery:
$('a.linkToLoadTable').click(function(){
var pageId = $(this).data('tableId')
$.ajax({
url: 'loadTable.php?id='+pageId
}).done(function(data) {
$('#contentToPopulate').html(data)
});
})

jQuery context menu filled with php content based on selection

When a user selects a word in a text on my website (PHP), and then right clicks, i want a jQuery context menu to come up, this can be done by using one of the already existing jQuery context menu plugins.
But besides the options like copy / paste / cut, etc. I also want something to be done with the selected word using PHP. Which, i think, is a little harder.
For example using this script:
$selection = //the selected word or text
$target = //fetch from MYSQL database
$output = array();
while ($row = //fetch $target) {
If ($selection == $row->input) { array_push($output,$row->output); }
}
echo '//menu '.print_r($output).''; // of course not print_r! Just for the example's sake.
Databse example:
(Sorry for the oversized image)
Ok so selecting the word 'lazy' in the example text, and then right clicking, the jQuery box should pop up showing the results from the database extracted by PHP.
Example:
Ok, so i know you can't just combine javascript with PHP and it can only be parsed, but i thought loading an iframe withing the menu, which does the database extraction would do the job by using javascript to set the iframe src containing the selected word in the url.
However, iFrames are not really a nice way to solve this.
The question: How can i do this effectively? Execute this script on right-click and show the database-related content in the menu?
I would need to know the plugin you're using to give you some code examples but, general, I would go about this like this:
There has to be a click handler on the items in the jQuery context menu. Use it to submit an AJAX request to the server when the "selection" term is clicked.
Make sure to give the user some feedback (a loader or spinner)
Put the results into an array server-side.
JSON encode the array and send it as the response (e.g. echo json_encode($output)
JSON.parse(response) on client-side and you now have a JS object with the results
Put those results in the context menu (again, how depends on the plugin you're using)
AJAX is a great way to do what you want.
Here is a simple AJAX example. Note that in the 2nd .PHP file, that is where you put your database lookup etc.
Whatever you echo from the 2nd script is received by the calling javascript (first script again) and can be inserted into your context menu on-the-fly. Here is another example with a very detailed, step-by-step explanation of the process at the bottom of the answer.
I think you have to use Ajax to get JSON from a PHP file, which you would process on the actual page.
I you create a PHP file called test.php, with the following in it:
<?php
echo json_encode(array('time' => time(), 'hour', date('H')));
?>
Then the Javascript:
<script>
$('#curr_menu_entry').click(function() {
$.getJSON('test.php', function(data) {
$.each(data, function(key, val) {
$('#curr_menu_entry').append('<li id="' + key + '">' + val + '</li>');
});
});
});
</script>
Would that work?

Updating list items using PHP and AJAX

I'm trying to make 2 lists where one lists is updated depending on what the user choses from the first list.
The first list is made up of "lists names"... every "list" that is made by a user contains a number of movies,...
So for example I would make a list: Top 5 fav movies and when I click on it in my first list on the second list it will show the lists of movies that are in that list.
I know I also need to use Ajax to make this happen but I'm stuck. I'm able to create the first list from my database but I don't know how to go any further?
<ul class="MyLists">
<?php
$MyList = new Lists();
$res = $MyList->GetMyLists();
foreach ($res as $r) {
echo "<li><a href='mylists.php?id=".$currentID."&listname".$r['list_name']."'>". $r['list_name'] . "</a></li>";
}
?>
</ul>
<ul class="MyLists">
<?php
<li>Here are items of the selected list</li>
?>
</ul>
I put the name of the list that the user chose in the "href" section as you can tell so that I might be able to get this with a $_GET method. But I been trying and I haven't gotten this to work.
Also any reference to usefull AJAX tips are more then welcome.
Thanks in advance and for your time.
This is my approach when I do something like this.
First when generating the links in php I give each link element a data attribute, like:
<li><a data="<?php echo $id; ?>">List Title</a></li>
The $id can be anything that identifies the list and it's elements. Something that you can use on the php side of things to extract the data that you need. Now in your javascript with jQuery you can do a simple ajax call like so:
$(document).ready(function(){
$('a').click(function(){
var id = $(this).attr("data");
$.ajax({
url: 'getlistitems.php',
type: 'GET',
data: {id:id},
success: function(data){
//I'll talk about what goes in here in a bit
}
});
});
});
Let be break down what is going on. So basically when you are clicking on a link element the jQuery is extracting what you saved in the data attribute of the specific link that was clicked (with $(this)) to pass to you PHP file in the ajax call. The 'url' parameter of the AJAX call is the php file that is going to extract the data from your database, or however it is saved. The 'type' parameter is the HTTP method you are using. The data parameter here is a json object that will get put into the $_GET global server side.
Now in your php file you will simple extract your data using the supplied id, referencing like $_GET['id']. I don't know how your data is saved so I cannot get very specific here but you could easily structure a MySQL query here to get the items prevalent to list that was clicked. Now you just have to get this data back to your client side browser. Thankfully this is very easy using php's built in json_encode() function. Simply save all of your list items to an array and supply that array to json_encode() and echo it out like so:
$listitems = array();
//add all relevant items to $listitems
echo json_encode($listitems);
Now here is where that success: function(data){} parameter in the ajax call above comes into play. That json_encoded($listitems) parameter will be the data parameter to the success callback. It is even turned into a usable array for you. So now all you have to do loop over the data array and append it to the second list using jQuery append and you will be all set.

Categories