Keep jQuery accordion state on postback with PHP - php

I am using jQuery UI's accordion as a subnav on a site I am building. The problem is that I haven't been able to find a good way to maintain state between pages. I'm wondering what the best way to do this is.
I've thought of storing the index of the accordion in the database, but that seems overly complicated for a problem like this. Is there a better way? Obviously cookies and session but that is equally complicated for just a subnav...any ideas?
EDIT: Here's my code
$.post(
accordion_ajax.ajaxurl,
{
type : 'GET',
action : 'accordion_ajax'
},
function(data){
$(".accordion-main").accordion('option', 'collapsible', true);
$(".accordion-main").accordion('option', 'active', 0);
// the accordion just does not work inside this ajax call, but if I put it outside the ajax call it works fine. Any thoughts?
}
);
$(".accordion-main").accordion({
change: function(event, ui){
$.post(
accordion_ajax.ajaxurl,
{
type : 'SET',
action : 'accordion_ajax',
data : $(".accordion-main").accordion('option', 'active')
}
);
}
});

Here's what I would do:
In the change() handler for the accordion, I would send the index of the current accordion section to the server via an AJAX call:
$( "#AccordionID" ).accordion({
change: function(event, ui) {
$.ajax({
type:'POST',
url: 'urlToPhpScript.php',
data:'function=setAccordion&selectedAccordionSection='+ $("#AccordionID").accordion('option', 'active')
});
}
});
On the server side I would store this value in the users session:
<?php
// urlToPhpScript.php
session_start();
if($_GET['function']=='getAccordion') {
if(isset($_SESSION['currentAccordion'])) {
return $_SESSION['currentAccordion'];
} else {
return 0;
}
}
if($_POST['function']=='setAccordion') {
$_SESSION['currentAccordion'] = $_POST['AccordionID'];
}
Then on each page load I would send an AJAX call to the server that would query the accordion section from the users session:
$(document).ready(function () {
$.ajax({
type: 'GET',
url: 'urlToPhpScript.php',
data: 'function=getAccordion',
success: function(data) {
$('#AccordionID').accordion('activate', data);
}
});
});
This way it wouldn't matter how you're navigating from one page to the next, and you wouldn't need to worry about burying a 'currentAccordion' type hidden field on each page of your site.

Related

Wordpress Ajax call only works with console.log debugging

So I am building a user profile section in front-end Wordpress, and loading different content dynamically in jQuery tabs to break up the UI a bit. I early on switched from loading this all in on page load to using ajax to call in the php files for the user profile only on demand.
This was not working so I added a console.log to the success action to see what is going on. Funnily this function works to load in the php files, but ONLY IF I have console.log enabled. To be clear, when I check the network tab under XHR requests, both with console.log and without console.log I get a 200 status back from the server, it just doesn't render if I am not declaring that success action to the console.
Any ideas why?
$('.profileTabs ul li a').click(function(e) {
e.preventDefault();
var tab_id = $(this).attr('id');
$.ajax({
type: "GET",
url: cyberAjax.ajaxurl,
dataType: 'html',
data: ({
action: 'ajax_load_tabs', id: tab_id
}),
success: function(data){
$('#tab'+tab_id).html(data);
console.log( $('#tab-'+tab_id).html(data) );
},
error: function(data)
{
alert("Error!");
return false;
}
});
});
For reference, my approach was influenced by this article.
So I have the below in my functions.php - this all works with console.log so I don't think the cause lies here:
function ajax_load_tabs() {
$tab_id = $_GET['id'];
if ($tab_id == 'ui-id-7') {get_template_part( '/page-templates/dashboard/broker-dashboard', 'onboarding' );}
elseif ($tab_id == 'ui-id-8') {get_template_part( '/page-templates/dashboard/broker-dashboard', 'tasks' );}
elseif ($tab_id == 'ui-id-9') {get_template_part( '/page-templates/dashboard/broker-dashboard', 'incidents' );}
die();
}
add_action('wp_ajax_ajax_load_tabs', 'ajax_load_tabs');
add_action('wp_ajax_nopriv_ajax_load_tabs', 'ajax_load_tabs');

jQuery toggle with different attributes and apply ajax

