Add strings with ajax from server using phpMyAdmin, jquery - php

Right now, i'm trying to add a couple of <li>, using ajax. The problem is that i'd like these <li> to use data from a database I have on the server. I'd like to know how to do that! Also, is it possible to use jQuery?
Let's say I have a <div id="listHolder">, where I have a <ul> and then some <li>. Those <li> are the ones I want to change via ajax.
I use phpMyAdmin, where I have a database called t_menuMaterials, and I want to retrieve strings inside m_nom.
I'd also want to be able to change the menu, on a click of a button, change t_menuMaterials to t_menuTextures.
I have been able to populate my menu, but only at the load of the page like that!
$requeteMenuMaterials = "SELECT * FROM t_menuMaterials ORDER BY m_id LIMIT 10";
$ressourcesListe = mysql_query($requeteMenuMaterials);
$targetMenu = "SELECT r_categorie FROM t_ressources ORDER BY m_id LIMIT 10";
$ressourcesListe2 = mysql_query($targetMenu);
$menu2 ='';
while($tbl_ressources1 = mysql_fetch_assoc($ressourcesListe)){
$menu2 .='<li class="secondaryMenu"><a href="#" onClick="test('.$ressourcesListe2.');" ><div>'.$tbl_ressources1['m_nom'].'</div></a></li>';
}
Now, I'd like to be able to change the div (like if $requeteMenuMaterials became ="SELECT * FROM t_menuTextures(instead of t_menuMaterials). I have no idea on how to change those <li> via ajax using my databases and phpMyAdmin.

Its difficult to give you exact advice as you only list small parts of your service side code.
But some general guildlines:
Take a look on jQuery, it has support for ajax calls and also a lot of client side plumbing to update elements.
On the server you have to have som separation of the different calls to the DB so that the client via the URL or POST data can tell the service side script what to do.
There is no way from Javascript to directly call some inner part of a php page, you have to call the page as a regular http request and use URL arguments or postdata to have the page return different information.

jQuery $.get is probably what you need. Basically, have a page that pulls the relevant data from the database, and echo it out to your page. So your page (get-li-data.php, for example) might output:
<li>An item</li>
<li>Another item</li>
And use $.get to get that data and insert it into a div, like:
$.get('/get-li-data.php', function(data) {
$('#div-where-i-have-a-ul').html(data);
});

Related

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)
});
})

Use the form values in the php without submitting and without sending query string to other page

All the above code I saved in a page called dum.php
$(document).ready(function(){
$(".sameclass").click(function (e) {
e.preventDefault();
var QS = $(this).attr('href').split('?');
if(QS.length>0){
var val = QS[1].split('=');
if(val.length>0){
$("#edit_prdct").hide().slideDown('slow');
//Below am adding a value to the hidden text filed
document.getElementById('prd_id').value=val[1];
}
}
});
});
I had some products which i want to edit their info EDIT are the hyperlinks with the query string value
<DIV id="list_prdct">
<a href="dum.php?id=1" class=sameclass>EDIT</A><BR><DIV id="edit_prdct">
<a href="dum.php?id=2" class=sameclass>EDIT</A><BR><DIV id="edit_prdct">
<a href="dum.php?id=3" class=sameclass>EDIT</A><BR><DIV id="edit_prdct">
<a href="dum.php?id=4" class=sameclass>EDIT</A><BR><DIV id="edit_prdct">
</DIV>
In the below div I used a hidden field and I want to used its values in the mysql query in the where condition and I will display a form related to that value
<DIV id="edit_prdct">
<?PHP
$prdid"<input type=hidden id='prd_id' value=''>";
// Here I want to use that value of the hidden field as the condition in the mysql query
?>
I am not sure if I got your question correctly, however, this is my try.
Every system has 3 parts: input, processing and output.
Here, your PHP logic is the processing part. It runs on the server and understands only Php. It doesnot know about your HTML, CSS, JavaScript, etc.
Input is provided through HTML and Javascript(JQuery) using a web browser. When you click a link, or submit a form, or make an Ajax call, then browser basically sends an input to the web server (its called a HTTP Request)
Output is again HTML, CSS and Javascript. The statements you echo or print including the ones outside <?php ?> tag, are all output. These are understood by a web browser and not by the server.
To send any data from client side (the web browser) to the server, you need to use HTTP requests. This can be done in 3 ways:
Synchronous Request(href redirects, form submission, sync. Ajax calls, etc)
Asynchronous Request (Ajax Calls).
URL redirections (its a form of way 1 above!!)
All the ways above typically use either the GET method (query strings) or the POST method.
If you dont want to use Ajax or form submission, you are left with only third option, that is, call the resource links directly. For example, redirecting the user to some URL like:
http://www.example.com/products/134
where 134 is a prod_id.
Then on the server side, you will have to retrieve the URL and extract out prod_id from it. This is a tedious task. Fortunately we have some good frameworks to do that, like CodeIgniter, etc. But this is not the way to send data to the server in case you need to fetch data for a list of prod_id.
So, No, there is no other way to get data from server. Perhaps you need to remodel your problem and understand that Php server can't know about your prod_id magically, you need to send it through one of the methods of HTTP request

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.

jQuery updateing multiple #divs, one mysql_query

