Jquery tabs: change ajax data on tab click - javascript

I have used jquery tabs for loading data with ajax, but I need to add some parameters to the url when the user clicks in a tab. I don't know the parameters in advance because they come from a form which has been filled by the user. So I've tried something like the following code, but I don't get it working:
<div id="tabs">
<ul>
<li>Tab 1</li>
<li>Tab 2</li>
<li>Tab 3</li>
</ul>
</div>
and I serialize the form in an array and join the array to the array containing the satic data.
var staticData = [{name:'id',value:'${myId}'}];
$("#tabs").tabs({
var $tabs = $("#tabs").tabs({
ajaxOptions: { data: staticData},
select: function(event, ui) {
var dynamicData = $("#common_form").serializeArray();
var dataToSend = staticData.concat(dynamicData);
$("#tabs").tabs("option", "ajaxOptions", { 'data': dataToSend });
return true;
}
});
});
but this doesn't update the ajax data after the tabs are created (I'm seeing the request sent with Firebug and it only includes the initial params).
How can I change the ajax data when the user clicks the tab?
Thanks
EDITED: now with this code works

I think that what you are looking for is the "url" method :
http://jqueryui.com/demos/tabs/#method-url
You code would look something like that :
$(function(){
$("#tabs").tabs({
select: function(event, ui) {
var data = $("#common_form").serialize();
if(ui.index == 1){
var url = '${tab2_url}' + "&" + data;
$("#tabs").tabs("url", 1, url); //this is new !
}
return true;
}
});
});

jQuery(document).ready(function($){
$("a[name=tab]").click(function(e){
if($(this).attr('id')=="tab1")
{
//pass url1
}
if($(this).attr('id')=="tab2")
{
//pass url2
}
if($(this).attr('id')=="tab3")
{
//pass url3
}
});
});
This work for me but if i need for ex 100 tabs i need to put in all 100 tabs url.

<div id="tabs">
<ul>
<li>Tab 1</li>
<li>Tab 2</li>
<li>Tab 3</li>
</ul>
</div>
Jquery code...
jQuery(document).ready(function($){
$("a[name=tab]").click(function(e){
if($(this).attr('id')=="tab1")
{
//pass url1
}
if($(this).attr('id')=="tab2")
{
//pass url2
}
if($(this).attr('id')=="tab3")
{
//pass url3
}
});
});

Related

JQuery Sortable get Target item

I have a table with the following structure:
<tbody>
<tr>
<td>
<button id=“elem_id”>Move</button>
</td>
<td>
</td>
</tr>
With this script:
$('tbody').sortable({
handle: '.drag_handle',
group: 'nested',
animation: 600,
ghostClass: 'drag_drop_class',
fallbackOnBody: true,
swapThreshold: 0.65,
onEnd: function (evt) {
var btn = evt.item.firstElementChild.firstElementChild;
let id = btn.id;
let oldIndex = evt.oldIndex;
let newIndex = evt.newIndex;
//TODO: Em vez do index da linha tenho de obter o id do destino
let component_name = btn.getAttribute('data-component');
// alert("[" + component_name + "] Alterou id=" + id + " da pos[" + oldIndex + "] para a pos[" + newIndex +"]");
//TODO: Emitir um evento para o componente livewire da tabela de modo a atualizar
Livewire.emitTo(component_name, 'reorder', id, newIndex);
}
});
I have access to the element/item that was dragged, but now I need the element/item that was dropped in to, I've tried a lot of stuff but nothing worked.
I have access to the index but that won't help me because the Data Table I'm using uses pagination and I need to get the position (its a property) of the item by id.
The project I'm working on uses this scripts:
<script src="https://cdnjs.cloudflare.com/ajax/libs/Sortable/1.10.2/Sortable.min.js" ></script>
<script src="https://cdn.jsdelivr.net/npm/jquery-sortablejs#latest/jquery-sortable.js"></script>
Maybe this example will help you. I could found an onEnd function within Sortable Jquery Ui.
HTML
<ul id="sortable">
<li class="name1">Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
<li>Item 4</li>
<li>Item 5</li>
</ul>
JQuery
$( "#sortable" ).sortable({
update: function( event, ui ) {
var item = ui.item;
var target_prev = ui.item.prev();
var target_next = ui.item.next();
console.log('item', item);
console.log('target_prev', target_prev);
console.log('target_next', target_next);
}
});
Just watch the console.log at your Developer Tools.
I figured out the project I'm working on does not use JQuery UI. It uses SortableJS. The equivalent code to JQuery UI I found, was the following:
onEnd: function (evt) {
var current = evt.item;
var prev = evt.item.previousElementSibling;
var next = evt.item.nextElementSibling;
}
For anyone with the same problem just console.log() this vars.

jQuery UI Sortable Connected Lists - Get Changed Status

