ajax firing for every button when a single button is clicked - ajax

I'm adding a button to every list_item on page.
The buttons are generated, with their correct id.
And the button value changes as it should - as shown in the alert.
But on a single button click, the alert fires as many times as there are buttons on the page.
The alert always shows the same (and correct) button id.
Without the alert, this causes the button value to switch back and forth if other buttons are clicked in the meantime.
Generate the buttons:
function create_saved_message_button( ) {
$button_label = "Save";
?>
<td width="15%" class="thread-options">
<input type="button" class="savedbutton" value = "<?php echo $button_label ?>" id = "<?php echo message_thread_id(); ?>" />
</td>
<?php
}
The ajax:
function saved_message_button_javascript() {
?>
<script type="text/javascript" >
jQuery(document).ready(function($) {
$('.savedbutton').click(function(event){
event.preventDefault();
var button = $(this);
var butt_txt = $(button).attr('value');
alert($(button).attr("id"));
$(button).attr({'disabled': true});
var data = {
action: 'saved_button_clicked',
};
$.get(ajaxurl, data, function(response) {
if(butt_txt == 'Save') {
$(button).attr('value', 'Un-Save');
}
else {
$(button).attr('value', 'Save');
}
});
$(button).attr({'disabled': false});
return false;
});
});
</script>
<?php
}
Is there any way to stop the multiple alerts?
I think that would solve the value switching problem.
Then I just need to pass the button id to the php function saved_button_clicked
The add_actions:
add_action( 'messages_inbox_list_item', 'create_saved_message_button', 1 );
//this was the problem
//add_action('messages_inbox_list_item', 'saved_message_button_javascript');
//the solution - use this instead
add_action('after_member_messages_threads', 'saved_message_button_javascript');
add_action('wp_ajax_saved_button_clicked', 'process_save_button_clicked');

Maybe I misunderstood something. I created a html with 5 buttons and your javascript in it but I couldn't find the behavior you described. Look here.

Related

Can't get wordpress ajax form to submit

