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]);
});
Related
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++;
}
Let's see if I can explain what I'm trying to do here..
I've got a MySQL Database with some info stored in it. I am using PHP to query the database, pull my selected entries out, put each one into a separate <div> (with Bootstrap framework). I have accomplished this part.
Below is a snippet of what I'm doing...
$query = "SELECT `quote`,`id` FROM `db`";
$result = mysqli_query($con,$query);
while($row = mysqli_fetch_array($result))
{
echo ' <div class="panel panel-info">
<div class="panel-body text-muted" id="'.$row['id'].'">
'.$row['quote'].'
</div>
</div>';
}
Then I am wanting to use jQuery to add a css class on "click" to an individual <div> and be able to then use PHP to store the text of the "selected" <div> to a variable, for later use.
This is the part I am struggling with, I can not figure out how to separate each individual <div> specifically and have jQuery add the class to it, because the "id" of div differs with every result from the db query.
To add a class to a div when it is clicked -
jQuery
$('div').click(function() {
$(this).addClass('foo');
var divText = $(this).text(); // store to JavaScript variable
});
Now that you have the JavaScript variable stored you can send it to a PHP function via AJAX.
What I would do is add a class to the <div>s, and use that to attach the event.
<div class="panel-body text-muted click-panel" id="'.$row['id'].'">
Then in your JavaScript, do something like:
$(function(){
$('div.click-panel').click(function(){
var div_id = this.id,
div_text = $(this).text();
if(/* some condition eg. div_id === 5 */){
$(this).addClass('clicked');
}
});
});
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;
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/
I have a page with text displayed in divs and spans. Next to each one I have an image that the user can click on.
When they click this image I need the text to change to a text area so the user can edit the text and then when they click of it it will need to call a php script to save to DB via ajax.
All divs and images have unique ID's so this should make it easier with the jquery selector.
Can anyone help? Everything I have tried so far is not really worked.
Thanks
You could make the div editable:
$(".ajax-div .on-img").on("click",function(ev) {
$(this).parent().find(".editable-text").attr("contenteditable", "true").after("<button onclick='saveEdits()'>Save</button>");
})
Your html structure would have to look like this
<div class="ajax-div" id="somediv">
<div class="editable-text">Editable text</div>
<img class="on-img" src="" alt="">
</div>
The saveEdits() function:
function saveEdits() {
$(".ajax-div").each(function() {
if(this.hasAttr("contenteditable") && this.attr("contenteditable")==true) {
id = $(this).attr("id");
//handle change
}
})
}
Let's say you have:
<div id='mydivparent'>
Some text here
<div>
<img src='images/mypic.jpg' id='mydiv' onclick='editr(this)' />
</div>
</div>
To do as your requirements suggest, an approach that would suffice is the below JS code.
<script>
function editr(obj)
{
var id = $(obj).attr('id');
var text = $('#mydiv'+parent).text();
$('#mydiv'+parent).empty();
$('#mydiv'+parent).append('<form action='form_processor.php' onsubmit="send_ajax($('textarea#'+id+').value)"><textarea id='+id+'>'+text+'</textarea><input type='submit' value='Save Text'></form>');
}
function send_ajax(txtValue){
$.ajax({
url: 'form_processor',
cache: false;
type: 'POST',
data: {'text': txtValue},
success: function(){
//Code to add the text to the div and delete the textarea returning it to a normal div
}
});
return false;
}
</script>
You should put in mind how to name the divs and images ids so that accessing a div's id from the image id is easy. You should use your own protocol so that if you have the image ID, you can get the asssociated div id, OR you can put the image inside the div so that it's as easy as selecting the PARENT.
After editing you can then set it up for ajax after the user.
The code is does not fully cover every situation for example if you click another imagebefore saving your first opened textarea but I believe that it will set you to the right road on the approach you should take.
I used jeditable plugin in the end to solve this one for anyone that finds this post