A bit complicated, but ill do my best to explain my question.
I have a main file, dashboard.html.
Within that I have a jQuery function to load the mysql_query every 15sec to get the 15 or so variables that I need. (This is a financial/sales webapp...the sales agents want near realtime updates of the sales, orders, $earned..etc) which are displayed in a #div with multiple listitems contained within. No issues with this with the approach that every 15sec, query, then entire div is updated all at once. Because of this I have not attached an Jquery effect (namely fadeIn/fadeOut) to it, as then the entire div is constantly fading. Not the visual effect I would like, but as it stands, it works.
My Goal: To be able to do the mysql_query every 15sec. Grab the variables (which Im already doing currently. But now, I would like to be able to update ONLY the ListItem that has changed and attach the fade effect to just that item, not the entire #div as a whole.
What Im trying to avoid is separating out the query to 15 separate querys, as that obviously that is not efficient.
Hopefully that makes some sense to everyone. Code can be provided, but I dont think it will help at this point .. I need to understand what approach I need to go to develop the correct code. Thanks everyone for your anticipated help.
EDIT: Im adding a bit of code to help clarify where I stand:
dashboard.html
var auto_refresh = setInterval(function (){
$('#order_jq').load('stats_count.php')
}, 15000); // refresh every 15 seconds
and then in the body:
<div class="span8">
<div id="order_jq" class="centerContent">
Patiently loading stats ...
</div><!-- End id="ortder_jq -->
</div><!-- End .span8 -->
stats_count.php consists of (stripped down for clarity)
<?php
require "database/connect2.php";
$result = mysql_query( "SELECT .... NORMAL QUERY...NOTHING FANCY HERE")
while ($row = mysql_fetch_array($result))
{$orders = number_format($row['ordercount']);
$annual_order = number_format($row['annual_order']);
}
and lastly contained within stats_count.php I also include the list items:
<ul class="bigBtnIcon">
<li>
<a href="#">
<span class="icon entypo-icon-phone"></span>
<span class="txt">Orders</span>
<span class="notification"><?php echo $orders?></span>
</a>
</li>
<li>
<a href="#">
<span class="icon brocco-icon-mic"></span>
<span class="txt">Auburn</span>
<span class="notification blue"><?php echo $annual_order ?></span>
</a>
</li>
</ul>
-D
If you have multiple divs to be updated, you have to select them with their class ".class" not id "#id"..
To create mysql_query every 15 seconds, you need to make setInterval(function(),15000) where function must make ajax request to some page where to do this query..
I can advice you to use jQuery Ajax for those requests..
Without knowing more details about what format your data is being returned in its difficult to get into specifics but the general approach would be:
store current values into an object,
create a new object with your incoming values
cycle through the properties of the obect comparing incoming values
to existing values
update individual panels (via classes or more specific id's)
turn incoming values object into current values object in
preperation for next sql query
If i understand correctly, this could be done like this :
- all your listitems must have a class attribute let's say "list_items".
- after getting data with Jquery you can do a jquery.each() on the list_items, this way you can check if the value of that list item == the new value if not you update your list item.
I hope this answers a little bit your question.

Ajax and PHP help

Im currently calling a php code that displays results from a mysql db by using AJAX so that the page doesnt reload!
Inside the php code, I am creating a menu where the users can chose to display only "private ads" or "all ads".
Currently, "all ads" are displayed in a div container using ajax as mentioned because I havent implemented the "show private only", which is where I need your help...
Is it possible to use AJAX to check if the user clicks on the "show private only" tab in the php code displayed, and then setting a variable to something and sending it to the SAME php code which then uses the variable to display"private ads" only, WITHOUT making a new query to mysql?
If you need more input just tell me...
SOME MORE INPUT:
This is what I want:
AJAX is used to check search criteria... AJAX sends criteria to PHP... PHP Checks mysql db for criteria and displays in tables, also creates two links, one for "all ads" and one for "private only"... PHP echoes the display tables... AJAX DISPLAYS the tables in a DIV container in the HTML page (innerhtml=blabla)
UPDATE
HERE COMES THE ADDITION I WANT: the users click on one of the links provided by the PHP code, lets say "private only", AJAX reacts and calls PHP code again ... PHP code this time displays the tables differently, filtering out all non-private ads... AJAX displays in the div container...
Is this possible, if so could you point me in the right direction please!
Thanks
If I understood correctly you want do filtering on your ads by a criteria. This could easily be done without a second query in php code. Just change your html code to add a class in advertisement entry that describes the category. Then add the buttons that will filter out the unwanted.
HTML:
Display all ads
Display normal ads
Display private ads
<div id="ads">
<ul>
<li class="normal">Advertisment 1</li>
<li class="normal">Advertisment 2</li>
<li class="private">PRIVATE Advertisment 1</li>
<li class="normal">Advertisment 3</li>
</ul>
</div>
<!-- Then add the following code to capture click events -->
<script type="text/javascript">
$(document).ready(function()
{
$('#normal_ads').click(function()
{
$('#ads li:not(.normal)').hide();
$('#ads li.normal').show();
return false;
});
$('#private_ads').click(function()
{
$('#ads li:not(.private)').hide();
$('#ads li.private').show();
return false;
});
$('#all_ads').click(function()
{
$('#ads li').show();
return false;
});
});
</script>
This was written from mind, I will cross-check it right away. OK it works.
The advantage of this is that you want have to re-query for every click of the user as all advertisements will sent the first time and JavaScript will filter out the unwanted. You can also add some effects in the show/hide through jquery's effects.
The php should just be outputting the form, so the javascript can definitely check what the form value is before sending and/or displaying the ads and do filtering based on the form value (or letting the server side of the AJAX request do the filtering).
If I understood your question correctly, you could implement it with JQuery with ease.
HTML:
Display normal ads
Display private ads
<div id="ads"></div>
JQuery:
$(document).ready(function()
{
$('#normal_ads').click(function()
{
$('#ads').html("").load("ajax_ads.php?normal=1");
return false;
});
$('#private_ads').click(function()
{
$('#ads').html("").load("ajax_ads.php?private=1");
return false;
});
});
Just add a token to the URL string which the XmlHTTP request goes to?
In other words "my.server.script.php?ads=all" or "my.server.script.php?ads=private" and examine your request variables in the PHP script to determine what to return.

Categories