I am porting an application to WordPress. It uses a form to select what attributes the customer is looking for in an Adult Family Home via checkboxes and drop-downs. It re-searches the database on each onchange and keyup. Originally I had the application standalone in PHP, but when I migrated it to WordPress I started having issues.
Currently in WP I have the code conditionalized ($DavesWay == 1) to do ajax the normal no-WordPress-way and ($DavesWay == 0) to do it the WordPress-way.
In the non-WordPress-way, the ajax works fine EXCEPT that I get a WP header and menu between the search form and the results-div that Ajax puts the data in. I get no errors from WP or in the JS console. In the WP-way The search form displayed, but nothing happens when I check any of the checkboxes. The JS console displays
POST http://localhost/demo4/wp-admin/admin-ajax.php 400 (Bad Request)
But I don't see any way to tell exactly what it is complaining about. How should I troubleshoot this?
Troubleshooting = Examine the HTML output, lots of echos and exits in PHP code, look at JS console.
function submitPg1(theForm) {
// Used with onChange from "most" form elements, but not on those that change the page
// rather than the select criteria. Such as rowsPerPage, pageNumber etc.
setById("pageNo", "1"); // set inital page
mySubmit();
}
function mySubmit(theForm) { // The actual ajax submit
// DO NOT set page number
jQuery.ajax({ // create an AJAX call...
data: jQuery("#asi_search_form").serialize(), // get the form data
type: jQuery("#asi_search_form").attr("method"), // GET or POST
url: jQuery("#asi_search_form").attr("action"), // the file to call
success: function (response) { // on success..
jQuery("#result").html(response); // update the DIV
}
})
}
function setById(id, value) { // Used to set vales by Id
x = document.getElementById(id).value;
x.value = value;
}
// 1st submit with blank selection
jQuery(document).ready(function () { submitPg1(this.form) });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
Code fragments: (from the displayed page source)
<div id="asi_container" class="asi_container" >
<noscript><h2>This site requires Javascript and cookies to function. See the Help page for how to enable them.</h2></noscript>
<div id="searchForm">
<form id="asi_search_form" name="asi_search_form" method="post" action="http://localhost/demo4/wp-admin/admin-ajax.php">
<input type="hidden" name="action" value="asi_LTCfetchAll_ajax" style="display: none; visibility: hidden; opacity: 0;">
<table id="greenTable" class="asi_table" title="The Green areas are for site administration, not typical users">
<tbody>
PHP code:
$DavesWay = 0;
if ($DavesWay == 1){ //echo "Daves Way Setup"; // Dave's way, which works but prints the menu twice
if( $operation == "submit"){
require("asi_LTCfetchAll.php"); // for each onchange or onkeyup
}else{
add_filter( 'the_content', 'asi_tc_admin', '12' ); // Initial page refresh # must be >12
}
}else{
// The WordPress way that I could't get to work -- asi_LTCfetch never gets called
function asi_LTCfetchAll_ajax(){
//echo "<br /> Goto to Submit function"; // DEBUG
require($asi_plugin_dir . "/includes" . '/asi_LTCfetchAll.php');
}
add_action( "wp_ajax_asi_LTCfetchAll_ajax", "asi_LTCfetchAll_ajax" ); // admin users
add_action( "wp_ajax_nopriv_asi_LTCfetchAll_ajax", "asi_LTCfetchAll_ajax" ); // non-logged in users
add_filter( "the_content", "asi_tc_admin", "12" ); // Initial page refresh # must be >12
}
Try changing the JavaScript to the way WordPress recommends it in their documentation:
var data = {
'action': 'my_action',
'whatever': 1234
};
jQuery.post(ajaxurl, data, function(response) {
alert('Got this from the server: ' + response);
});
I suggest trying following URL: https://codex.wordpress.org/AJAX_in_Plugins
Also you can use the plugin: https://wordpress.org/plugins/ajax-search-lite/

Open a link without a page reload

When I click on the link i want page2.html to appear without any reloading of the current page. Despite all trials, when i click on the link it does reload the entire page before displaying page2.html
<script>
$(document).ready(function() {
$("a").click(function(event) {
var $this = $(this),
url = $this.data("url");
$(document.body).load(url);
event.preventDefault();
});
}); < /script>
homepage.html
<a href="#" data-url="page2.html" class="topic-list-item">
<h3 class="topic-title">Internet Protocol Basics</h3>
<div class="topic-description-text">
Learn how Internet Protocol is used
</div>
</a>
$("a").click(function() {
var $this = $(this),
href = $this.attr("href");
$(document.body).load(href);
location.href = "#" + href;
});
See jQuery.fn.load for more details.
try this code it will work
$(document).ready(function () {
$("a").click(function (event) {
var $this = $(this),
url = $this.data("url");
$(document.body).load(url);
event.preventDefault();
});
});
the problem with Digital's code is that he is not using data function to get url as well when we click on then default action for anchor will be called so we need to stop default action so i used event.preventDefault();
also always put your jquery code between $(document).ready block

How to change submit value of form after used by AjaxForm

