jQuery click function and Callback Arrays - php

I`m new to jQuery and have a problem understanding functions.
I have the following structure of HTML code:
<ul class="result">
<li id="a"></li>
<li></li> //will be added through a loop depending on input
</ul>
And this jQuery code:
$(document).ready(function() { //changes are possible when the page has fully loaded
$('.inp').keyup(function() { //executes keyup function to the field class "inp"
var inp = $(this).attr('value'); //sets a variable with the value of input from class="inp"
$.post('ajax/file.php', {inp:inp}, function(data) { //posts that value to file.php as variable inp and executes the function (data) to this
$('.result').html(data); //adds the returned result into HTML content as a first element in the set of class="result" => <li>
$('.result li').click(function() { //executes click function when clicking li element
var result_value = $(this).text(); //sets a variable and prepares something as text
$('.inp').attr('value', result_value); //fills value attribute of field class "inp" with the variable result_value
$('.result').html(''); //???
});
});
});
});
Now my question is what $('.result').html(''); does?

JQuery .html() property sets the html of the object it is mapped to, it have same behavior like the javascript property .innerHTML.
So here in your scenario $('.result').html(''); will set the html of result class element to null.
<ul class="result">
</ul>
Secondly, you are using wrong approach in your 'file.php', instead use this code:
echo '<li>'.$row["name_1"].'</li>';
echo '<li>'.$row["name_2"].'</li>';
echo '<li>'.$row["name_3"].'</li>';

$('.result').html(''); sets the html of .result to a blank string.

$('.result').html(''); clears the contents of <ul class="result">.
http://api.jquery.com/html/

Related

How to display appending data without refresh in tree

This is my tree view
I have already done that when i do right click tree name(For example ,Asset, Non Current , Shah) and click add head Then there will come jquery dialog form and I add head code and head name and it is saved successfully in mysql database using codeigniter frame work in php.
Basically , it is created subhead under head.
I need when after submitting, it will be display subhead under that head without refresh tree. For Example ,
If i create subhead under asset then append subhead after "104-Kamrul" without refresh and Display without Change.
How can i solve it, Please any suggestions?
i think you need ajax to make what you need, just use a specific class for each tree parent for example:
<div class="parent-1">
<div class="child-1"></div>
<div class="child-2"></div>
</div>
<div class="parent-2">
<div class="child-1"></div>
<div class="child-2"></div>
</div>
now just load what you need following parents classess:
$('.parent-1').children('.child-1').load('http://site.com/url/to/load/new/childs');
or
var _childs = $.get('http://site.com/url/to/get/some/childs');
$('.parent-1').append(_childs);
Given the following markup:
<div id="tree">
<ul>
<li>Asset
<ul>
<li>101-Non Current</li>
<li>102-Current Asset</li>
<li>103-Abdul Halim Shah
<ul>
<li>10301-Shah
<ul>
<li>1030101</li>
</ul>
</li>
</ul>
</li>
<li>104-Kamrul</li>
</ul>
</li>
<li>2-Expenses</li>
</ul>
</div>
I wrote a couple of jQuery functions to dynamically add new nodes. One adds the node below the selector specified and the other adds it as a sibling:
function addSibling(selector, content) {
var markup = '<li>' + content + '</li>';
$(selector).parent().append(markup);
}
function addChild(selector, content){
var obj = $(selector);
var markup='<li>' + content + '</li>';
var element;
if ($('ul', selector).length > 0){
//nested list
element = obj.find('> ul');
} else {
element = obj;
markup = '<ul>' + markup + '</ul>';
}
element.append(markup);
}
Although you'll have to adapt them to your code, you can use the following click function to test them:
$("#tree ul").click(function (e) {
//addSibling(e.target, 'new one');
addChild(e.target, 'new one');
e.stopPropagation();
});
I didn't understand what your variable were, but to get the data to the server without a page load, you can use an ajax function something like the following:
$('#form').submit(function() {
var headCode = $('input[name="headCode"]').val();
var headName = $('input[name="headName"]').val();
$.ajax({
url: "load.php",
type: 'POST',
data: {
head_code: headCode,
head_name: headName
},
cache: false,
success: function(json){
alert('loaded');
}
});
return false;
});

jQuery UI Sortable, then write order into a database

I want to use the jQuery UI sortable function to allow users to set an order and then on change, write it to the database and update it. Can someone write an example on how this would be done?
The jQuery UI sortable feature includes a serialize method to do this. It's quite simple, really. Here's a quick example that sends the data to the specified URL as soon as an element has changes position.
$('#element').sortable({
axis: 'y',
update: function (event, ui) {
var data = $(this).sortable('serialize');
// POST to server using $.post or $.ajax
$.ajax({
data: data,
type: 'POST',
url: '/your/url/here'
});
}
});
What this does is that it creates an array of the elements using the elements id. So, I usually do something like this:
<ul id="sortable">
<li id="item-1"></li>
<li id="item-2"></li>
...
</ul>
When you use the serialize option, it will create a POST query string like this: item[]=1&item[]=2 etc. So if you make use - for example - your database IDs in the id attribute, you can then simply iterate through the POSTed array and update the elements' positions accordingly.
For example, in PHP:
$i = 0;
foreach ($_POST['item'] as $value) {
// Execute statement:
// UPDATE [Table] SET [Position] = $i WHERE [EntityId] = $value
$i++;
}
Example on jsFiddle.
Thought this might help as well. A) it was designed to keep payload to its minimum while sending back to server, after each sort. (instead of sending all elements each time or iterating through many elements that server might chuck out) B) I needed to send back custom id without compromising the id / name of the element. This code will get the list from asp.net server and then upon sorting only 2 values will be sent back: The db id of sorted element and db id of the element next to which it was dropped. Based on those 2 values, server can easily identify the new postion.
<div id="planlist" style="width:1000px">
<ul style="width:1000px">
<li plid="listId1">List 1</li>
<li plid="listId2">List 1</li>
<li plid="listId3">List 1</li>
<li plid="listId4">List 1</li>
</ul>
<div id="pl-1"></div>
<div id="pl-2"></div>
<div id="pl-3"></div>
<div id="pl-4"></div>
</div>
<script type="text/javascript" language="javascript">
$(function () {
var tabs = $("#planlist").tabs();
tabs.find(".ui-tabs-nav").sortable({
axis: "x",
stop: function () {
tabs.tabs("refresh");
},
update: function (event, ui) {
//db id of the item sorted
alert(ui.item.attr('plid'));
//db id of the item next to which the dragged item was dropped
alert(ui.item.prev().attr('plid'));
//make ajax call
}
});
});
</script>
You're in luck, I use the exact thing in my CMS
When you want to store the order, just call the JavaScript method saveOrder(). It will make an AJAX POST request to saveorder.php, but of course you could always post it as a regular form.
<script type="text/javascript">
function saveOrder() {
var articleorder="";
$("#sortable li").each(function(i) {
if (articleorder=='')
articleorder = $(this).attr('data-article-id');
else
articleorder += "," + $(this).attr('data-article-id');
});
//articleorder now contains a comma separated list of the ID's of the articles in the correct order.
$.post('/saveorder.php', { order: articleorder })
.success(function(data) {
alert('saved');
})
.error(function(data) {
alert('Error: ' + data);
});
}
</script>
<ul id="sortable">
<?php
//my way to get all the articles, but you should of course use your own method.
$articles = Page::Articles();
foreach($articles as $article) {
?>
<li data-article-id='<?=$article->Id()?>'><?=$article->Title()?></li>
<?
}
?>
</ul>
<input type='button' value='Save order' onclick='saveOrder();'/>
In saveorder.php; Keep in mind I removed all verification and checking.
<?php
$orderlist = explode(',', $_POST['order']);
foreach ($orderlist as $k=>$order) {
echo 'Id for position ' . $k . ' = ' . $order . '<br>';
}
?>
This is my example.
https://github.com/luisnicg/jQuery-Sortable-and-PHP
You need to catch the order in the update event
$( "#sortable" ).sortable({
placeholder: "ui-state-highlight",
update: function( event, ui ) {
var sorted = $( "#sortable" ).sortable( "serialize", { key: "sort" } );
$.post( "form/order.php",{ 'choices[]': sorted});
}
});
I can change the rows by following the accepted answer and associated example on jsFiddle. But due to some unknown reasons, I couldn't get the ids after "stop or change" actions. But the example posted in the JQuery UI page works fine for me. You can check that link here.
Try with this solution: http://phppot.com/php/sorting-mysql-row-order-using-jquery/
where new order is saved in some HMTL element.
Then you submit the form with this data to some PHP script,
and iterate trough it with for loop.
Note: I had to add another db field of type INT(11) which is updated(timestamp'ed) on each iteration - it serves for script to know which row is recenty updated, or else you end up with scrambled results.

Jquery tabs with load more button

hi is there any reference/sample for php ajax tabs with load more functionality within each tabs? Lets say we have 2 tabs and when we click each tab it will display only selected number of result until we click load more button at end of each result. Thanks. My current code seems not works well,when i click each tabs it display result correctly but when i click the tabs again it loads more data.Below are my current code:
<li data-tab-id="self" class="tab selected">Near You<span class="unread-count hidden" style="display: none;"></span></li>
<li data-section-id="user_feed" data-component-bound="true">
<ul class="module-list">
<!-- USER ACTIVITY JSON -->
</ul>
<a class="ybtn ybtn-primary ybtn-large more-wishlist" href="#" onclick="getRecentActivityClick(event)">
<span data-component-bound="true" class="loading-msg user_feed">See more recent activity</span>
</a>
</li>
<script type="text/javascript">
var totalRecords = '<?= $this->totalRecords?>';
$(document).ready(function(){
getRecentActivity(totalRecords);
});
$(".hd-ui-activity li a").click(function(e) {
e.preventDefault();
var tabid = $(this).parent().attr('data-tab-id');
if(tabid == "self"){
getRecentActivity(totalRecords);
}
});
function getRecentActivityClick(event)
{
if (event != null){
disabledEventPreventDefault(event);
}
getRecentActivity(totalRecords);
}
home.js:
function getRecentActivity(totalRecords)
{
$.ajax({
url:baseUrl + "activity/activityfeed",
data:{'total':totalRecordsView},
dataType:"json",
type:"POST",
success:function(data){
var activityHtml = '<p>Hello</p>';
$('#activity-feed li[data-section-id=near_you] .module-list').append(activityHtml);
}
});
}
UPDATE:
JSFIDDLE: http://jsfiddle.net/zlippr/5YkWw/1/
with what i understood from your question.. i think you are getting more datas since u are using.. append()..
use html()
append() inserts content, specified by the parameter, to the end of each element in the set of matched elements.
html() is used to set an element's content, any content that was in that element is completely replaced by the new content.
try this
replace
$('#activity-feed li[data-section-id=near_you] .module-list').append(activityHtml);
with
$('#activity-feed li[data-section-id=near_you] .module-list').html(activityHtml); //html()
You can do this:
$('#activity-feed li[data-section-id=near_you] .module-list').append(activityHtml);
// here you are appending the fulldata just apply some css here
use css this way:
$('#activity-feed li[data-section-id=near_you] .module-list')
.css({'height':'300px','overflow':'hidden'})
.append(activityHtml);
then click the loadmore:
$('your load more button').toggle(function(){
$('#activity-feed li[data-section-id=near_you] .module-list')
.css({'height':'auto','overflow':'auto'})
},function(){
$('#activity-feed li[data-section-id=near_you] .module-list')
.css({'height':'300px','overflow':'hidden'});
});

How to get index of input in javascript - can use jQuery

I have an array of inputs generated from js code. I have set the name of the inputs like this: name="myTextInput[]"
How can I get the index of the selected input?
I tried something like:
onClick="oc(this);"
where:
function oc(inp)
{
return(inp.index);
}
but is not working.
I can use jQuery as well
You can use the EACH function in jquery. This will parse through the set of matched elements. You can put a custom function inside that will use the index of each element, as you parse through, as an argument.
$('input').each(function(index){
alert(index);
});
You can also get the value of each input like this:
$('input').each(function(index, val){
alert(index + ' has value: ' + val);
});
see details here: http://api.jquery.com/jQuery.each/
** EDIT **
If you want the value shown in an alert box on click, use the each function and the click function together. Remember to get the real-time value of the input, use $(this).val(). Return index and value data on click:
$('input').each(function(index, val){
$(this).click(function(){
alert(index + ' has value: ' + $(this).val());
});
});
You could get the input like this (not sure if you actually wanted the click event though)...
var inputs = $('input[name="myTextInput[]"]');
inputs.click(function() {
alert(inputs.index(this));
});
Please use the index() method to find the position of an element.
Check out this example: http://jsbin.com/uyucuv/edit#javascript,html
<ul>
<li id="foo">foo</li>
<li id="bar">bar</li>
<li id="baz">baz</li>
</ul>
$(function() {
$("li").on("click", function() {
alert($(this).index());
});
});
Check the index() documentation here: http://api.jquery.com/index/
Hope this helps!
The "jQuery way" is to avoid onClick="whatever()" and use pure JavaScript separate from the HTML tags. Try this between a pair of <script> tags (note: requires jQuery 1.7 or higher):
$('input').on('click', function() {
var varname = $(this).attr('name'),
$arr = $('input[name="'+varname+'"]'),
idx = $arr.index(this);
alert(idx);
});​
http://jsfiddle.net/mblase75/EK4xC/

jquery php div tag assign

I have this jquery script to assign a div tag with data from a url:
$(function() {
$(".loadlink").click(function(event) {
event.preventDefault();
$("#result").load($(this).data('url'));
});
});
As well as the #result div, I want to add another div called #crimes which also updates after the one above had ran with data from page2.php.
How can I change this to accommodate that extra div?
You can target multiple elements by comma separating them
$("#result, #crimes").load($(this).data('url'));
Or if crimes doesn't exist yet...
//create an element
var $crimes = $('<div />', {
id: 'crimes',
class: 'myclass'
});
//append the element inside something else
$('selector').append($crimes);
$("#result, #crimes").load($(this).data('url'));

Categories