jQuery + ajax livesearch - php

I am doing a mysql database search and retrieving some results via ajax livesearch using the example on w3schools and i want to manipulate those results (drag and drop them) but im having a problem because the script loads before you enter the search and get the results so it does absolutely nothing no the search results. Any thoughts on this matter ?

Ah - thanks for the clarification.
The elements you want to drag are being created after the drag/drop initialization. You need make them draggable:
for example, add 'dragMe' as a class to the items. Once the list is populated from the server, then make those items dragable:
$('.dragMe').draggable();
I would really look into jQuery's ajax functions and their autocomplete
To clarify and for jquery (against your cited example):
function showUser(str)
{
$.get( 'getuser.php', { q: str },
function(data) {
$('#txtHint').html( data ); // add the returned content to #txtHint
$('#txtHint').find('.dragItem').draggable(); //make the new items draggable
}, 'html' );
}
In your php, change your display so it is blocks that can be dragged.
while($row = mysql_fetch_array($result))
{
echo "<div class="dragItem">"; // see how we're adding the 'dragItem' class?
echo "Firstname " . $row['FirstName'];
echo "</div>";
}
past that, you'll really want to do some more research to get a better idea of whats going on.

Related

pass sql query result to another php page (that is contained in a div) to run another sql query - all on the same page, with ajax