I am using AjaxForm extension to submit form with ajax as following
var options =
{
url:'<?php echo site_url('user/ajaximage')?>',
dataType: 'json',
success: function(data)
{
if(data.messagecode==1)
{
$(".wrap label").hide();
$("#preview").html("<img src='"+data.content+"'class='preview'>");
$("#errormessagepic").hide();
}
else if(data.messagecode==0)
{
$("#errormessagepic").html(data.content);
$("#preview").html('<img width="100" height="100" src="<?php echo base_url();?>/images/avatar_generic.png" />');
}
//$('#SignupForm').resetForm();
//$("#SignupForm").attr('action','<?php echo site_url('user/individualprofile')?>');
} ,
};
$("#SignupForm").ajaxForm(options);
$("#SignupForm").submit();
but after this ajax submission I want to resend form to another URL other than '' but it does not work. Any help
Ok so you want to post a form using ajax to two different urls. I dont know about your extension but i can tell you how to do this.
1- create a function and run this function when the user clicks on the submit
<-input type="button" name="submit" value="Submit" onclick="post_form()"-/>
2- Create the body of the function, this function will submit data to two urls
function post_form(){
// save the values in text boxes in variable
var val1=$("#text1").val();
var val2=$("#text2").val();
var data={name:val1,age:val2};
var url1="savedata.php";
var url2="updatedata.php";
$.post(url1,data, function(response){
alert(response);
// so when the form is submited to ur1 this callback function runs and here you can submit it to another url
$.post(url1,data,function(response){alert(response)});
});
}
</script>

jQuery: Get next page via ajax and append it with animation

