i have a form in which if the user enters the search query, its parameter should be passed through jquery and after getting the results it should load the results in the div container. since i'm not very well-versed with jquery, how would i do this?
html:
//currently the data is being displayed on pageload:
$(document).ready(function() {
$("#bquote").load("quotes_in.php")
});
$(".bsearch")
.keydown(function() {
//pass the parameter to the php page
//display in div #bquote
});
<!-- Begin Search -->
<div id="search" style="display:none;">
<input type="text" class="bsearch" name="search" value="Search" />
</div>
<!-- End Search -->
php [using OOP]:
if (isset($_POST["search"]))
{
$quotes->searchQuotes();
}
php class:
$search = $_POST['search'];
$sql = "SELECT * FROM thquotes WHERE cQuotes LIKE '%"
. mysql_real_escape_string($search) ."%' ORDER BY idQuotes DESC";
try {
$query = $this->_db->prepare($sql);
$query->execute();
if(!$query->rowCount()==0)
{
while($row = $query->fetch())
{
echo $this->formatSearch($row);
}
I would do in that way:
$(".bsearch").keydown(function() {
//create post data
var postData = {
"bsearch" : $(this).val(),
"anotherParam" : "anotherValue"
};
//make the call
$.ajax({
type: "POST",
url: "yourAjaxUrl.php",
data: postData, //send it along with your call
success: function(response){
alert(response); //see what comes out
//fill your div with the response
$("#bquote").html(response);
}
});
});
EDIT:
For putting a loader you need to check this here:
http://api.jquery.com/category/ajax/global-ajax-event-handlers/
And to show a loader image for example:
$("#loading").ajaxStart(function(){
$(this).show();
});
And to hide it when ajax call is complete:
$("#loading").ajaxComplete(function(){
$(this).hide();
});
If you want to go down the ajax route...
$(".bsearch").keydown(function() {
// Get the current input value
var value = $(this).val();
//pass the parameter to the php page
$.ajax({
type: "POST",
url: "some.php", // replace this with the right URL
data: "bsearch=" + value,
success: function(msg){
$("#search").html(msg);
}
});
});
Read up on jQuery.ajax() and if you turn that search box into a proper form, utilize jQuery.serialize()
Instead of using $_POST, you can use $_GET or $_REQUEST like the following:
var searchString = $(".bsearch").val();
$("#bquote").load("path_to_php_file.php?search="+searchString);
Then, in PHP, replace
$_POST
...with
$_GET
Related
I'm trying to show a specific div depending on the result of a SQL query.
My issue is that I can't get the divs to switch asynchronously.
Right now the page needs to be refreshed for the div to get updated.
<?php
//SQL query
if (foo) {
?>
<div id="add<?php echo $uid ?>">
<h2>Add to list!</h2>
</div>
<?php
} else {
?>
<div id="remove<?php echo $uid ?>">
<h2>Delete!</h2>
</div>
<?php
}
<?
<script type="text/javascript">
//add to list
$(function() {
$(".plus").click(function(){
var element = $(this);
var I = element.attr("id");
var info = 'id=' + I;
$.ajax({
type: "POST",
url: "ajax_add.php",
data: info,
success: function(data){
$('#add'+I).hide();
$('#remove'+I).show();
}
});
return false;
});
});
</script>
<script type="text/javascript">
//remove
$(function() {
$(".minus").click(function(){
var element = $(this);
var I = element.attr("id");
var info = 'id=' + I;
$.ajax({
type: "POST",
url: "ajax_remove.php",
data: info,
success: function(data){
$('#remove'+I).hide();
$('#add'+I).show();
}
});
return false;
});
});
</script>
ajax_add.php and ajax_remove.php only contain some SQL queries.
What is missing for the div #follow and #remove to switch without having to refresh the page?
"I'm trying to show a specific div depending on the result of a SQL query"
Your code doesn't seem to do anything with the results of the SQL query. Which div you hide or show in your Ajax success callbacks depends only on which link was clicked, not on the results of the query.
Anyway, your click handler is trying to retrieve the id attribute from an element that doesn't have one. You have:
$(".plus").click(function(){
var element = $(this);
var I = element.attr("id");
...where .plus is the anchor element which doesn't have an id. It is the anchor's containing div that has an id defined. You could use element.closest("div").attr("id") to get the id from the div, but I think you intended to define an id on the anchor, because you currently have an incomplete bit of PHP in your html:
<a href="#" class="plus" ?>">
^-- was this supposed to be the id?
Try this:
<a href="#" class="plus" data-id="<?php echo $uid ?>">
And then:
var I = element.attr("data-id");
Note also that you don't need two separate script elements and two document ready handlers, you can bind both click handlers from within the same document ready. And in your case since your two click functions do almost the same thing you can combine them into a single handler:
<script type="text/javascript">
$(function() {
$(".plus,.minus").click(function(){
var element = $(this);
var I = element.attr("data-id");
var isPlus = element.hasClass("plus");
$.ajax({
type: "POST",
url: isPlus ? "ajax_add.php" : "ajax_remove.php",
data: 'id=' + I,
success: function(data){
$('#add'+I).toggle(!isPlus);
$('#remove'+I).toggle(isPlus);
}
});
return false;
});
});
</script>
The way i like to do Ajax Reloading is by using 2 files.
The first: the main file where you have all your data posted.
The second: the ajax file where the tasks with the db are made.
Than it works like this:
in the Main file the user lets say clicks on a button.
and the button is activating a jQuery ajax function.
than the ajax file gets the request and post out (with "echo" or equivalent).
at this point the Main file gets a success and than a response that contains the results.
and than i use the response to change the entire HTML content of the certain div.
for example:
The jQuery ajax function:
$.ajax({
type: 'POST', // Type of request (can be POST or GET).
url: 'ajax.php', // The link to the Ajax file.
data: {
'action':'eliran_update_demo', // action name, used when one ajax file handles many functions of ajax.
'userId':uId, // Simple variable "uId" is a JS var.
'postId':pId // Simple variable "pId" is a JS var.
},
success:function(data) {
$("#div_name").html(data); // Update the contents of the div
},
error: function(errorThrown){
console.log(errorThrown); // If there was an error it can be seen through the console log.
}
});
The PHP ajax function:
if (isset($_POST['action']) ) {
$userId = $_POST['userId']; // Simple php variable
$postId = $_POST['postId']; // Simple php variable
$action = $_POST['action']; // Simple php variable
switch ($action) // switch: in case you have more than one function to handle with ajax.
{
case "eliran_update_demo":
if($userId == 2){
echo 'yes';
}
else{
echo 'no';
}
break;
}
}
in that php function you can do whatever you just might want to !
Just NEVER forget that you can do anything on this base.
Hope this helped you :)
if you have any questions just ask ! :)
Ok , I am trying to get different id values through Jquery , and pass them to Jquery AJAX that will hit a PHP file so I can get some data back .... I'm not sure how to get all the multiple different ids because Jquery is only getting the first id of many of the unique id values generated by the while loop .. and I would like each unique ID to also be passed to the AJAX function in Jquery .. Your help would be so much appreciated . I'm still new to the Jquery world
<?php
require('../database/connection.php');
?>
<script type="text/javascript">
jQuery(document).ready(function() {
var ID = $('div#opposition img').attr("id"); alert(ID);
$.ajax({
type:'GET',
url :'get_users_images.php',
data:'screen_name='+ ID,
success: function(result){
$('div#opposition img').attr('src', result);
}
});
});
</script>
<?php
$select2 = "SELECT * FROM AUTHORS WHERE ID <> $id";
$result2 = mysql_query($select2);
$result_count = mysql_num_rows($result2);
echo '<div id ="opposition">';
while ($row2 = mysql_fetch_array($result2, MYSQL_ASSOC)) {
echo "<img id ='".$row2['Twitter']."' src='images/ajax-loader.gif' class ='image".$row2['Twitter']."'/>"; // echos different ids,
}
?>
</div>
You can send an stringified array of id's like this -
jQuery(document).ready(function () {
var ID = $('div#opposition img').map(function(){
return this.id;
}).get();
$.ajax({
type: 'GET',
url: 'get_users_images.php',
data: { screen_name : JSON.stringify(ID)},
success: function (result) {
$('div#opposition img').attr('src', result);
}
});
});
If I am correct, Actually , why you are placing the set of images returned by php in one
img tag, $('div#opposition img').attr('src', result); . Rather I think you must do something like $('div#opposition').innerHTML(result) .
I am trying to pass a variable from my ajax to my php script. I can't see to get it to work. It keeps on giving me NULL when I do a var_dump on the variable.
JQUERY:
$(document).ready(function() {
$('.trigger').click(function() {
var id = $(this).prev('.set-id').val();
$.ajax({
type: "POST",
url: "../modules/Slide_Show/slide_show.php",
data: id
});
LinkUpload(id);
function LinkUpload(id){
$("#link-upload").dialog();
}
});
});
</script>
PHP:
$id = $_POST['id'];
$query = mysql_query("SELECT * FROM xcart_slideshow_slides where slideid='$id'")or die(mysql_error());
$sli = mysql_fetch_array($query);
$slide_id = $sli['slideid'];
$link = $sli['link'];
var_dump($id);
I need the $id variable to post so I can dynamically change the dialog box when the click function is activated.
EDIT:
So I have changed some of my coding:
Jquery:
$(document).ready(function() {
$('.trigger').click(function() {
var id = $(this).prev('.set-id').val();
$.post(
"slide-show-link.php",
{ id: id },
function(data,status){alert("Data: " + data + "\nStatus: " + status); }
);
// alert(id);
LinkUpload(id);
});
function LinkUpload(id){
$("#link-upload").dialog();
}
});
I wanted to see if the data was in fact being passed so I threw an alert in the .post. This is the error I'm getting now:
I have tried passing plain text and echoing it back on the page but it fails. It is just not passing.
Try this -
$.ajax({
type: "POST",
url: "../modules/Slide_Show/slide_show.php",
data: { id : id }
});
Working on a project where I want to be able to delete a dynamic record using jQuery and PHP. I already have the option for users to add a record dynamically it is just getting the delete option to work. While I am trying to develop this function I have set the Delete to INSERT. Where I am having trouble is getting the value from the hidden field to delete-class.php (the bottom script). Below I have posted the code:
<form id="frmDelete" method="post" action="delete-class.php">
<input id="btnSubmit" type="submit"/>
<ul id="class">
<?php
//this is being loaded from a different page and is here just to reference the fields
while ($row = mysql_fetch_array($result)) {
echo '<li id="liClass" class="ui-widget"><img src="trash-can-icon.png" id='.$row["id_distance_class"].' class="delete"/>' . $row["class_section"] . '<input type="hidden" name="hdid" id="hdid" value="'.$row["id_distance_class"].'"/></li>';
?>
</ul>
</form>
<script>
$(function() {
$(".delete").click(function() {
$('#load').fadeIn();
var commentContainer = $(this).parent();
var id = $(this).attr("id");
var string = id ;
// console.log(id);
$.ajax({
type: "POST",
url: "delete-class.php",
data: $(this).serialize(),
cache: false,
success: function(){
commentContainer.slideUp('slow', function() {$(this).remove();});
$('#load').fadeOut();
}
});
return false;
});
});
</script>
//this is the delete-class.php
$results = mysql_query("INSERT INTO distance_class (class_section) VALUES ( '".$_POST['hdid']."' ) ");
The problem is you're not passing this information in your AJAX request. You're passing
data: $(this).serialize()
...presumably thinking this points to the form. It doesn't; it points to the deletion button clicked, since this code is running in the button's event handler callback.
Change the above to target the form.
main.php:
<SCRIPT type="text/javascript">
$("#btnSubmit").click(function () {
alert("What will i put here!");
});
</SCRIPT>
<input type = "submit" id = "btnSubmit" value = "Try IT!" />
<div id = "show_search2">
</div>
output.php:
<?php $val = $_POST['btnSubmit'];
echo "<H1>$val</H1>"; ?>
What specific jQuery functionality can get the value of the btnSubmit and access it through $_POST and output it to the div show_search2? I used prototype.js but it provides conflict with my other JS scripts in the index.
Note: all my script source is included in index and that's why I didn't include the source in this post.
Do you mean something like this:
$("#btnSubmit").click(function (e) {
e.preventDefault();
var submitVal = $(this).val();
$.ajax({
type: "POST",
url: "url_of_your_output.php",
data: {btnSubmit : submitVal},
success: function(response) {
$("#show_search2").html(response); //response from output.php
}
});
});