Objective:
Pass sql query result to separate php file that uses that result to run another sql query.
I have an sql query that lists a few rows of data. I want one data piece of the row as a link. When that link is clicked, that data is passed to another php page that runs an sql from that passed data.
Currently have an ajax script that updates content in a separate div on the same page as the original sql query. Basically my sql lists basketball players info. Name, height, weight, position. I want to click the players name and have a separate php file pull up more data based on the players name.
What I have to create the column with the players name:
echo
"<td><a href=javascript:void(0); onClick=getdata('/players/player1.php,'content');>".$players['first_name']." ".$players['last_name']."</a></td>";
How do I pass the name to a separate php file? Thank you!
A couple of errors in your HTML: the attribute data needs to be wrapped in quotes, and you have a missing single quote:
echo
"<td><a href='javascript:void(0);' onClick='getdata(\'/players/player1.php\',\'content\');'>".$players['first_name']." ".$players['last_name']."</a></td>";
So, knowing that, you've obviously not written the getData function?
Assuming that you haven't, and assuming you're a beginner, I'd encourage you to look at jQuery as this will simplify a lot of what you are doing. (It can be done in JavaScript without jQuery if that's what you prefer, but this is simpler.)
Your HTML will be
echo
"<td><a href='#' class='js-load-more' data-playername='" . htmlspecialchars($players['first_name']) . "'>".htmlspecialchars($players['first_name'])." ".htmlspecialchars($players['last_name'])."</a></td>";
Than include jQuery in your HTML (see http://jquery.com/)
Then include the event handlers: and right on the front page of jQuery are the two examples you need to adapt. You'll end up with something like this (where #info is a div on your page where you display the data):
$( ".js-load-more" ).on( "click", function( event ) {
$.ajax({
url: 'http://YourUrl/page.php?name=' + $(this).data('playername'),
error: function() {
$('#info').html('<p>An error has occurred</p>');
},
dataType: 'json',
success: function(data) {
var $title = $('<h1>').text(data.talks[0].talk_title);
var $description = $('<p>').text(data.talks[0].talk_description);
$('#info')
.append($title)
.append($description);
},
type: 'GET'
});
});
have a play from there, this should get you going.

Showing a dynamically built div

I have a drop-down menu built from entries in a database. What I need to do is to show certain content based on the selected entry in the menu. So, if I choose "Apples" in the menu, I can write a query to pull "Apple" info out of the database and the content div will show this information. "Oranges" will write an "Oranges" query and then show the info on oranges.
Ideally, I'd like the index of the selected menu item. But since I'm not submitting any form, I cannot get the info from $_POST variables. I could get it via jQuery or Javascript but I need it for processing another MySQL statement.
Since I don't know the information in the menu, I can't set up specific divs to show the content.
Hopefully this makes sense! Thanks for any help.
You want to create an asynchronous call. You want JavaScript triggered on the form changing to make a call to the server. On the server, you perform the SQL query and return it in a machine readable format such as JSON or just build the div on the server. When the JavaScript gets the reply from the server, it can parse the contents and insert it into the page.
I can sense you need an example
JQUERY:
$('select').change(function(){
var myfruit = $(this).val(); // apple, orange
$.ajax({
"url": yourphpfile.php,
"type": "POST",
"data":{"fruit":myfruit},
}).success(function(response) {
// response is what we get back from php
for(var i in response){
$('#div').append(response[i]['fruit'];
}
});
});
PHP
if(isset($_POST['fruit'])){
$sql = "SELECT * FROM fruits WHERE fruit = '{$_POST['fruit']}'";
// do something with your query, and get a result;
echo json_encode($result); // this gets sent to your jquery
die;
}

How to tell which JQUERY popup to display

Finally figured it out thanks to One Mad Monkey, but forgot quotes on my $eventDate variable for the SQL query. Thanks for the help guys :)
$(".date_has_event").live("click",function(){
console.log('you clicked', this);
var dateClicked = $(this).attr('id');
$.ajax({
type:"GET",
url: "popup_events.php",
data:"date="+dateClicked,
success: function(data){
$(".popupContent").html(data);
}});
//centering with css
centerPopup();
//load popup
loadPopup();
});
This is linked to my popup_events.php file:
<?php
include ("Includes/dbConnect.php");
$eventDate = $_GET['date'];
$query = "SELECT * FROM events WHERE eventDate='$eventDate'";
$check = mysqli_query($cxn,$query) or die("Couldn't execute query!");
while($row = mysqli_fetch_array($check))
{
$id = $row['eventID'];
echo "<div class='submit_event_list'><a href='individual_event_page_main.php?id=$id'>";
echo $row['eventName'];
echo " | " . $row['host'];
echo " | " . $row['venue'];
echo " | " . $row['eventDate'];
echo "</a></div>";
echo "<br />";
}
?>
If the question is "is this possible?" The answer is yes. Of course you can bind events to your HTML that will show a popup. People do it all the time, so it's not really a valuable question!
The broader question of "am I doing this in a good way?" is a tougher one to answer and also stretches the limits of an "appropriate" Stack Overflow question, which should have a more focused scope than this.
I say "have at it!" safely knowing that you can add popups. Then come back when you have more specific questions. Things I would think about when you get started:
Is JavaScript the best way to dynamically generate a calendar? Are you using a server-side language at all? This might be the better place. And if you ARE using JS, why not build the calendar completely, and THEN go back and populate it?
Do you need to make your ajax call synchronous? Are there ways you can design it so that it can happily go fetch the new information and not worry about whether it's returning in sequence or not? (hint, this might relate back to #1)
Information moreso than a hint: live() is a deprecated function. From jQuery 1.7 onward, I would look into using .on() instead. There's an equivalent for .live() using .on() but I don't think you should use it... you should use the equivalent to .delegate() since you should have an ancestor of your calendar that can serve as a listener (instead of the whole document!). If you're using jQuery 1.5.x or 1.6.x then use .delegate().
Maybe this should've been the first question: have you looked into UI frameworks that already include calendars and popups (they won't include the event management, so you still have some fun work to do)?
I'm not sure you actually have a question...
But it seems like you probably just need some help on how to tell which pop up to display.
in your:
$(".popup").live("click",function(){})
you can use the special "this" variable to determine which of your day's was clicked.
eg.
$(".popup").live("click",function(){
console.log('you clicked', this);
//to get the date id (your formatdate) from this
var dateClicked = $(this).parent().parent().attr('id');
//have to do parent() twice because you put your .popup under <div class='title'>
})
To make it easier.. you should consider changing your click event to use .date_has_event instead of .popup so you could do this instead:
$(".date_has_event").live("click",function(){
var dateClicked = $(this).attr('id');
})
once you know you which day was clicked, you probably want to render that day's popup's content (the list of events for that day) in your popup window.
That's where you should use an ajax request sent to some backend code which is basically the php code you already have shoved behind your (that stuff under your #popupContact).
You should move that code out somewhere.. in say a "getEvents.php"
eg.
$(".date_has_event").live("click",function(){
var dateClicked = $(this).attr('id');
$.ajax({
type: "GET",
url: "getEvents.php",
dataType: "json",
data: "date="+dateClicked,
success: function(data){
//fill your popup with the data received
}
})
})
I think that should be enough to get you on your way.
Good luck.

POSTing data to the server, behind the scenes

