dynamically handle jquery events [closed] - php

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I have a list of main subjects streams. let's say they are Art, Science, Commerce. For each main steam there are several subjects.
Such as for Science, subjects are Mathamatics, Bio Science and etc.
When a user select a main stream, I want to show relevent subjects for the selected main stream.
I use jquery pannels. Basicaly, when a stream is checked the releveant subjects div will be toggle.
I get Main stream and subjects are from database. they can be change(dynamic). So how to handle this?
I used following code. But this is not dynamic.
$("#Science").change(function(){
$("#Mathas").slideToggle("fast");
});
$("#Bio_cience").change(function(){
$("#b").slideToggle("fast");
});
$("#Pure_Maths").change(function(){
$("#cc").slideToggle("fast");
});
I want to make above script dynamic. How to proceed?

You need something common between your checkbox and the div, and you probably don't need to make another trip to the server (via ajax) to do this. Instead add an attribute when you generate the page with PHP and then use the jQuery data() method to help make the association. For example:
<input type="checkbox" data-category="a">
<input type="checkbox" data-category="b">
<div id="main-stream-art-a">Content A</div>
<div id="main-stream-art-b">Content B</div>
<script>
$(function(){
$('input[type="checkbox"]').change(function() {
var category = $(this).data('category');
$('#main-stream-art-sub-' + category).slideToggle("fast");
});
})
</script>

Your html will like...
<div id="1sub" class="sub">sub1</div>
<div id="2sub" class="sub">sub2</div>
<div id="3sub" class="sub">sub3</div>
<div id="stream-1" class="stream" style="display:none;">Stream 1</div>
<div id="stream-2" class="stream" style="display:none;">Stream 2</div>
<div id="stream-3" class="stream" style="display:none;">Stream 3</div>
Now,in jquery
$(".sub").click(function(){
var subClicked = $(this).attr('id');
$(".stream").hide();
$("#stream-" + subClicked.substring(0,1)).toggle();
});

To periodically get updates from the server, you could use AJAX something like this:
function load_subjects(){
$.ajax({
url: "http://www.example.com/loader",
cache: false,
success: function(html){
$("#items").html(html);
}
});
}
setInterval(load_subjects, 240000);

I depends on how much data you need to load. It's a personal choice really, if there are just a few records then you could load them into an array as the page loads, for larger data sets I would use ajax.
Something like this can load html into your #display area
$("#Main_stream_arts").change(function(){
$.ajax({
type: "POST",
url: "some.php",
dataType: "html",
data: { id: $(this).val()}
}).done(function(html) {
$("#display").html(html);
});
});
You could also change the dataType to json and output a json encodeed string from PHP
Or a shorter version - depending on how much control you want:
$("#Main_stream_arts").change(function(){
$('#display').load('some.php?id='+$(this).val());
});

You could create a HTML structure like this which you could duplicate for every stream. This will be helpful if you have multiple streams in your HTML.
<div class="container">
<div class="header">
<input type="checkbox" value="Electronics" id="electronics" />
<label for="electronics">Electronics</label>
</div>
</div>
Then, assuming your data in database looks like this ,
{
"Electronics": [
"VLSI",
"Tele Communication",
"Digital Circuits",
"Analog Communication"
],
"Medicine": [
"MBBS",
"MD",
"General Surgeon",
"Dental"
],
"Computers": [
"fuzzy logic",
"DataStructures",
"JavaScript"
]
}
You could get value by json["Electronics"] - that's how we'll simulate an ajax call. Then your change event would look like this.
$(".header [type=checkbox]").change(function () {
//remove all the older values - not necessary
$(".content").slideToggle(500, function () {
e.preventDefault();
$(this).remove();
});
//check if youre checking or unchecking
if (this.checked) {
//choosing header
var $header = $(this).closest(".header");
//building container element with ul for subjects in stream
var $content = $("<div/>", {
"class": "content"
}).append("<ul></ul");
var value = this.value;
//simulate ajax call -
var json = res[value];
//ajax here. result is json
//ajax success start - starting here , you could put this in the success function of ajax
//construct the lis - u could do it in any way
var $li = $.map(json, function (val, i) {
return "<li>" + val + "</li>";
});
//add the li to the uls
$content.find("ul").append($li);
//insert the content after specific header
$content.insertAfter($header).promise().done(function () {
//wait for the append to happen, else you wont get the animation
//open up the content needed
$content.slideToggle(500);
});
//ajax success end
}
});
Basically we're adding an element which contains the subjects in a stream dynamically right next to the header. So this will help if you have multiple streams in your HTML. So the resulting HTML would look like this :
<div class="container">
<div class="header">
<input type="checkbox" value="Electronics" id="electronics" />
<label for="electronics">Electronics</label>
</div>
<div class="content">
<ul>
<li>Fuzzy Logic</li>
<!--more li's like this-->
</ul>
</div>
</div>
Demo : http://jsfiddle.net/hungerpain/Uyugf/

Related

How Make Div Sortable And Updating Value In Database

