Ajax and PHP help - php

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.

Related

codeigniter - how to redirect to default index page when user submits form that's embedded in menu

Background Information
I have a php web application that uses a template approach to my pages.
So in other words, I have a header.php, footer.php and a leftnav.php.
Each view in my php app includes all three pages listed above.
So far, so good. Everything works.
As a part of my leftnav.php, I have the following code:
<div class="input-group custom-search-form">
<input type="text" class="form-control" placeholder="Quick Search..." id="searchtext">
<span class="input-group-btn">
<button class="btn btn-default" type="button" id="qsearch">
<i class="fa fa-search"></i>
</button>
</span>
</div>
The idea is to provide the users with a "quick search" option that they can use where ever they are in the application... It always shows up because every page includes the same menu stored in leftnav.php.
Problem
This code works fine ONLY if you launch my app and trigger the search right away. But if you navigate away from the default controller, and then the user tries to run the search... nothing happens because they're not in the default controller.
So for example, here's the default URL when you launch my web app:
http://myserver/testapplication/index.php
From here, you can run the quick search and the dashboard controller kicks in.
But from somewhere else like this:
http://myserver/testapplication/index.php/widgets/addwidget
the search button does nothing.
Question
I don't know how to set up my code so that whenever the user clicks on the search submit button, the first thing that happens in the system redirects to the dashboard controller.
The logic that actually runs the search is in my default controller, called "Dashboard". The controller looks like this:
public function index()
{
$data['main_content'] = "dashboard";
$this->load->view('includes/template',$data);
}
public function quicksearch()
{
//grab search text
$seg3 = $this->uri->segment(3); //hardwaremodel
$searchresults = $this->dashboard_model->quick_search($seg3);
$retval = array();
foreach ( $searchresults as $id => $value )
{
//logic to build results array
array_push($retval, $temp);
}
echo json_encode($retval);
}
}
And the view that includes the logic to display the search results is in the "dashboard.php" file.
$(document).ready(function(){
$(".searchresults").hide();
$('#qsearch').click(function(){
$('#qsearchresults tbody').empty();
var searchstring = $('#searchtext').val();
var searchurl = "<?php echo site_url('dashboard/quicksearch/');?>" + searchstring;
$.ajax({
url:searchurl,
type:'POST',
dataType:'json',
success: function(res) {
if (res.length > 0) {
var htmlstring = "<tr><th>ID</th><th>PH</th><th>Site</th><th>Location</th><th>Department</th><th>Description</th><th>Fax?</th><th>Last Assigned Date</th><th>Score</th></tr>";
for (var key in res) {
tmpurl = "<?php echo site_url('did/getdidbyobjid/')?>";
//bunch of logic to build html string with search results
}
$('#qsearchresults tbody').append(htmlstring);
$('.searchresults').show();
}
},
error: function(xhr, req, err) {
var err = eval("(" + xhr.responseText + ")");
console.log(err.Message);
}
});
});
});
EDIT 1
I tried to put all the javascript that handles the search button click event into a separate js file called qsearch.js.
qsearch.js is now included in the header.php... which in turn in included by all views.
<head>
<script src="<?php echo base_url(); ?>assets/l/js/qsearch.js"></script>
</head>
Test
This works: (because it's launch the default controller Dashboard)
http://myserver/myapp/index.php/
But let's say i go to:
http://myserver/myapp/index.php/reports/dept
the search IS WORKING... but it has no where to display the results.
The javascript that handles the search click event does this in part:
$('#qsearchresults tbody').append(htmlstring);
"htmlstring" contains the results of the search... but not all pages have the html table called qsearchresults.
So I guess I need to know if it's possible to redirect the user to the dashboard controller and then run the search.
If not, no worries. I will redo the code and use a static form inside the leftnav.php menu. But I'm so close, I'd like to leave it as is... if possible
I found this link: How to redirect on another page and pass parameter in url from table?
and I'm trying to see if I can adapt it to my use case.
First of all, the form and ajax will only work if your JS is included on every page (which it appears you are only adding on the dashboard from your description). This is easily achieved in a slight customization to the way your template system works, you do not have to add it to every controller.
However, I would suggest you actually use a form with form_open and a submit button styled in any way that suits. The submit button will then submit to your search controller from any page. Having a dedicated non-ajax search results page allows you to do lots of things very easily, without worrying about loading the same js on every page, and disabling it on pages where you do not have the search.
A dedicated search results page is actually very user freindly. The form_open will also give you xss protection if you have that enabled by adding the hidden xss code that will be updated on every page.
You can read about it here: http://www.codeigniter.com/user_guide/helpers/form_helper.html
One of the benefits is that you can show a more complex result set. For instance for a shop you can show exact matches, suggested matches, matching categories, matching sub-categories etc in a layout that is user friendly and easily understood. You can then develop that page to provide more and more information that you think your visitor wants. Ajax, in this situation, might not be the best answer.
A better use of ajax here might be to create a list of clickable search terms that appears when they start typing, which gives you the benefit of suggesting searches that actually produce good results rather than some of the weird searches users actually do.
I have rattled on a bit here but I hope this helps in some way.
Paul.

Pass the information of tags to the php and display in another page( and can also update in another page)?

I am working on a tag system:
1.you can select some tags from a list and display them in a tag container (the tag can be selected only once and the sum is limited to 10), and different tag has different colors.
2.you can delete some selected tags in the tag container
3.pass the information to the php and store in the database.
4. display the tags in another page and you can update the selected tag list in this page.
For now the first two steps has finished by javascript but I am quite confused how I can pass the selected information to the php and the database (the content and colors) so they can be displayed and updated in another page.Anyone can give me some suggestions? Thanks.
The link to the jsfiddle is http://jsfiddle.net/V9Euk/1015/
Here is the html:
<ul>
<li data-val="300"><span class="label label-morning">Morning</span></li>
<li data-val="301"><span class="label label-afternoon">Afternoon</span></li>
<li data-val="302"><span class="label label-evening">Evening</span></li>
</ul>
<div class="tagHandler">
<ul class="tagHandlerContainer" id="tag_handler">
</ul>
</div>
here is the javascript:
$(function(){
var tags = [];
function add_tag(that){
var tag = $(that).text();
if($.inArray(tag, tags)>=0|| tags.length >= 10) return;
tags.push(tag);
var singleValues = $(that).find('span').clone();
singleValues[0].innerHTML += "&times";
$("#tag_handler").append(singleValues);/*display the selected tags in the tag_handler with &times style*/
}
$("li").click(function(){
add_tag(this);
});/*add tags to the tag_container when click the li*/
$('#tag_handler').on('click', 'span', function(){
var tag = $(this).text();
var index = $.inArray(tag, tags);
tags.splice(index,1);
$(this).remove();
});/*remove the tag when click this tag in the tag_container*/
});
First of all the jsfiddle link doesn't work for me.
Now, the only way is to use http methods like POST/GET to pass the data from client to server. The implementation depends of what you like the most or better a friendly and easy to use interface, so my suggestions are:
You can create (dynamically or not) a form (with hidden fields for example) and update their values with JS and pass the data through a submit button which is an easy implementation.
An another implementation is to use Ajax if you take care of user selection and create the data structure dynamically.
In both cases, you should validate the correctness of the submitted data with php. Never trust the user or the "supposed" JavaScript restrictions.

Use Jquery to prevent page reloading pressing anchor

I am trying to use the jquery to Prevent page realoading. I have the whole code php done... and is functional. if you can please go to http://www.jonathansconstruction.com/gallery3.php and click on the different gallery SUbmenus for category View All, Kitchen etc... i'm using get for variables. However, I would like to use a jquery to process the php so i dont have to include it into the gallery.php and also, to prevent page reloading because it brings the page back up and that could be confusing. Any hlep willl be greatly appreciated THanks
UPDATE, Thanks for everyone that helped:
SO far i made an advance on the website, Corrected URL was edited on top of the post
Everything is working smoothly on the effects of quicksand.. HOwever, Lytebox Doesn't Load when a quicksand effect is placed. , at the beginning it loads just fine, but right after pressing one of the menus for the quicksand effect. It stops working. Also, I want to style my menu buttons as is in http://www.jonathansconstruction.com/gallery.php. I see jquery doesnt add and witht the sample I downloaded. and also the that says "gallery Pictures" dissapears ont he quicksand demo.
Any Help is appreciated. Below is the script.js code I have modified so far
$(document).ready(function(){
var items = $('.photo_show figure'),
itemsByTags = {};
// Looping though all the li items:
items.each(function(i){
var elem = $(this),
tags = elem.data('tags').split(',');
// Adding a data-id attribute. Required by the Quicksand plugin:
elem.attr('data-id',i);
$.each(tags,function(key,value){
// Removing extra whitespace:
value = $.trim(value);
if(!(value in itemsByTags)){
// Create an empty array to hold this item:
itemsByTags[value] = [];
}
// Each item is added to one array per tag:
itemsByTags[value].push(elem);
});
});
// Creating the "Everything" option in the menu:
createList('View All',items);
// Looping though the arrays in itemsByTags:
$.each(itemsByTags,function(k,v){
createList(k,v);
});
$('#gallery_menu nav a').live('click',function(e){
var link = $(this);
link.addClass('current').siblings().removeClass('current');
// Using the Quicksand plugin to animate the li items.
// It uses data('list') defined by our createList function:
$('.photo_show').quicksand(link.data('list').find('figure'), {adjustHeight: 'dynamic'} );
e.preventDefault();
});
$('#gallery_menu nav a:first').click();
function createList(text,items){
// This is a helper function that takes the
// text of a menu button and array of li items
// Creating an empty unordered list:
var ul = $('<ul>',{'class':'hidden'});
$.each(items,function(){
// Creating a copy of each li item
// and adding it to the list:
$(this).clone().appendTo(ul);
});
ul.appendTo('.photo_show');
// Creating a menu item. The unordered list is added
// as a data parameter (available via .data('list'):
var a = $('<a>',{
html: text,
href:'#',
data: {list:ul}
}).appendTo('#gallery_menu nav');
}
});
ANOTHER EDIT :
All Looking good So far Fixed Lot of problems, However, for some reason, the span I had on teh static html dissapears from display and even html code when loading jquery quicksand code..?? Here is the code i have on the html part of the website that Does Not appear on the live website for some reason.
<div id="portfolio">
<div class="photo_show"><span>Gallery Pictures</span>
the span part doesnt appear, dont know why
I had the TOp Part Resolvd. just moved the on top of photo_show div and edited positioning... HOPEFULLY Last Edit
the jquery for quicksand made my calendar dissapear, checked and yes it was some jquery conflict but dont know what can be causing it.. also the form validation not working as well ... any help is appreciated!
I visited your webpage link after correcting a typo in the URL for word construction.
I also see the problem that the page reloads when clicking on a sorting filter such as View All, Kitchen, and Miscellaneous which is what you want to prevent.
Unfortunately, those buttons are using URL Links asking to reload the webpage with a filtered option via query string. Nothing can be done for that method of filtering, your just going to reload the webpage since filtering is done on page load.
Perhaps this DEMO shows what you want to accomplish since it does not reload the webpage. That demo has markup that is easy to create and maintain which is build using the Quicksand jQuery Plugin. The tutorial for that demo is accessed using the link at the bottom right, but looking at the source HTML file shows how simple it is.
I made a downloadable demo using both Quicksand and Shadowbox, a lightbox alternative HERE, which might interest you since your webpage is linking the filtered icon results to a lightbox alternative named Lytebox.
Since your edit reflects your interest in Lytebox, the following markup will reinitialize that lightbox alternative after a filtering event has occurred with Quicksand. Update your script.js file accordingly.
$('.photo_show').quicksand(link.data('list').find('figure'), function(){
adjustHeight = 'dynamic';
initLytebox();
});
I also made a correction to your existing adjustHeight since it was using a semicolon instead of an equal sign, but the correct location and use of that is for something unrelated.
The reason that you are not seeing the bullets is because your not using ul/li tags that the demo is using.

Add strings with ajax from server using phpMyAdmin, jquery

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

PHP variable as part of a jQuery function doesn't work, but plain text does

I have the following jQuery code in my PHP file (edited Jan 19 2010 # 10:40 MST):
<?php
$count = 0;
foreach($attachments as $attachment) :
echo '<script type="text/javascript">
$(\'#a_'.$count.'\').click(function() {
$(\'#d_'.$count.'\').show(200);
});
// if "no" is clicked
$(\'#d_'.$count.' .no\').click(function() {
$(\'#d_'.$count.'\').hide(200);
});
// if "yes" is clicked
$(\'#d_'.$count.' .yes\').click(function() {
$(\'#d_'.$count.'\').hide(200);
// update database table -- this is why I need the script inside the for loop!
var jsonURL = \'http://path/to/update_db_script.php\';
$.getJSON(jsonURL, {\'post_id\' : '.$attachment->ID.'}, function(data) {
alert(\'Thank you. Your approval was received.\');
});
$(\'#a_'.$count.'\').replaceWith(\'<span>Approved</span>\');
});
</script>';
echo '<li>';
if($attachment->post_excerpt == 'approved') {
// Check the proof's status to see if it reads "approved"
echo '<span>Approved</span>';
} else { ?>
// If not yet approved, show options
<a class="approve" id="a_<?php echo $count; ?>" href="#">Click to Approve</a>
<div class="confirm-approval" id="d_<?php echo $count; ?>">
<p>Please confirm that you would like to approve this proof:</p>
<a class="yes" href="#">Yes, I approve</a>
<a class="no" href="#">No, not yet</a>
</div><?php
} ?>
</li>
<?php $count++;
endforeach; ?>
The page in question is available here. The "click to approve" links do not work (that's my problem).
When I view source, the PHP variables appear to have echoed properly inside the jQuery:
<script type="text/javascript">
$('#a_0').click(function() {
$('#d_0').show(200);
});
... etc ...
</script>
This looks correct, but nothing happens when I click any of the links. However, when I replace the PHP echo statements with plain numbers (0, 1, etc.) the click functions work as expected.
You may be asking: why on earth do you have this inside a for loop? The reason is that I need to retrieve the attachment->ID variable and pass it to an external PHP script. When someone clicks "approve" and confirms, the external script takes the attachment->ID and updates a database value to read "approved".
Why won't the click function fire when PHP is in place? Is there some kind of greater force at work here (e.g., hosting limitation), or am I missing a fundamental piece of how PHP and JavaScript interact?
Since you didn't post your HTML its a little hard to troubleshoot.
First, I am not sure why one is working and the other is not since the code it is outputting looks correct. Either way, I still would make some changes. Move your a_0,a_1, etc and d_0,d_1, etc into the id attribute instead of a class:
<div>Click Me</div>
<div class="confirm_approval" id="d_0">Show Me</div>
<div>Click Me</div>
<div class="confirm_approval" id="d_1">Show Me</div>
Now, instead of outputting your code in a loop in PHP, place this jQuery code once on your page:
$(document).ready(function(){
$("a.approve[id^='a_']").click(function(e){
var id = this.id.replace('a_',''); // Get the id for this link
$('#d_' + id + '.confirm-approval').show(200);
e.preventDefault();
});
});
This code finds any a element with the approve class that has an id that starts with a_. When this is clicked, it grabs the number off the id a_0 = 0 and uses that id to find the confirm-approval element and show it.
Since the javascript is run on the client and has no way of knowing whether the script was generated using PHP or not, I think that particular part is a wild goose chase...
When I replace the PHP echo statements
with plain numbers (0, 1, etc.) the
click function works as expected.
Do this again and compare the actual output using view-source in a browser. I'll bet you find that there is a difference between the working and failing scripts, other than one of them being generated by PHP.
It seems that the problem is in jQuery selectors. Instead of dynamically binding click() events on multiple objects with an output of PHP code, use just one class selector and bind to objects with this class. And you can specify an id attribute to make them unique.
Something strange too is to have the script tag and the
$(document).ready(function()
in the loop. I don't know if this causes any problems, but it's sure not very efficient, one time is enough.

Categories