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.
Related
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);
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)
});
})
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?
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.
I have a list of names (1-15 rows) I display from an array. I want the administrator to select the correct name from the list by clicking on the hypertext called "link." The record id is in the array and I want that passed to the called script.
I found this javascript that works except that I want the linkur.php page to print (with its information messages). I know it doesn't print because of the void(0) but can not figure the correct method needed.
<a href="javascript:void(0);" onclick='$.get("linkur.php",{ rid: "<?php echo $k['id']; ?>", uid: "<?php echo $uid; ?>", } ,function(data){ $("#link<?php echo $k['id']; ?>").html(data); });'>Link</a>
Also, is it possible to do the hyperlink with pure HTML? The hyperlink is straight forward except for passing the array values.
Thanks for any ideas.
Carl
I'm a bit confused by your request. You don't mention needing an asynchronous request, yet that is what your code is doing using the jQuery library. If you don't need an asynchronous request, and want to see the end-page, you just build a regular link:
Link
This would be rendered on the page with solid values rather than variables:
Link
Once you clicked the link, you would pass rid=123 and uid=281 to the end-script, seeing its output on the screen.
Properly Adding some Asynch'ness
If you need to load this data asynchronously, there is only a small addition to the code. Keep the original link that we just referenced above, but add a class to it:
Link
Now with jQuery we can incercept these requests and load up their HTML elsewhere:
$(function(){
// Intercept the click event of our links
$(".loadme").click(function(e){
// Prevent them from leaving the page
e.preventDefault();
// Fire off a request for their content
$.get($(this).attr("href"), function(data) {
// Load their content into a container on our page
$("#content-viewer").html(data);
}, "html");
});
});
Note that I referenced a #content-viewer. You would need to have this on your page someplace:
<div id="content-viewer">I will show the content .loadme links!</div>
Your approach is a bit hacky, to say the least. Now you need to have the javascript stuff on every link, whereas the correct way to do it would be to bind the functions separately. You could do something like this instead:
Link
Which would output to the browser as:
Link
And in a separate Javascript file:
$('a.some_links').click(function() {
$("#link"+$(this).attr('rel')).load($(this).attr('href'));
return false;
});
If I understood your code correctly, this will do the exactly same thing – loading the content from linkur.php with passed variables to #link+rid element.