I'm implementing sortable plugin of jQuery UI.
There are two columns and we can drag and drop an element from one column to another column.
I have the following javascript code:
$(function () {
$("#sortable1, #sortable2").sortable({
connectWith: ".connectedSortable",
update: function () {
var order1 = $('#sortable1').sortable('toArray').toString();
var order2 = $('#sortable2').sortable('toArray').toString();
alert("Order 1:" + order1 + "\n Order 2:" + order2);
$.ajax({
type: "POST",
url: "/echo/json/",
data: "order1=" + order1 + "&order2=" + order2,
dataType: "json",
success: function (data) {
}
});
}
}).disableSelection();
});
And HTML:
<ul id="sortable1" class="connectedSortable">
<li class="ui-state-default" id='item1'>Item 1</li>
<li class="ui-state-default" id='item2'>Item 2</li>
<li class="ui-state-default" id='item3'>Item 3</li>
<li class="ui-state-default" id='item4'>Item 4</li>
<li class="ui-state-default" id='item5'>Item 5</li>
</ul>
<ul id="sortable2" class="connectedSortable">
<li class="ui-state-highlight" id='item6'>Item 6</li>
<li class="ui-state-highlight" id='item7'>Item 7</li>
<li class="ui-state-highlight" id='item8'>Item 8</li>
<li class="ui-state-highlight" id='item9'>Item 9</li>
<li class="ui-state-highlight" id='item10'>Item 10</li>
</ul>
From above javascript, I can get the order of column 1 and column 2 after change as a whole. However, I would like to know the individual item that has been changed.
Like, in this image below, I have Item3 dragged from Column 1 to Column 2. I want to get output like - Item3_before=Column1,Item3_after=Column2.
In the javascript code above, by using start event like the update event, we can get the Before status of the elements, but not the individual element; it gives before status of all elements.
Few steps to take. I setup an Object to store the values at Activation, Pre-Sorting, and Post-Sorting for both lists. Once that was done, I used this method to determine the difference: JavaScript array difference
Working Example: https://jsfiddle.net/Twisty/kfedekmj/
jQuery
$(function() {
var items = {
"act": {
1: [],
2: []
},
"pre": {
1: [],
2: []
},
"post": {
1: [],
2: []
}
}
function log(et) {
if (!et) {
console.log("Activation");
console.log(" - order1: ", items.act[1].toString());
console.log(" - order2: ", items.act[2].toString());
}
if (et == "sortstart") {
console.log("Pre-Sort");
console.log(" - order1: ", items.pre[1].toString());
console.log(" - order2: ", items.pre[2].toString());
}
if (et == "sortupdate") {
console.log("Post-Sort");
console.log(" - order1: ", items.post[1].toString());
console.log(" - order2: ", items.post[2].toString());
}
}
function determineChange(a1, a2) {
var a = {},
diff = [],
i = 0;
for (i = 0; i < a1.length; i++) {
a[a1[i]] = true;
}
for (i = 0; i < a2.length; i++) {
if (a[a2[i]]) {
delete a[a2[i]];
} else {
a[a2[i]] = true;
}
}
$.each(a, function(k, v) {
diff.push(k);
});
return diff[0];
}
$("#sortable1, #sortable2").sortable({
connectWith: ".connectedSortable",
start: function(e, ui) {
// Start of Sort Order
items.pre[1] = $('#sortable1').sortable('toArray')
items.pre[2] = $('#sortable2').sortable('toArray')
log(e.type);
},
update: function(e, ui) {
// End of Sort Order
items.post[1] = $('#sortable1').sortable('toArray');
items.post[2] = $('#sortable2').sortable('toArray');
log(e.type);
/*
$.ajax({
type: "POST",
url: "/echo/json/",
data: "order1=" + order1 + "&order2=" + order2,
dataType: "json",
success: function(data) {}
});
*/
var newItem1 = determineChange(items.pre[1], items.post[1]);
console.log(newItem1);
}
}).disableSelection();
// Activation Order
items.act[1] = $('#sortable1').sortable('toArray');
items.act[2] = $('#sortable2').sortable('toArray');
log();
});
Leaving them as Arrays makes it a lot easier to compare and manipulate. Storing each part in an object simply makes it easier to gather all the info.
The only thing to be mindful of is that update runs 2 times. When an item is removed from list 1, out and added to list 2, receive. It does not make a difference in the end, but it's something to be mindful of just in case.

jQuery: Convert Attribute Values to Nested Array (Strings to Numbers)

Using jQuery, I would like to get each attribute value, insert it into an array and then insert each array into an array.
From this HTML:
<ul>
<li data-bbox="-121,20,-36,30">Item 1</li>
<li data-bbox="-122,30,-46,40">Item 2</li>
<li data-bbox="-123,40,-56,50">Item 3</li>
</ul>
I'm trying to create this type of nested array:
var bboxArray = [
[-121,20,-36,30],
[-122,30,-46,40],
[-123,40,-56,50]
];
...and convert the strings to numbers.
I'm assuming I need to do something like this:
var bboxArray = [];
$('li[data-bbox]').each(function() {
bboxArray.push($(this).attr('data-bbox').split(','));
});
Working Example
While your code does work, it is returning strings instead of the numbers you have in your required output this will do that:
I simply added .map(Number) at the end of your push
$('li[data-bbox]').each(function() {
bboxArray.push($(this).attr('data-bbox').split(',').map(Number));
});
You can use the .map() method like so:
var bboxArray = $('ul > li').map(function() {
return [ $(this).data('bbox').split(',') ];
}).get();
var bboxArray = $('ul > li').map(function() {
return [ $(this).data('bbox').split(',') ];
}).get();
console.log( bboxArray );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li data-bbox="-121,20,-36,30">Item 1</li>
<li data-bbox="-122,30,-46,40">Item 2</li>
<li data-bbox="-123,40,-56,50">Item 3</li>
</ul>