I'm building a website which has a page that users can add content to, and they can rearrange the divs to whichever position and size they want. I'd like to have a save button which saves the current position of each div; however, I don't want the page to refresh each time (I'm also going to have an auto-save, which will have to save the information in the background).
I can't figure out how to post the data to the server though, without causing the page to reload. I figure I need some kind of AJAX request, but can't find anything that tells me how to do that (all the AJAX examples I can find seem to be about reading data from the server). I think I'm just starting to go round in circles now, but I can't get my head around this at all - I know it's probably not a hard thing to do, but I keep getting confused by the different examples.
So, first of all, is this the best way to do it? And, if so, can someone point me to a straightforward example of posting data via AJAX? I'm already using jQuery, so can use that for the Ajax as well.
Thanks.
Super simple AJAX with jQuery:
$.ajax({
url: '/save-the-stuff-url',
type: 'POST',
data: {
// information about your divs, etc.
'foo' : 'bar'
},
success: function(response) {
// if the AJAX call completes successfully, this function will get called.
alert('POST successful!');
}
});
Give it a shot!
Here, try this for AJAX:
$.post("example.php", {
from : "ajax", // put some info in these - they are the params
time : "2pm",
data : "save"
},
function(data) { // callback function - data always passed to it
$("#success").html(data); // do something with that data
}
);
And put this somewhere:
<span id='success'></span>
And then, try this example for example.php:
<?php
if(isset($_POST['from']) and $_POST['from'] == 'ajax'){
echo "<span style='color: green;'>Saved!</span>";
}
else {
echo "<span style='color: red;'>Failure!</span>";
}
?>
And then just modify these to fit your needs, probably changing the file of target. Whatever the script outputs is what is given to the ajax request. This means that if this was my PHP script:
<?php echo "Aloha!"; ?>
And this was my javascript:
$("#output").load("myScript.php");
Then #output would have "Aloha!" in it.
Hope this helps!
Please go through the Jquery site for various examples of post.
HTH
and the jQuery docs pages are a great way to learn jQuery.. the page for post is http://docs.jquery.com/Post
you may also want to look at jQuery draggables if you're not using that yet..
http://docs.jquery.com/UI/API/1.8/Draggable
you can fire a save tied to your draggable object being let go rather easily with
$( ".selector" ).draggable({
stop: function(event, ui) { ... }
});

How to update a <div> with jQuery and CakePHP?

I'm using CakePHP for a small web app and on one form page there's a dropdown to select a job number. I'd like to update two text fields based on the job number selected in the dropdown using jQuery (I'm also open to using the default ajax helper but I didn't have a lot of success with it).
Here's my jQuery snippet:
<script>
$(document).ready(function() {
$('#job_id').change(function() {
$.post('/surveys/jobdetails', {id: $(this).attr('id')});
})
.change();
});
</script>
jobdetails is a method in my controller that gets the current job based on the job id passed in. However, it doesn't get called when the dropdown changes value. I tried substituting an alert function in place of .post and that worked, so onchange is being called correctly.
Here's the <div> I'm trying to update:
echo "<div id='job_details'>";
echo $form->label('jobtitle', 'Job Title');
echo "<input type='text' name='jobtitle' id='jobtitle'>";
echo $form->label('department', 'Department');
echo "<input type='text' name='department' id='department'>";
echo "</div>";
I want to set the value of each text field to be the corresponding value for the job returned from the ajax call. There's a lot of really good jQuery and CakePHP documentation but I haven't found anything that quite covers what I'm trying to do. Can anyone see what I'm doing wrong? Is there a better way to use ajax to update a div with CakePHP?
Right now, it appears that the AJAX request hits the "/surveys/jobdetails" URL, but does nothing with the results. You need to add a callback to your AJAX request, like so:
$(document).ready(function() {
$('#job_id').change(function() {
$.post('/surveys/jobdetails', {id: $(this).attr('id')},
function(result) {
$('#job_id').html(result);
});
})
.change();
});
There is also a convenience function in jQuery called load() which simplifies it even further, getting the contents of a URL and applying it to the selected element:
$(document).ready(function() {
$('#job_id').change(function() {
$(this).load('/surveys/jobdetails', {id: $(this).attr('id')});
})
.change();
});
Your CakePHP controller needs to look something like this:
function jobdetails() {
// get the data however you want
// $_POST['id'] will have the job_id
print json_encode(array(
'jobtitle' => $jobtitle,
'department'=>$dept
));
exit;
}
Then you need to add a callback to your $.post that will actually update the fields:
$(document).ready(function() {
$('#job_id').change(function() {
$.post('/surveys/jobdetails', {id: $(this).attr('id')}, function(json) {
// now that we are in the callback,
// the variable json is an object
// with the values we passed above
// so we can update the fields with the new values
$('#jobtitle').val(json.jobtitle);
$('#department').val(json.department);
});
})
.change();
});
I also recommend you get a tool like Firebug so you can see the progress of your AJAX requests and make sure the server is returning what you think its returning. It makes testing and debugging anything related to AJAX way easier.
In my opinion this is more elegant than outputting the whole DIV to update, but if you want to go that route you would just use jQuery's .load to achieve what you want.

Categories