i want to make my divs sort-able using jquery and getting their current new position so i can update that into database. i tried but not succeed. my code is
<div id="d">
df
</div>
<div id="d">
df
</div>
<div id="d">
df
</div>
jquery code is
$(document).ready(function(){
$('#d').sortable({
placeholder: "ui-state-highlight",
helper: 'clone'
});
});
})
anyone please help me out .thanks
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.
$('#el1').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'
});
}
});
It creates an array of the elements using the elements id. So, I usually do something like this:
<div id="el1" class="ui-sortable">
<div id="item_1">
df
</div>
<div id="item_2">
df
</div>
<div id="item_3">
df
</div>
</div>
Serialize option will create a POST query string like this: item[]=1&item[]=2 . 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.
$i = 0;
foreach ($_POST['item'] as $value) {
// Execute statement:
// UPDATE [Table] SET [Position] = $i WHERE [EntityId] = $value
$i++;
}

Codeigniter - refresing multiple elements with multiple contents using JQuery ajax?

what I want to achieve is that multiple divs in my view get fill up with different content using ajax at the same time when a button is clicked, let's say something like this:
view:
<div id="one">
</div>
<div id="two">
</div>
<div id="three">
</div>
div one, two and three should be refreshed with different content each one.
my script is:
$("input[type='button']").click(function(){
var mail= $("#mail").val();
var password = $("#password").val();
$.ajax({
url: '<?php echo base_url()?>index.php/login/theLogin',
type: 'POST',
data: {'mail':mail, 'password':password},
success: function(data) {
$('div#one').html(data);
$('div#two').html(data);
$('div#three').html(data);
}
});
});
controller:
public function theLogin()
{
$this->load->view("ajax/newContent");
}
newContent.php:
<div id="ajax-one">
one
</div>
<div id="ajax-two">
two
</div>
<div id="ajax-three">
three
</div>
and the result is obviously the three divs in my view get refreshed with three divs (9 divs in total), but I don't want that, I want that div one gets refreshed only with the content of div ajax-one and so on.
I used something like this in my ajax method but no success:
success: function(data) {
$('#one').html($('#ajax-one' , data).html());
$('#two').html($('#ajax-two' , data).html());
$('#three').html($('#ajax-three' , data).html());
}
What possible solution could exists to solve this? thanks.
I would replace the DIVs with the new DIVs. So if you have a parent DIV you can replace the whole thing with the new data.
Consider this being your initial view:
<div id="myWrapperDiv">
<div id="one">
</div>
<div id="two">
</div>
<div id="three">
</div>
</div>
When your data is returned do this:
$("#myWrapperDiv").html(data);
UPDATE:
Since that was not a good option for you I have come up with another possible solution. Personally I would return a JSON array that separated the DIVs, however, I will offer a suggestion to work with your current code. I would split the return into an array and process it from there.
Let me show you. In the below we split the data on the closing div tags with a limit of 3. Without the limit you will get an empty string at the end of your array. Then we replace the contents of your DIVs with the ajax DIVs. We have to add back the closing div tags since it was removed when we split the data. I hope this helps :).
var myArray = data.split("</div>",3);
$("#one").html(myArray[0] + "</div>");
$("#two").html(myArray[1] + "</div>");
$("#three").html(myArray[2] + "</div>");
Here is a working fiddle. Change you response data to jQuery object. Hope this is what you need.
$("input[type='button']").click(function(){
var data = '<div id="ajax-one"><span>one</span></div><div id="ajax-two">two</div><div id="ajax-three">three</div>';
var $dataObj = $(data);
$('#one').html($dataObj[0]);
$('#two').html($dataObj[1]);
$('#three').html($dataObj[2]);
});

Cannot show div popup even after a successful ajax post

I have a div
<div id="pop2" class="pop-up1" style="display:none;">
<div class="popBox1">
<div class="popScroll1">
<h2></h2>
<p id="p1_id"></p>
</div>
<span>Close</span></span>
</div>
Back to links
</div>
I have an external file edit_invoice_details.php in which I want to post some data which I am doing through this jquery function
<script>
$(document).ready(function(){
$('table tbody tr').dblclick(function(){
//alert($("#myId2").text());
//showeditDiv($( "#myId2" ).text());
var invid=$("#myId2").text();
var pid=$("myId").text();
var dataString = 'inv_id='+ invid+'prod_id='+pid;
$.ajax({
type: "POST",
url: "edit_invoice_details.php",
data: dataString,
cache: false,
success: function(html)
{
alert("success");
$("#pop2").show();
$("#p1_id").html(html).show();
}
});
});
});
</script>
I want such a table such that when someone double clicks on it the div should open. Success alert is working fine. but I am not able to show that div. The divs content should be edit_invoice_details.php. Response text maybe
Any help is appreciated
Try this:
$("#pop2").style.display = "block";
if it dont work then there might be other problems. Let me know.
sometimes if you hardcode the property display in the html tag like you did here
<div id="pop2" class="pop-up1" style="display:none;">
when you tried to show the div it won't work, try set the display to none in the css instead of hardcode the css in the html tag, that happened to me and I fixed that way.
also with this code
$("#p1_id").html(html).show();
you are now showing the #p1_id selector, you are showing what is inside the #p1_id, tried some like
$("#p1_id").html(html);
$("#p1_id").show();
let me know if works for you the two possible issues that I wrote.
I think you need to use a & here:
var dataString = 'inv_id='+ invid+'&prod_id='+pid;

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;
});

