jQuery-ajax 'on click event' not working - javascript

I'm trying to use ajax to load certain pages, but the 'on-click' is not working. I created an init() function so one of the pages auto-loads when the page gets loaded. That works! However, when I click on any of the links, nothing gets loaded. In fact, nothing happens. Once a link is clicked, it's not going to the jQuery script. Any suggestions will be greatly appreciated.
Here are my links...
<a href="#" id='add' >Add</a>
<?php foreach($names as $name): ?>
<?= $name['name']; ?>
<?php endforeach; ?>
<section id='main'>Main content</section>
Here is my jQuery script...
var app = { // this is a namespace
nav: $('a.league'), // selector
content: $('section#main') // section where id='main'
};
app.putContent = function(content){
this.content.html(content);
}
app.loadPage = function(page){
$.ajax({
url: '../views/security.php',
type: 'GET',
cache: false,
//data:{id: page}, // this works too
data:"id=" + page,
success: function(data){
app.putContent(data);
},
error: function(){
app.putContent('Could not find page.');
}
});
}
app.init = function(){
app.loadPage('add'); // this part works
app.nav.on('click', function(){ // This part(on click) is not working
var page = $($this).attr("id");
app.loadPage(page);
});
}();

Change this line:
var page = $($this).attr("id");
Into this:
var page = $(this).attr("id");
Tip:
use your browser inspector/console to identify the problems in JS
code

Related

Reload an AJAX loaded page after update

I'm trying to understand how a dynamic page loaded with AJAX can be reloaded after one of the records is updated. I've got the following jquery script on my page.
<script type="text/javascript">
function showUser(str) {
if (str == "") {
$("#txtHint").empty();
return;
}
$("#txtHint").load("data_ajax.php?q=" + str);
}
$(document).ready(function () {
$("#txtHint").delegate(".update_button", "click", function () {
var id = $(this).attr("id");
var dataString = 'id='+ id ;
var parent = $(this).parent();
$.ajax({
type: "POST",
url: "data_update_ajax.php",
data: dataString
});
return false;
});
});
</script>
I thought I could get this done with the code below if I call it from within the data_ajax.php page after it loads the corresponding data from the database, but it refreshes the whole page.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#ref_butn").click(function(){
location.reload();
});
});
</script>
I know this can be done, just not sure where to turn after searching for an answer for a while.
You would just do what you did to initially populate it:
$("#txtHint").load("data_ajax.php?q=" + str);
That will load your "new" AJAX and overwrite what's currently inside #txtHint with it.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#ref_butn").click(function(){
//location.reload();
$("#txtHint").load("data_ajax.php?q=" + str); // I don't know where str comes from, but you get the idea.
});
});
</script>
A part/block/div of the page cannot be refreshed but can be dynamically updated with the data on a callback.
On the server side, echo the data you'd like to show on the client-side.
For example:
//Successful update in the database
$callback = array('heading' => 'Success!', 'message' => 'The data was successfully submitted');
echo json_encode($callback);
To retrieve the data you've to pass success callback function to your ajax block.
$.ajax({
type: "POST",
url: "data_update_ajax.php",
data: dataString,
dataType: 'json',
success: function(data) {
$('#yourDiv .heading').text(data.heading);
$('#yourDiv .message').text(data.message);
}
});
Ben's answer worked, but he lead me to figure out an easier way to do this. So I essentially called the original function showUser(str) { on the button and just had to give it the selected $_GET value.
<button name="users" onClick="showUser(this.value)" value="<?php echo $_GET['q']; ?>">Refresh Content</button>
This button was placed on the data_ajax.php page, not the parent index.php for anyone looking to do the same. So, every time I hit the Refresh Content button, the table refreshes without reloading the page and I no longer lose the loaded content.

how can I make one button correspond to different clicked div html jquery php?

