Updated:
I want to make a load more ajax button, I want it to load data from a php file which will extract data from database.
I've managed to make it to load just once, however when I click the new more button it doesn't work.
Here's the Javascript:
$(document).ready(function(){
$(".more").click(function(){
var ID = $(this).attr("id");
if(ID) {
$("#more"+ID).html('<img src="moreajax.gif" />');
$.ajax({
type: "POST",
url: "more.php",
data: "lastimg="+ ID,
cache: false,
success: function(html){
$("div#updates").append(html);
$("#more"+ID).remove(); // removing old more button
}
});
} else {
$(".morebox").html('The End');// no results
}
return false;
});
});
And here's more.php
$lastimg = mysql_real_escape_string($_POST['lastimg']);
$result = $mmhclass->db->query("SELECT * FROM `file_storage` WHERE `is_private` = '0' AND `file_id` < '$lastimg' ORDER BY `file_id` DESC LIMIT 10;", array(MYSQL_FILE_STORAGE_TABLE));
while($row=mysql_fetch_array($result))
{
$file_id = $row['file_id'];
$filename = $row['filename'];
?>
<li>
<?php echo $filename; ?>
</li>
<?php
}
?>
<div id="more<?php echo $file_id; ?>" class="morebox">
more
</div>
It just work once, because after your ajax completed, the .more element will be new on the page,
so the click event handler you attach to it, isn't working anymore.
You must use event delegation:
$('body').on('click', '.more', function () {
// your code
});
Note: jQuery 1.7+ required.
References:
.on() - jQuery API Documentation
I think you may use jQuery live function
$(".more").live("click", function(){
// Code here
});
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 ! :)
what is the problem of this code?
it is menu and page change by ajax with out refreshing the page, but its not working
it is my ajax code
<script>
$(document).ready(function() {
$('.news').click(function give(id){
$('#main-unit').text('Please Wait...');
var place= id;
$.ajax({
url:'pages/news.php',
type:'POST',
data:'where='+place,
statusCode:{
success: function(data){
$('#main-unit').html(data);
}
}
});
});
});
</script>
this is my html tags
<ul>
<li><a class="news" onclick=\"give('news')\" href="#">news</a></li>
</ul>
and php code
mysql_connect("localhost", "root", "")
or die(mysql_error());
mysql_select_db("basi")
or die(mysql_error());
if($_POST['where']=='news'){
$result = mysql_query("SELECT * FROM contents WHERE type = 0");
while ($row = mysql_fetch_array($result)){
$title = $row['title'];
$text = $row['text'];
echo"
<div class='title'><span>$title</span></div>
<div class='content'>
$text
</div>
";
}
}
the information read from DB but dont return to html file.
The problem is with your JavaScript. You're waiting for document ready and (incorrectly) binding a click event listener that isn't being used! Try:
<a class="news" onclick="give('news')" href="#">news</a>
with the JavaScript:
<script>
function give(id) {
$('#main-unit').text('Please Wait...');
var place = id;
$.ajax({
url:'pages/news.php',
type:'POST',
data:'where='+place,
statusCode:{
success: function(data){
$('#main-unit').html(data);
}
}
});
}
</script>
A better solution would be to separate HTML from JavaScript - remove the onclick attribute from your menu link, and use pure jQuery to select it and bind an event that calls give() when it is clicked:
$(document).ready(function() {
$('.news').click(function(e) {
give('news');
});
});
FTFY
<script>
$(document).ready(function() {
$('.news').click(function give(id){
$('#main-unit').text('Please Wait...');
var place= id;
$.ajax({
url:'pages/news.php',
type:'POST',
data:'where='+place,
//I believe your mistake was here
success: function(data){
$('#main-unit').html(data);
}
});
});
});
</script>
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.
http://pastebin.com/dttyN3L6
The file that processes the form is called upload.php
I have never really used jquery/js so I am unsure how I would do this or where I would put the code.
It has something to do with this setInterval (loadLog, 2500);
Also, how can I make it so the user can submit a form without the page refreshing?
$.ajax({
type: "POST",
url: "upload.php",
data: dataString,
success: function() {
}
});
return false; `
and
<?php
$conn1 = mysqli_connect('xxx') or die('Error connecting to MySQL server.');
$sql = "SELECT * from text ORDER BY id DESC LIMIT 1";
$result = mysqli_query($conn1, $sql) or die('Error querying database.');
while ($row = mysqli_fetch_array($result)) {
echo '<p>' . $row['words'] . '</p>';
}
mysqli_close($conn1);
?>
</div>
<?php
if (!isset($_SESSION["user_id"])) {
} else {
require_once('form.php');
}
?>
You can submit a form without refreshing a page something like this:
form.php:
<form action='profile.php' method='post' class='ajaxform'>
<input type='text' name='txt' value='Test Text'>
<input type='submit' value='submit'>
</form>
<div id='result'>Result comes here..</div>
profile.php:
<?php
// All form data is in $_POST
// Now perform actions on form data here and
// create an result array something like this
$arr = array( 'result' => 'This is my result' );
echo json_encode( $arr );
?>
jQuery:
jQuery(document).ready(function(){
jQuery('.ajaxform').submit( function() {
$.ajax({
url : $(this).attr('action'),
type : $(this).attr('method'),
dataType: 'json',
data : $(this).serialize(),
success : function( data ) {
// loop to set the result(value)
// in required div(key)
for(var id in data) {
jQuery('#' + id).html( data[id] );
}
}
});
return false;
});
});
And If you want to call an ajax request without refreshing page after a particular time, you can try something like this:
var timer, delay = 300000;
timer = setInterval(function(){
$.ajax({
type : 'POST',
url : 'profile.php',
dataType: 'json',
data : $('.ajaxform').serialize(),
success : function(data){
for(var id in data) {
jQuery('#' + id).html( data[id] );
}
}
});
}, delay);
And you can stop the timer at any time like this:
clearInterval( timer );
Hope this will give you a direction to complete your task.
This is pretty simple.
To access elements using Jquery you use css selectors, for example, to get value of an input field with name "foo" you do the following:
var fooVal = $("input[name=foo]").val();
To send it over to the server you are to append an event listener (for example, click) to the submit button/any other element
var data = { varName : fooVal };
var url = "http://example.com";
var responseDataType = "json";
function parseResponse(JSON)
{
// your code handling server response here, it's called asynchronously, so you might want to add some indicator for the user, that your request is being processed
}
$("input[type=submit]").on('click', function(e){
e.preventDefault();
$(this).val("query processing");
$.post(url,data, parseResponse, responseDataType);
return false;
});
If you want to do constant updates, you can, of course, add timers or some other logic. But I hope you get the idea of how to proceed to such cases;
To answer part of your question, you can use ajax.
<html><head></head><body>
<div id="feed"></div>
<script type="text/javascript">
var refreshtime=10;
function tc()
{
asyncAjax("GET","upload.php",Math.random(),display,{});
setTimeout(tc,refreshtime);
}
function display(xhr,cdat)
{
if(xhr.readyState==4 && xhr.status==200)
{
document.getElementById("feed").innerHTML=xhr.responseText;
}
}
function asyncAjax(method,url,qs,callback,callbackData)
{
var xmlhttp=new XMLHttpRequest();
//xmlhttp.cdat=callbackData;
if(method=="GET")
{
url+="?"+qs;
}
var cb=callback;
callback=function()
{
var xhr=xmlhttp;
//xhr.cdat=callbackData;
var cdat2=callbackData;
cb(xhr,cdat2);
return;
}
xmlhttp.open(method,url,true);
xmlhttp.onreadystatechange=callback;
if(method=="POST"){
xmlhttp.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
xmlhttp.send(qs);
}
else
{
xmlhttp.send(null);
}
}
tc();
</script>
</body></html>
I have a div which contains some text for the database:
<div id="summary">Here is summary of movie</div>
And list of links:
Name of movie
Name of movie
..
The process should be something like this:
Click on the link
Ajax using the url of the link to pass data via GET to php file / same page
PHP returns string
The div is changed to this string
<script>
function getSummary(id)
{
$.ajax({
type: "GET",
url: 'Your URL',
data: "id=" + id, // appears as $_GET['id'] # your backend side
success: function(data) {
// data is ur summary
$('#summary').html(data);
}
});
}
</script>
And add onclick event in your lists
<a onclick="getSummary('1')">View Text</a>
<div id="#summary">This text will be replaced when the onclick event (link is clicked) is triggered.</div>
You could achieve this quite easily with jQuery by registering for the click event of the anchors (with class="movie") and using the .load() method to send an AJAX request and replace the contents of the summary div:
$(function() {
$('.movie').click(function() {
$('#summary').load(this.href);
// it's important to return false from the click
// handler in order to cancel the default action
// of the link which is to redirect to the url and
// execute the AJAX request
return false;
});
});
try this
function getmoviename(id)
{
var p_url= yoururl from where you get movie name,
jQuery.ajax({
type: "GET",
url: p_url,
data: "id=" + id,
success: function(data) {
$('#summary').html(data);
}
});
}
and you html part is
<a href="javascript:void(0);" class="movie" onclick="getmoviename(youridvariable)">
Name of movie</a>
<div id="summary">Here is summary of movie</div>
This works for me and you don't need the inline script:
Javascript:
$(document).ready(function() {
$('.showme').bind('click', function() {
var id=$(this).attr("id");
var num=$(this).attr("class");
var poststr="request="+num+"&moreinfo="+id;
$.ajax({
url:"testme.php",
cache:0,
data:poststr,
success:function(result){
document.getElementById("stuff").innerHTML=result;
}
});
});
});
HTML:
<div class='request_1 showme' id='rating_1'>More stuff 1</div>
<div class='request_2 showme' id='rating_2'>More stuff 2</div>
<div class='request_3 showme' id='rating_3'>More stuff 3</div>
<div id="stuff">Here is some stuff that will update when the links above are clicked</div>
The request is sent to testme.php:
header("Cache-Control: no-cache");
header("Pragma: nocache");
$request_id = preg_replace("/[^0-9]/","",$_REQUEST['request']);
$request_moreinfo = preg_replace("/[^0-9]/","",$_REQUEST['moreinfo']);
if($request_id=="1")
{
echo "show 1";
}
elseif($request_id=="2")
{
echo "show 2";
}
else
{
echo "show 3";
}
jQuery.load()
$('#summary').load('ajax.php', function() {
alert('Loaded.');
});
<script>
$(function(){
$('.movie').click(function(){
var this_href=$(this).attr('href');
$.ajax({
url:this_href,
type:'post',
cache:false,
success:function(data)
{
$('#summary').html(data);
}
});
return false;
});
});
</script>
<script>
function getSummary(id)
{
$.ajax({
type: "GET",//post
url: 'Your URL',
data: "id="+id, // appears as $_GET['id'] # ur backend side
success: function(data) {
// data is ur summary
$('#summary').html(data);
}
});
}
</script>