Deleting href when clicked on a link (a delete icon) beside it (Javascript help)

I have a link <a href="#"> and beside that there is a delete png icon (which is also <a href="#"> link.
So what I want is, when clicked on that delete icon, the link <a href="#"> should get deleted with a confirmation window.
So far I have got like,
html:
<ul>
<li>link <a class="delete" href="#" data-request="POST" >....</a></li>
</ul>
My javascript for data-request
var join_request = function(evnt){
evnt.preventDefault();
var $a = $(this);
var request = $a.data('request') || 'POST';
if (confirm("Are you sure want to delete it?")) {
$.ajax($a.attr('href'), {
type: request,
context: $a,
success: join_request_success
});
}
return false;
};
var join_request_success = function(data, a, b){
this.trigger('executed');
};
$(document).ready(function(){
$('a[data-request]').bind('click', join_request);
}
This doesn't seem to be working! When I am clicking on the delete icon, it is displaying the confirmation window but not doing anything.
Is there any other simple way of achieving this? If not, can anyone tell me where am I going wrong?
Thanks.
var join_request = function(evnt){
evnt.preventDefault();
var $a = $(this);
var request = $a.data('request') || 'POST';
if (confirm("Are you sure want to delete it?")) {
$.ajax($a.attr('href'), {
type: request,
context: $a,
error: join_request_success
});
}
return false;
};
var join_request_success = function(data, a, b){
this.trigger('executed');
this.prev().remove();
};
$(document).ready(function(){
$('a[data-request]').bind('click', join_request);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul>
<li>link <a class="delete" href="#" data-request="POST" >....</a></li>
</ul>
Note that I had to change success: to error: for demonstration.

Load data, insert after and slidetoggle

I`m kind of novice in jquery and want to make a sliding table.
The orinal table has 3 levels:
<ul class="categories">
<li id="category1">1 element</li> //parentid=0
<li id="category2">2 element</li> //parentid=0
<ul>
<li id="category3">1 element of element id2</li> //parentid=2
<ul>
<li id="category4">1 element id3</li> //parentid=3
</ul>
</li>
</ul>
</li>
</ul>
The first level elements have parentid = 0, id=1++, the next level have nested parentid and there own id and so on.
Page loads with only 1 level with parentid = 0.
<ul class="categories">
<li id="category1">1 element</li> //parentid=0
<li id="category2">2 element</li> //parentid=0
</ul>
Then I want to click the li, take id ID - go to file, execute mysql, get the new table in variable, bring it back and slideToggle it under LI.
php side
if(isset($_POST['subcategory'])){
$subcategory = str_replace('category', '', $_POST['subcategory']);
echo build_category_tree($subcategory); // builds the UL tree
}
this returns me id, i need to return the list and toggle it.
NOW the new UL is connected BUT i jquery cant work with it, updated the script with the one below but still cant.
UPDATED JQuery
$(".tablecategoryname").on('click', function(){
var $a = $(this).closest('li').attr('id');
var $c = $(this).closest('li');
$.ajax({
type: "POST",
url: "functions.php",
data: {subcategory:$a},
cache: false,
success: function(data)
{
$(data).hide().insertAfter($c).slideDown(400);
}
});
});
ID's should not contain just a number (or start with a number), you should probably use #a1 or something similar. In the data parameter you're sending an object, and equalsigns does'nt really work.
$(".table li").on('click', function(){
var self = this;
$.ajax({
type: "POST",
url: "functions.php",
data: {id : self.id},
cache: false
}).done(function(data) {
//guessing you're returning valid HTML
$(data).hide().insertAfter(self).slideDown(400);
});
});
EDIT:
Your build_category_tree() function needs to return the HTML so you can echo it back to the ajax request:
if(isset($_POST['subcategory'])){
echo $subcategory = str_replace('category', '', $_POST['subcategory']);
$ULtree = build_category_tree($subcategory); // builds the UL tree
echo $ULtree; //echo back to Ajax
}
You should put an id in your main ul to catch his parent and them toggle the list inside the main ul.
$("ul.umenu > li).click(function (e) {
e.preventDefault();
var element = $(this);
if (element.parent().find("ul").is(":visible")) {
} else {
$("ul.umain> li > ul").slideUp();
element.parent().find("ul").slideToggle("fast");
}
});

Categories