I am getting next page on my wordpress blog using jquery, finding the desired div and appending it to the existing one. This part works without a problem. But, what I need to do is, to add slideDown animation to it.
This is how my working code so far looks like:
$.get(next_page, function(data) {
var response = $(data);
var more_div = $(response).find('.FeaturedRow1').html();
$('.FeaturedRow1').append(more_div).slideDown('slow');
$('.navigation').not(':last').hide();
I tried adding hide() to response, more_div as well as append lines. In the first case, I get error stating that it cannot set property display of undefined.
In the second case, in the console it display HTML and says "has no method hide". I also tried adding a line $(more_div).hide() but again, I get the error "Uncaught TypeError: Cannot set property 'display' of undefined".
If I use hide in the 3rd line
$('.FeaturedRow1').hide().append(more_div).slideDown('slow');
it hides the whole FeaturedRow1 div and animates it, that takes me to the top of the div, which is what I don't want.
EDIT: Here's the important HTML structure and jQuery code for the desired section
<div class="FeaturedRow1">
<div class="postspage">
//list of posts here
</div>
<div class="navigation">
<span class="loadless">
//hyperlink to previous page
</span>
<span class="loadmore">
//hyperlink to next page
</span>
</div>
</div>
When you click on the hyperlink inside the loadmore, the following jQuery code gets called
$('.loadmore a').live('click', function(e) {
e.preventDefault();
var next_page = $(this).attr('href');
$.get(next_page, function(data) {
var $response = $(data);
var $more_div = $response.find('.FeaturedRow1').hide();
$more_div.appendTo('.FeaturedRow1').delay(100).slideDown('slow')
$('.navigation').not(':last').hide();
});
});
$('.loadless').live('click', function(e) {
e.preventDefault();
if ($('.postpage').length != 1) {
$('.postpage').last().remove();
}
$('.navigation').last().remove();
$('.navigation').last().show();
});
You get error as you are using html method which returns a string not a jQuery object, try the following.
var $response = $(data);
var $more_div = $response.find('.FeaturedRow1').hide();
$more_div.appendTo('.FeaturedRow1').delay(100).slideDown('slow');
//$('.navigation').not(':last').hide();
Update:
$.get(next_page, function(data) {
var $response = $(data);
var more_div = $response.find('.FeaturedRow1').html();
$('<div/>').hide()
.append(more_div)
.appendTo('.FeaturedRow1')
.delay(100)
.slideDown('slow')
$('.navigation').not(':last').hide();
});

codeigniter and tab contents

I have some tabs whose contents are fully functional parts of my website.
For instance, in my admin area, I have tabs [add/delete album][add photo][delete photo]. I'm technically dividing the admin area via tabs.
I'm using ajax to load the content into these tabs. tab content area is a div.
The view that is inside the tab content area also uses ajax to load stuff.
These are ajax calls that operates inside the tab content area.
Everything works fine as long as the view inside the tab content area stays same or only part of it changes. But when certain interactions inside tab content area return a whole new view, tab content area would not show them.
I know what happens is that this new view that is returned is not passed into the tab content area div.
In firebug, I can see that ajax success function response shows the new view that is returned.
But I do not know how to pass that new view to the tab content area.
I would appreciate it if someone could help me out in explaining how this could be solved or how contents inside tabs are managed in CI.
adminTabsview.php
<ul id="adminTabs">
<li ><?php echo anchor('#album_addDelete', 'Album Add/Delete'); ?></li>
</ul>
<div id="adminTabsContent"></div>
$(document).ready(function(){
$('#adminTabs a').on({
click: function (evt){
evt.preventDefault();
var page = this.hash.substr(1);
adminTabsAjaxCall(page);
}
});
});
function adminTabsAjaxCall ($data){
$.ajax({
type: "POST",
url: "index.php/adminsite_controller/"+ $data + "/",
dataType: "html",
data: $data,
statusCode: {removed}
},
success: adminTabContent
});
function adminTabContent (data){
$('#adminTabsContent').html(data);
}
albumsEditDeleteView.php
(this is a view that gets loaded into the tab contentarea div)
<div id="adminTabsContent">
<div id="albumList">
<ul>
<li>
Asdf
<a class="add" href="http://localhost/myPHP/photoalbums/index.php/Albums_Controller/add_album/301/Asdf/1/28/0">[ add ]</a>
<a class="delete" href="http://localhost/myPHP/photoalbums/index.php/Albums_Controller/delete_album/301/Asdf/1/28/0">[ delete ]</a>
</li>
</ul>
</div>
</div>
$(document).ready(function(){
$('#albumList').on({
click: function (evt){
evt.preventDefault();
var $clickedElement = evt.target.tagName;
if ($clickedElement == 'A' ){
var urlarray = url.split('/');
$chosen.albumid = urlarray[8];
$chosen.albumname = urlarray[9];
$chosen.lft = urlarray[10];
$chosen.rgt = urlarray[11];
$chosen.nodeDepth = urlarray[12];
if ($class == 'add'){
albumajaxcall($chosen);
}
if ($class == 'delete'){
deleteajaxcall($chosen);
}
}
}
});
});
function albumajaxcall($data){
$.ajax({
type: "POST",
url: "index.php/Adminsite_Controller/add_album/",
dataType: "json",
data: $data,
statusCode: {removed}
},
success: adminTabContent
});
}
function adminTabContent(data){
$('#adminTabsContent').html(data);
}
//heres the view file that has to replace the original view inside
//tabcontent area
//addnode_view.php
<?php echo form_open('Albums_Controller/update_albumSet');?>
<input type="text" name="newAlbum" id="newAlbum" value=""/>
<input type="submit" name="submit" value="Submit" />
<?php echo form_close();?>
<?php
//heres the controller function
function add_album(){
$levelData ['albumid'] = $this->input->post('albumid');
<!-- removed-->
$levelData ['main_content'] = 'addnode_view';
$this->load->view('includes/template', $levelData);
}
//And heres the controller method that loads
//the original page (albumsEditDeleteView.php) - this is the original view
//that gets loaded into the tab- I get stuck when this view
//has to be **totally** replaced through links in the view)
function album_addDelete(){
$allNodes ['myAlbumList'] = $this->Albums_Model->get_albumList();
echo $this->load->view('albumsEditDelete_view', $allNodes);
}
thanx in advance.
basically what you need to do is load whatever new view youll be putting in the tab in the controller function(adminsite_controller/whatever function) that is handling your ajax.
this will basically echo out the view file, which will be viewed as the success variable of your ajax function.
so you have something like this then for the success part of your ajax
success:function(msg){adminTabContent(msg);}
and in your controller in codeigniter you'll load a view the standard way, but since this will be only loading a piece of the page you may need to create a new view file thats just the div that will be there. You will do all your data gathering the same way you would if it wasn't ajax.
$data['some_data'] = $this->some_model->some_function();
$this->load->view('someview', $data);

Resources