I am using this jQuery plugin for making toggle, but I have an issue that when I make multiple toggles that have same ids and class so in that case I am not able to identify particular toggle for applying auto load ajax on changing value.
I would to ask that how I make same toggle with this same plugin but different ids or class or name so I make ajax function like when I click toggle it will update in PHP without submitting submit button.
The plugin I am using is this one
The code I am using is this:
HTML
<p>Default: <span class="easyswitch"></span></p>
<p>Checked: <span class="easyswitch" data-default="1"></span></p>
SCRIPT
<script>
$('.easyswitch').easyswitch();
</script>
AJAX
$('MY_CLASS_NAME').change(function(){
var mode= $(this).prop('checked');
$.ajax({
type:'POST',
dataType:'JSON',
url:'test.php',
data:'mode='+mode,
success:function(data)
{
$("body").html('Operation Saved');
}
});
You can not handle easyswitch's change event. you need to create click event of it, and from it you can get the status of current toggle.
$('.easyswitch').easyswitch();
$('.easyswitch').click(function () {
var mode = $(this).hasClass('on');
toogleStatus(mode);
});
// for all controlls.
$(".easyswitch").each(function() {
var mode = $(this).hasClass('on');
toogleStatus(mode);
});
function toogleStatus(mode)
{
if (!mode) {
alert('checked')
}
else {
alert('unchecked')
}
}
Try using callback option
$('.easyswitch').easyswitch({
callback: function(val, ele) {
$.ajax({
type: 'POST',
dataType: 'JSON',
url: 'test.php',
data: { mode: val },
success: function(data) {
$("body").html('Operation Saved');
}
});
}
});

Using $.post with CodeIgniter URL issue

I have one page in CodeIgniter with URL http://127.0.0.1/FOLDER/data/getList.
On that page, there is list of enteries. On that list, in every item there is a link on which by clicking I need to fetch some data using $.post jQuery.
I have used this code:
$(".class_name").click(function() {
$val = $(this).attr('val')
$.post("class/func", {val:$val}, function(data) {
alert(data);
});
});
The issue is with the URL to be used with $.post.
If I use, "/class/func", it sends the requsts to http://127.0.0.1/class/func (FOLDER is not getting in).
If I use, "class/func", it sends the request to
http://127.0.0.1/FOLDER/data/class/func (here data gets inserted which is class for the current page).
How should I resolve this error? Should I be using <?php echo base_url() ?>class/func; is it the correct way of doing it?
If your JavaScript code is between <script></script> in your view:
$.post("<?php echo site_url("class/func") ?>", {val:$val}, function(data) {
alert(data);
});
If your JavaScript is on a separate .js file:
In the footer of your page:
<script>var baseUrl = "<?php echo base_url() ?>";</script>
And then:
$.post(baseUrl + "index.php/class/func", {val:$val}, function(data) {
alert(data);
});
Alternative :
Set a data-attribute to your item
Go!
And then:
$.post($(this).data("ajaxurl"), {val:$val}, function(data) {
alert(data);
});
I had a separate js file from where I had to call the function in a controller "Verifypass.php". I had something like this in the $_post():
$.post( "verifypass", { pass: $("#password").val() }, function(data){
});
This did not work for me, So all I did was to add index.php at the beginning of the controller name as:
$.post( "index.php/verifypass", { pass: $("#password").val() }, function(data){
});
And it worked then.

Issue with using a value in JQuery/Javascript

I have a PHP populated table from Mysql and I am using JQuery to listen if a button is clicked and if clicked it will grab notes on the associated name that they clicked. It all works wonderful, there is just one problem. Sometimes when you click it and the dialog(JQuery UI) window opens, there in the text area there is nothing. If you are to click it again it will pop back up. So it seems sometimes, maybe the value is getting thrown out? I am not to sure and could use a hand.
Code:
$(document).ready(function () {
$(".NotesAccessor").click(function () {
notes_name = $(this).parent().parent().find(".user_table");
run();
});
});
function run(){
var url = '/pcg/popups/grabnotes.php';
showUrlInDialog(url);
sendUserfNotes();
}
function showUrlInDialog(url)
{
var tag = $("#dialog-container");
$.ajax({
url: url,
success: function(data) {
tag.html(data).dialog
({
width: '100%',
modal: true
}).dialog('open');
}
});
}
function sendUserfNotes()
{
$.ajax({
type: "POST",
dataType: "json",
url: '/pcg/popups/getNotes.php',
data:
{
'nameNotes': notes_name.text()
},
success: function(response) {
$('#notes_msg').text(response.the_notes)
}
});
}
function getNewnotes(){
new_notes = $('#notes_msg').val();
update(new_notes);
}
// if user updates notes
function update(new_notes)
{
$.ajax({
type: "POST",
//dataType: "json",
url: '/pcg/popups/updateNotes.php',
data:
{
'nameNotes': notes_name.text(),
'newNotes': new_notes
},
success: function(response) {
alert("Notes Updated.");
var i;
$("#dialog-container").effect( 'fade', 500 );
i = setInterval(function(){
$("#dialog-container").dialog( 'close' );
clearInterval(i);
}, 500);
}
});
}
/******is user closes notes ******/
function closeNotes()
{
var i;
$("#dialog-container").effect( 'fade', 500 );
i = setInterval(function(){
$("#dialog-container").dialog( 'close' );
clearInterval(i);
}, 500);
}
Let me know if you need anything else!
UPDATE:
The basic layout is
<div>
<div>
other stuff...
the table
</div>
</div>
Assuming that #notes_msg is located in #dialog-container, you would have to make sure that the actions happen in the correct order.
The best way to do that, is to wait for both ajax calls to finish and continue then. You can do that using the promises / jqXHR objects that the ajax calls return, see this section of the manual.
You code would look something like (you'd have to test it...):
function run(){
var url = '/pcg/popups/grabnotes.php';
var tag = $("#dialog-container");
var promise1 = showUrlInDialog(url);
var promise2 = sendUserfNotes();
$.when(promise1, promise2).done(function(data1, data2) {
// do something with the data returned from both functions:
// check to see what data1 and data2 contain, possibly the content is found
// in data1[2].responseText and data2[2].responseText
// stuff from first ajax call
tag.html(data1).dialog({
width: '100%',
modal: true
}).dialog('open');
// stuff from second ajax call, will not fail because we just added the correct html
$('#notes_msg').text(data2.the_notes)
});
}
The functions you are calling, should just return the result of the ajax call and do not do anything else:
function showUrlInDialog(url)
{
return $.ajax({
url: url
});
}
function sendUserfNotes()
{
return $.ajax({
type: "POST",
dataType: "json",
url: '/pcg/popups/getNotes.php',
data: {
'nameNotes': notes_name.text()
}
});
}
It's hard to tell from this, especially without the mark up, but both showUrlInDialog and sendUserfNotes are asynchronous actions. If showUrlInDialog finished after sendUserfNotes, then showUrlInDialog overwrites the contents of the dialog container with the data returned. This may or may not overwrite what sendUserfNotes put inside #notes_msg - depending on how the markup is laid out. If that is the case, then it would explains why the notes sometimes do not appear, seemingly randomly. It's a race condition.
There are several ways you can chain your ajax calls to keep sendUserOfNotes() from completing before ShowUrlInDialog(). Try using .ajaxComplete()
jQuery.ajaxComplete
Another ajax chaining technique you can use is to put the next call in the return of the first. The following snippet should get you on track:
function ShowUrlInDialog(url){
$.get(url,function(data){
tag.html(data).dialog({width: '100%',modal: true}).dialog('open');
sendUserOfNotes();
});
}
function sendUserOfNotes(){
$.post('/pcg/popups/getNotes.php',{'nameNotes': notes_name.text()},function(response){
$('#notes_msg').text(response.the_notes)
},"json");
}
James has it right. ShowUrlInDialog() sets the dialog's html and sendUserOfNotes() changes an element's content within the dialog. Everytime sendUserOfNotes() comes back first ShowUrlInDialog() wipes out the notes. The promise example by jeroen should work too.

HTML : Enable Multiple Submission without refreshing

I want to enhance my tool's page where as soon use click a button. Request goes to server and depending upon return type (fail/pass) i change color of button. No Refresh/page reload
Page has multiple buttons : some what like below.
Name 9-11 - 11-2 2-5
Resource1 - Button - Button - Button
Resource2 - Button - Button - Button
Resource1 - Button - Button - Button
I am a c++ programmer so you might feel i asked a simple question
Here's a sample of jQuery Ajax posting a Form. Personally, I'm unfamiliar with PHP but Ajax is the same no matter what. You just need to post to something that can return Success = true or false. This POST happens asynchronously so you don't get a page refresh unless you do something specific in the success: section.
$("document").ready(function () {
$('form').submit(function () {
if ($(this).valid()) {
$.ajax({
url: yourUrlHere,
dataType: "json",
cache: false,
type: 'POST',
data: $(this).serialize(),
success: function (result) {
if(result.Success) {
// do nothing
}
}
});
}
return false;
});
});
Of course you don't have to be doing a POST either, it could be a GET
type: 'GET',
And if you don't need to pass any data just leave data: section out. But if you want to specify the data you can with data: { paramName: yourValue },
The cache: false, line can be left out if you want to cache the page. Seeing as how you aren't going to show any changes you can remove that line. jQuery appends a unique value to the Url so as to keep it from caching. Specifying type: "json", or whatever your specific type is, is always a good idea but not necessary.
Try using the $.post or $.get functions in jquery
$.post("url",$("#myform").serialize());
Adding a callback function as Fabrício Matté suggested
$.post("url",$("#myform").serialize(),function(data){alert(data);$("#myform").hide()//?Do something with the returned data here});
Here you go. You will find an example of a form, a button a the necessary ajax processing php page. Try it out and let us know how it goes:
<form action="" method="post" name="my_form" id="my_form">
<input type="submit" name="my_button" id="my_button" value="Submit">
</form>
<script type="text/javascript">
$("document").ready(function () {
$('#my_form').submit(function () {
$.ajax({
url: "ajaxpage.php",
dataType: "json",
type: "POST",
data: $(this).serialize(),
success: function (result)
{
//THere was an error
if(result.error)
{
//So apply 'red' color to button
$("#my_button").addClass('red');
}
else
{
//there was no error. So apply 'green' color
$("#my_button").addClass('green');
}
}
});
return false;
});
});
</script>
<?php
//ajaxpage.php
//Do your processing here
if ( $processed )
{
$error = false;
}
else
{
$error = true;
}
print json_encode(array('error' => $error));
die();
?>

Categories