Ajax request inside ajax request fails - reloads the whole page again

So, basicly what I'm trying to achieve:
In index.php
I would enter products code to search for products information and it's images (that query is run in open_first.php, called via ajax post request).
It works just perfect..
When open_first.php is loaded, it displays me some images I can select from (when I click on the image, it's relevant checkbox get's checked containing the image id).
This works too, just fine.
BUT,
If I enter a code in the field: "productCodeCopy" and click on "confirmCodeCopy" -button it reloads the whole page, I mean index.php and everything I've entered is lost and I'm back in the starting point again. I don't understand why it does so. I suppose it has something to do with the fact, that the second ajax request is made from a dynamically created page (open_first.php)?? Do I miss something I should POST too?? Or what's the problem, this is really frustrating me since I've tried to fix this for hours now.
Note:
Jquery is loaded in index.php, open_first.php and open_second.php, I've just ignored that to keep the code simpler.
FILE: index.php (the "starting point")
<!-- head -->
<script type="text/javascript">
$(document).ready(function() {
$("#confirmCode").on('click', function(){
var productCode = $("#productCode").val();
$.ajax({
url: 'open_first.php',
type: "POST",
data: ({code: productCode}),
success: function(data){
$("#found").html(data);
},
error: _alertError
});
function _alertError() {
alert('error on request');
}
});
});
</script>
<!-- body -->
<input type="text" class="textfields" id="productCode" name="productCode" value="YT-6212">
<input type="button" class="admin-buttons green" name="confirmCode" id="confirmCode" value="Search">
<div id="found"></div>
FILE open_first.php
<script type="text/javascript">
$(function() {
$("#foundImage").on('click', function(){
$('#foundImage').toggleClass("foundImage-selected foundImage");
var myID = $('#foundImage').data('image-id');
var checkBox = $('input[id=selectedImages-'+myID+']');
checkBox.prop("checked", !checkBox.prop("checked"));
});
$("#confirmCodeCopy").on('click', function(){
var checkedItems = $('input:checkbox[name="selectedImages[]"]:checked');
// this code here reloads the whole page / view (as in "index.php")
$.ajax({
url: 'open_second.php',
type: "POST",
data: ({checked: checkedItems, copyTo: productCodeCopy, code: "<?php echo $_POST['code']; ?>"}),
success: function(data){
$("#copyToProducts").append(data);
},
error: _alertError
});
/*
// the code below runs just fine when I hit the button "confirmCodeCopy"
alert('Fuu');
return false;
*/
});
function _alertError() {
alert('error');
}
});
</script>
<!--BODY-->
<!-- these are dynamically generated from php, just to simplify we have checkbox that contains value "1" to be posted in ajax -->
<div class="foundImage" id="foundImage" data-image-id="1"><img src="image.jpg"><input type="checkbox" id="selectedImages-1" name="selectedImages[]" value="1" style="display: none;"></div>
<label for="productCodeCopy">Products code</label>
<input type="text" class="textfields" id="productCodeCopy" name="productCodeCopy">
<br /><br />
<label for="confirmCodeCopy"> </label>
<input type="button" class="admin-buttons green" name="confirmCodeCopy" id="confirmCodeCopy" value="Search">
<div id="copyToProducts"></div>
open_second.php only prints out POST variables for now, so nothing special yet.
SOLVED
So ok, I solved it. With dumdum's help.
I removed the line:
$('input:checkbox[name="selectedImages[]"]:checked');
And added this:
var checkedItems = new Array();
var productToCopy = $('#productCodeCopy').val();
$("input:checkbox[name=selectedImages[]]:checked").each(function() {
checkedItems.push($(this).val());
});
Since there was no form element present, it didn't get the field values unless "manually retrieved" via .val() -function.. Stupid me..
I don't know how much this affected but I changed also:
data: ({checked: checkedItems, copyTo: productCodeCopy"})
To
data: {"checked": checkedItems, "copyTo": productToCopy}
So now it's working just fine :) Cool!
WHen you apply event hander to a button or a link to do ajax...always prevent the browser default processing of the click on that element
There are 2 ways. Using either preventDefault() or returning false from handler
$("#confirmCodeCopy").on('click', function(event){
/* method one*/
event.preventDefault();
/* handler code here*/
/* method 2*/
return false;
})
The same is true for adding a submit handler to a form to do ajax with form data rather than having the form redirect to it's action url
your code $('input:checkbox[name="selectedImages[]"]:checked'); is returning undefined making the json data in the ajax call invalid. Check you selector there.

Categories