You can see my code below. I face a challenge that I don't know how to use one button to correspond different click. On the php, if I put the button inside the foreach loop, it will create a lot of button, that's not what I want. In the js, if I put the on.click button inside the foreach elements loop, it will also create a lot of on.click button, so I click one button, it will run many times depends on the number of label_name. I think about addClass, if I clicked the heart div, I use js to add a class, and then get the attr('id') inside button.on.(click), so I can differentiate them in my server php and mysql can request the correspond data. But the problem is that if a user click every div, then every div add classes, then problem again.
var current_page = 1;
var elements_body = {
"heart": "1",
"eye": "2",
"ear_nose_throat": "3",
"hand_foot_mouth": "4"
};
jQuery.each(elements_body, function (label_name, label_num) {
var disease_label = $('#' + label_name + '_d');
disease_label.on('click', function () {
var data = {
action: 'body_part_keyword', //wordpress loading url
postSearchNonce: MyAjaxSearch.postSearchNonce,
current_page: current_page,
label_name: label_name //this label_name will differentiate data that need to request from mysql in the action.php
};
$.ajax({
url: MyAjaxSearch.ajaxurl,
type: 'POST',
cache: false,
data: data,
success: function (data) {
disease_menu_result.append(data);
current_page++
}
}); //ajax
});
}); //jQuery.each
$('#loadmorebutton_body').on('click', function () {
//I dont know how can I make this button to correspond above code
});
<div id="disease_menu">
<?php
$arr = Array(
'heart'=>'heart',
'eye'=>'eye',
'ear_nose_throat'=>'ear nose throat',
'hand_foot_mouth'=>'hand foot mouth'
);
foreach ($arr as $key=>$value) {
?>
<div class="disease_li" id="disease_li_<?php echo $key;?>">
<span class="disease_span" id="<?php echo $key;?>_d"><label>(<?php echo $value;?>)</label>diseases</span>
</div>
<!--disease_li-->
<?php }?>
</div>
<!--disease_menu-->
<button id="loadmorebutton_body">Load More</button>
Use javascript functions :
function MyFunction() {
jQuery.each( elements_body, function( label_name, label_num) {
var disease_label= $('#'+ label_name + '_d');
disease_label.on('click',function(){
var data={
action: 'body_part_keyword',//wordpress loading url
postSearchNonce : MyAjaxSearch.postSearchNonce,
current_page:current_page,
label_name:label_name//this label_name will differentiate data that need to request from mysql in the action.php
};
$.ajax({
url: MyAjaxSearch.ajaxurl,
type:'POST',
cache: false,
data: data,
success: function(data){
disease_menu_result.append(data);
current_page++
}
});//ajax
});
});
}
$('#loadmorebutton_body').on('click',function(){
MyFunction();
}

Can't place jQuery inside loaded document.ready: not called

I have a page called: contact_profile.php that uses jquery .load to load info into a div.
$('#json_comments').load('json_comments_content.php');
json_comments_content.php looks like this:
<?php
require_once 'core/init.php';
$user = new User();
if(!$user->isLoggedIn()) {
Redirect::to('login.php');
}
$contact = new Contact();
//check to make sure there is current contact selected, otherwise redirect to index. This helps when you deselect a contact from menu bar while on contact page.
if (!($contact->isSelected())) {
Redirect::to('index.php');
}
?>
<div class="items general-item-list">
<div class="item">
<div class="item-head">
<div class="item-details">
<img class="item-pic" data-field="pic_url" src="">
<span class="item-label" data-field="datetime" data-value="" data-pk=""></span>
</div>
</div>
<div class="item-body"></div>
</div>
</div>
Load More...
<script type="text/javascript">
$(document).ready(function() {
$('.comments_data').loadmore({
source: 'json_comments.php',
step: 15,
userid: '<?php echo $user->data()->id; ?>'
});
//on load, disabled the comments editable info on page load so it looks better.
$('#json_comments a').attr("data-disabled", "true");
$.fn.editable.defaults.mode = 'inline';
});
</script>
I am using a custom plugin called 'loadmore' that will load more data on my page from a mysql database. It works fine.
However, I have to use the following code for the data that is supplied by the loadmore plugin:
$('.edit_me').editable({
emptytext: ".....",
url: "ajax_xeditable_update.php?table=comments",
});
That code is using the X-Editable plugin for jQuery: http://vitalets.github.io/x-editable/
If I place the code in the loaded content's page inside the document.ready function, it never gets called!
Here's what my loadmore plugin looks like. If the code for X-Editable is placed there it will work properly. It would be better to have the code placed in the loaded page and NOT in the plugin - that way the plugin can stay generic.
Hope I was clear on my problem.
Here's the loadmore custom plugin:
(function ($) {
"use strict";
$.fn.loadmore = function(options) {
var self = this,
settings = $.extend({
source: '',
step: 2,
userid: '',
}, options),
stepped = 1,
item = self.find('.item'),
items = self.find('.items'),
finished = function() {
// hide the load more button
self.find('.items-load').remove();
},
append = function(value) {
var name, part, id, userid, canedit;
item.remove();
for(name in value) {
if(value.hasOwnProperty(name)) {
id = value['id'];
userid = value['user_id'];
part = item.find('*[data-field="' + name +'"]');
//find anything that has a can edit class and then add the general editable class for x-editable to work.
canedit = item.find(".can_possibly_edit");
if(part.length){
part.text(value[name]);
//add the value to an image if there is one for x-editable to work.
if($(part).is("img")) {
$(part).attr("src", value[name]);
}
//only make the current user's stuff editable
if(settings.userid == userid ) {
//add edit_me to the classes so x=editable can work. but then remove edit_me and the editable class so x-editable doesn't work for data that doesn't belong to the user(found in the else clause below).
$(canedit).addClass('edit_me editable editable-pre-wrapped editable-click editable-disabled');
$(canedit).attr('data-value', value[name]);
//there must be an id field in the json so it can be assigned to the primary key for x-editable to work.
$(canedit).attr('data-pk', id);
} else {
//remove hyperlink stuff and just leave the text to view only.
$(canedit).removeClass('edit_me editable');
}
}
}
}
item.clone().appendTo(items);
//this works if it's placed here only!
$('.edit_me').editable({
emptytext: ".....",
url: "ajax_xeditable_update.php?table=comments",
});
},
load = function(start, count) {
$.ajax({
url: settings.source,
type: 'get',
dataType: 'json',
data: {start: start, count: count},
success: function(data) {
var items = data.items;
if(items.length) {
$(items).each(function(index, value) {
append(value);
});
stepped = stepped + count;
}
if(data.last === true) {
finished();
}
}
});
};
if(settings.source.length) {
self.find('.items-load').on('click', function(){
load(stepped, settings.step);
return false;
});
load(1, settings.step);
} else {
console.log('Source required for loadmore.');
}
};
}(jQuery))
It's almost like on the loaded page: json_comments_content.php I need to run the loadmore plugin on document.ready and THEN once the loadmore has been completed, return back to the page and run:
$('.edit_me').editable({
emptytext: ".....",
url: "ajax_xeditable_update.php?table=comments",
});
Not sure if it matters, but the loadmore script is included on my main page from: 'js/loadmore.js'. It's in a subdirectory.

Change div's content after clicking on a link using Ajax request

My div contains a PHP function having an sql query which fetch latest threads from threads table. The structure of my page is something like this;
Section # 1 --- Link 1
Section # 2 --- Link 2
Section # 3 --- Link 3
What I want to do is to make it so like when Link 1 is clicked it shows the latest threads from Section 1, and when Link 3 is clicked then it shows latest threads of Section 3.
PLEASE NOTE: I know that I can use slidetoggle() jQuery function to show and hide div, but I want to make it so that WHEN link is clicked THEN runs the sql query to show latest threads. I'm using the following jQuery;
jQuery(document).ready(function($)
{
$('a[id^="forum_name"]').on('click', function (e)
{
e.preventDefault();
var fid = $(this).attr("fid");
$.ajax(
{
type: "POST",
url: 'latest_threads.php?fid='+fid,
dataType: 'json',
success: function (data)
{
$("#forum_threads_"+fid).html(data).stop().slideToggle("fast");
}
});
});
});
My PHP file latest_threads.php has the following code;
<?php
define("IN_MYBB", 1);
require_once "./global.php";
if ($mybb->input['fid'] != "")
{
require_once MYBB_ROOT."inc/functions.php";
$fid = intval($mybb->input['fid']);
$forum['forum_threads'] = kalachi_forum_threads($fid);
}
?>
and My HTML is like;
{$forum['threads']}
<div id="forum_threads_{$forum['fid']}" style="display: none;">{$forum['forum_threads']}</div>
But it doesn't works, please help!
jQuery:
jQuery(document).ready(function($){
$('a[id^="forum_name"]').on('click', function (e){
e.preventDefault();
var fid = $(this).attr("fid");
$.ajax(
{
type : "post",
dataType: "html",
url : "misc.php?action=forum_threads&fid="+fid,
cache: false,
success : function(response)
{
$("#forum_threads_"+fid).stop().slideToggle("fast").html(response);
}
});
});
});
PHP:
<?php
define("IN_MYBB", 1);
require_once "./global.php";
if ($mybb->input['fid'] != "")
{
require_once MYBB_ROOT."inc/functions.php";
$fid = intval($mybb->input['fid']);
echo $forum['forum_threads'] = kalachi_forum_threads($fid);
exit;
}
?>
In HTML:
Change the last line to this:
<div id="forum_threads_{$forum['fid']}"></div>
You're not outputting your response as far as I can see.
Try something like this:
...
$forum['forum_threads'] = kalachi_forum_threads($fid);
echo $forum['forum_threads']
exit();
...
I added the echo line to output the actual response back to your browser.
You can read Ajax tutorial.
But in your case, you should know, the data that you are showing in your div in this part of your code :
success: function (data)
{
$("#forum_threads_"+fid).html(data).stop().slideToggle("fast");
}
is the response of your php code.
Your php response is any output of your php code, it can be a simple echo 'something' or a html code, or including a html file etc.
generete a html code or include a html file in your php code, anything that you want to show in your div.
Note: always put a die() or exit() in the end of your php code.
This is a simple example :
HTML :
<div id="c1" onclick="javascript:loadcontent(1);">click</div><br>
<div id="c2" onclick="javascript:loadcontent(2);">click</div><br>
<div id="c1" onclick="javascript:loadcontent(3);">click</div><br/
Javascript (jquery) :
<script>
function loadcontent(id) {
$.post("yourphp.php", {id: id}, function(data) {
if (data) {
$("#c" + id).html(data);
}
else
{
alert("error");
}
});
}
</script>
PHP - yourphp.php :
<?php
$id = $_POST['id'];
require 'filename'.$id.".html";
die;
?>
Then you must create 3 html files with names : filename1.html , filename2.html , filename3.html
and put any content in them that you want to show in your divs with id c1,c2 or c3 .
Thats it

How to use data-toggle with Ajax and PHP

I am using Bootstrap (which is heavily modified) and love the use of data-toggle. My current script is pretty straight forward, it's an image upload script. I use the following code to list images from the database:
$stmt = $db->query('SELECT * FROM img_slider ORDER BY id ');
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo "<li>
<div class='thumbnail removable'>
<div class='remove' id='{$row['id']}' data-toggle='remove'></div>
<img src='../{$row['path']}'>
</div>
</li>"
;}
Notice data-toggle='remove' - This function works great removing images statically, but what say I want to remove the images in the database? I understand the best method would be to utilise Ajax. Here is what I mean:
My PHP file delete.php:
$id = $_REQUEST['id'];
$db->beginTransaction();
$st = $db->prepare('DELETE FROM img_slider WHERE id = :id');
$st->execute(array(':id' => $id));
$db->commit();
I am trying to execute this with the following jquery/ajax:
$("a[data-toggle=remove]").click(function()
{
var image_id = $(this).attr('id');
$.ajax({
cache: false,
type: 'POST',
url: 'actions/delete.php',
data: 'id='+image_id,
});
});
Any help would be greatly appreciated! I just don't know how to utilise bootstraps data-toggle with PHP, tried search for the solution, came up empty handed. Here is an image of how the image upload works:
If it is the selector that is the problem, tt should be
$('div[data-toggle="remove"]').click(function() {
but if it is click on the image you mean
$('div[data-toggle="remove"]').next().click(function() {
Edit. I just tested your question like so :
<div class='thumbnail removable'>
<div class='remove' id='27' data-toggle='remove'></div>
<img src='1.gif'>
</div>
$('div[data-toggle="remove"]').next().click(function() {
var image_id = $(this).prev().attr('id');
alert(image_id);
$.ajax({
cache: false,
type: 'POST',
url: 'actions/delete.php',
data: 'id='+image_id
});
});
alerts 27 and and try to XHR with id: 27.
If it is click on the data-toggle <div>
$('div[data-toggle="remove"]').click(function() {
var image_id = $(this).attr('id');
Take a look at jQuery function ON: http://api.jquery.com/on/
The issue is you are binding the click event at load, when you are loading elements in to the page async then they will not events binded. On should bind the events now and in the future.
$("body").on( "click", ".remove", function() {
// Remove stuff
});

Categories

Resources