I am trying to update the content of a div with a $.get call but it is failing in ie(9).
the js is this
function UpdateElementOfParent(box_id, page_ref, template_ref)
{
$.get("get_content.php", { box_id: box_id, page_ref: page_ref, template_ref:template_ref } )
.done(function(data) {
$('#'+box_id).html(data);
});
}
and the get_content.php is this
<?php
include("connect.php");
$page_ref = $_GET['page_ref'];
$template_ref = $_GET['template_ref'];
$box_id = $_GET['box_id'];
$sql = mysql_query("SELECT * FROM site_content WHERE page_ref='$page_ref' AND template_ref='$template_ref' AND box_id='$box_id' AND box_type='text'");
while($row=mysql_fetch_array($sql))
{
echo stripslashes($row['content']);
}
?>
it works fine in firefox/chrome/safari and opera.
the php updates the db but the div ("#"+box_id) doesnt update in ie (only have ie9 at hand so dont know if its just 9 or other versions also)
any clues?
QUICK UPDATE
it seems that ie is holding some data from a previous $.get call in the cache. Basically I have a div on the screen and when the user clicks a button, a layer opens with a textarea that is editable with nicedit.
The textarea is populated with a $.get, then the user clicks save, the layer is hidden and the original div on the parent page is updated with the same $.get call.
In ie, if I change the content, the db is updated but the div is not and when I open the layer, it still shows the old data.
the first $.get call is this
$.get("get_content.php", { box_id: box_id, page_ref: page_ref, template_ref:template_ref } )
.done(function(data) {
document.getElementById("edit_content").value=data;
area1 = new nicEditor({fullPanel : true}).panelInstance("edit_content",{hasPanel : true});
});
the alerted data doesnt show the updated text in IE so its definately something to do with the $.get call
I figured out the problem. Nothing to do with the selector, but with the scope of the parameter variable box_id.
Change your function to:
function UpdateElementOfParent(box_id, page_ref, template_ref) {
myBox = box_id;
$.get("get_content.php", { box_id: box_id, page_ref: page_ref, template_ref:template_ref })
.done(function(data) {
$('#'+myBox).html(data);
});
}
Explanation:
The AJAX callback function does not have access to the local variable in UpdateElementOfParent
This isn't an answer, as the question is incomplete, but I need to post a code comment to assist OP.
As you mentioned that the PHP works just fine, the problem might be that IE doesn't like dynamic selectors in jQuery. Do try these few options:
1) Change $('#'+box_id).html(data); to:
var id = '#'+box_id;
$(id).html(data);
2) Try logging or alert-ing the element out, to see if IE actually got the element right:
var elem = $('#'+box_id);
alert(elem);
elem.html(data);
This would display as [HTMLDivElement] or something similar if the element is there.
3) If all else fails, see if this vanilla JS works in IE, to verify that it isn't a jQuery selector problem.
var elem = document.getElementById(box_id);
alert(elem);
elem.innerHTML = data;
ok problem solved and I knew it was something very obvious.
inside the original $.get function call I have to set the document.ready state
function get_edit_content(box_id,page_ref,template_ref)
{
$(document).ready(function() { <<<<<HERE
if(area1) {
area1.removeInstance('edit_content');
area1 = null;
document.getElementById("edit_content").value="";
}
$.get("get_content.php", { box_id: box_id, page_ref: page_ref, template_ref:template_ref } )
.done(function(data) {
document.getElementById("edit_content").value=data;
document.getElementById("page_ref").value=page_ref;
document.getElementById("template_ref").value=template_ref;
document.getElementById("box_id").value = box_id;
area1 = new nicEditor({fullPanel : true}).panelInstance("edit_content",{hasPanel : true});
});
});
}
thanks for all the input
Related
I'm trying when i submit a value to jqgrid box on multiple selected rows to Update the data of specific columns.My code is this but when i click OK in jqgrid nothing happens and function is not called :
jQuery(document).ready(function(){
jQuery('#list1').jqGrid('navButtonAdd', '#list1_pager',
{
'caption' : 'Resubmit',
'buttonicon' : 'ui-icon-pencil',
'onClickButton': function()
{
var str = prompt("Please enter data of Column")
var selr = jQuery('#list1').jqGrid('getGridParam','selarrrow');
$(selector).load('Updatestatus.php', {'string': str,'box[]' : selr })
},
'position': 'last'
});
});
The function that updates the column of the table:
function update_data($data)
{
// If bulk operation is requested, (default otherwise)
if ($data["params"]["bulk"] == "set-status")
{
$selected_ids = $data["cont_id"];
$str = $data["params"]["data"];
mysql_query("UPDATE out_$cmpname SET cont_status = '$str' WHERE cont_id IN ($selected_ids)");
die;
}
}
I'm new to jqgrid and Jquery.What can i do to call and execute this function when i click ok?
Thanks in advance!
You'll need a Ajax-call for this. I see you're using jQuery, have a look at http://api.jquery.com/load/
With this function, you can load PHP or HTML with jQuery to a certain element.
I need to be able to replace a php file with another php file based on screen resolution. This is what I have so far:
<script type="text/javascript">
function adjustStyle(width) {
width = parseInt(width);
if (width = 1920) {
$('book.php').replaceWith('book2.php');
}
}
$(function() {
adjustStyle($(this).width());
$(window).resize(function() {
adjustStyle($(this).width());
});
});
</script>
which obviously isn't working-- any ideas? Thank you in advance for any help received.
UPDATE
Is this at all close (to replace the book.php line)?
{ $("a[href*='book.php']").replaceWith('href', 'book2.php'); };
Second Update to reflect input gathered here
function adjustStyle(width) {
width = parseInt(width);
if (width == 1920) {
$('#bookinfo').replaceWith(['book2.php']);
$.ajax({
url: "book2.php",
}).success(function ( data ) {
$('#bookinfo').replaceWith(data);
});
$(function() {
adjustStyle($(this).width());
$(window).resize(function() {
adjustStyle($(this).width());
});
});
}
}
I have not seen the use of replaceWith in the context you put it in. Interpreting that you want to exchange the content, you may want to do so my using the load() function of jQuery.
if(width == 1920){
$("#myDiv").load("book1.php");
} else {
$("#myDiv").load("book2.php");
}
Clicking on the button replaces the content of the div to book2.php.
The first problem is I don't think that you are using the correct selectors. If you have the following container:
<div id="bookContainer">Contents of book1.php</div>
The code to replace the contents of that container should be
$('#bookContainer').replaceWith([contents of book2.php]);
In order to get [contents of book2.php] you will need to pull it in by ajax using the following code I have also included the line above so that the data from book2.php will be placed into the container:
$.ajax({
url: "http://yoururl.com/book2.php",
}).success(function ( data ) {
$('#bookContainer').replaceWith(data);
});.
I haven't tested this so there might be an issue but this is the concept you need to accomplish this.
First off... using a conditional with a single = (equal sign) will cause the condition to always be true while setting the value of variable your checking to the value your checking against.
Your condition should look like the following...
if (width == 1920) { // do something }
Second, please refer to the jQuery documentation for how to replace the entire tag with a jquery object using replaceWith()... http://api.jquery.com/replaceWith/
I would use a shorthand POST with http://api.jquery.com/jQuery.post/ since you don't have the object loaded yet...
In short, my code would look like the following using $.post instead of $.ajax assuming I had a tag with the id of "book" that originally has the contents of book.php and I wanted to replace it with the contents of book2.php...
HTML
<div id="book">*Contents of book.php*</div>
jQuery
function onResize(width) {
if (parseInt(width) >= 1920) {
$.post('book2.php',function(html){
$('#book').html(html).width(width);
});
}
else {
$.post('book.php',function(html){
$('#book').html(html).width(width);
});
}
}
Hope this helps.
I have several divs that a user can Minimize or Expand using the jquery toggle mothod. However, when the page is refreshed the Divs go back to their default state. Is their a way to have browser remember the last state of the div?
For example, if I expand a div with an ID of "my_div", then click on something else on the page, then come back to the original page, I want "my_div" to remain expanded.
I was thinking it would be possible to use session variables for this, perhaps when the user clicks on the expand/minimize button a AJAX request can be sent and toggle a session variable...IDK..any ideas?
There's no need for an ajax request, just store the information in a cookie or in the localstorage.
Here's a library which should help you out: http://www.jstorage.info/
Some sample code (untested):
// stores the toggled position
$('#my_div').click(function() {
$('#my_div').toggle();
$.jStorage.set('my_div', $('#my_div:visible').length);
});
// on page load restores all elements to old position
$(function() {
var elems = $.jStorage.index();
for (var i = 0, l = elems.length; i < l; i++) {
$.jStorage.get(i) ? $('#' + i).show() : hide();
}
});
If you don't need to support old browsers, you can use html5 web storage.
You can do things like this (example taken from w3schools):
The following example counts the number of times a user has visited a
page, in the current session:
<script type="text/javascript">
if (sessionStorage.pagecount) {
sessionStorage.pagecount=Number(sessionStorage.pagecount) +1;
}
else {
sessionStorage.pagecount=1;
}
document.write("Visits "+sessionStorage.pagecount+" time(s) this session.");
</script>
Others have already given valid answers related to cookies and the local storage API, but based on your comment on the question, here's how you would attach a click event handler to a link:
$("#someLinkId").click(function() {
$.post("somewhere.php", function() {
//Done!
});
});
The event handler function will run whenever the element it is attached to is clicked. Inside the event handler, you can run whatever code you like. In this example, a POST request is fired to somewhere.php.
I had something like this and I used cookies based on which user logged in
if you want only the main div don't use the
$('#'+div_id).next().css('display','none');
use
$('#'+div_id).css('display','none');
*Here is the code *
//this is the div
<div id = "<?php echo $user; ?>1" onclick="setCookie(this.id)" ><div>My Content this will hide/show</div></div>
function setCookie(div_id)
{
var value = '';
var x = document.getElementById(div_id);
var x = $('#'+div_id).next().css('display');
if(x == 'none')
{
value = 'block';
}
else
{
value = 'none';
}
console.log(div_id+"="+value+"; expires=15/02/2012 00:00:00;path=/")
//alert(x);
document.cookie = div_id+"="+value+"; expires=15/02/2012 00:00:00;path=/";
}
function getCookie(div_id)
{
console.log( div_id );
var i,x,y,ARRcookies=document.cookie.split(";");
for (i=0;i<ARRcookies.length;i++)
{
x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
x=x.replace(/^\s+|\s+$/g,"");
if (x==div_id)
{
return unescape(y);
}
}
}
function set_status()
{
var div_id = '';
for(var i = 1; i <= 9 ; i++)
{
div_id = '<?php echo $user; ?>'+i;
if(getCookie(div_id) == 'none')
{
$('#'+div_id).next().css('display','none');
}
else if(getCookie(div_id) == 'block')
{
$('#'+div_id).next().slideDown();
}
}
}
$(document).ready(function(){
get_status();
});
Look about the JavaScript Cookie Method, you can save the current states of the divs, and restore it if the User comes back on the Site.
There is a nice jQuery Plugin for handling Cookies (http://plugins.jquery.com/project/Cookie)
Hope it helps
Ended up using this. Great Tutorial.
http://www.shopdev.co.uk/blog/cookies-with-jquery-designing-collapsible-layouts/
Hey guys. I'm usign a js/ajax script that doesnt work with internet explorer. Firefox its ok.
Btw the head tag, im using this:
$(document).ready(function () {
//Check if url hash value exists (for bookmark)
$.history.init(pageload);
//highlight the selected link
$('a[href=' + document.location.hash + ']').addClass('selected');
//Seearch for link with REL set to ajax
$('a[rel=ajax]').click(function () {
//grab the full url
var hash = this.href;
//remove the # value
hash = hash.replace(/^.*#/, '');
//for back button
$.history.load(hash);
//clear the selected class and add the class class to the selected link
$('a[rel=ajax]').removeClass('selected');
$(this).addClass('selected');
//hide the content and show the progress bar
$('#content').hide();
$('#loading').show();
//run the ajax
getPage();
//cancel the anchor tag behaviour
return false;
});
});
function pageload(hash) {
//if hash value exists, run the ajax
if (hash) getPage();
}
function getPage() {
//generate the parameter for the php script
var data = 'page=' + encodeURIComponent(document.location.hash);
$.ajax({
url: "http://pathfofolder/js/loader.php",
type: "GET",
data: data,
cache: false,
success: function (html) {
//hide the progress bar
$('#loading').hide();
//add the content retrieved from ajax and put it in the #content div
$('#content').html(html);
//display the body with fadeIn transition
$('#content').fadeIn('slow');
}
});
}
The loader.php contain the php code to get pages, something like:
switch($_GET['page']) {
case '#link1' : $page = 'contenthere'; break;
}
echo $page;
So, on the links, i'm using Link 1 to load the content into the div content.
The script does works well with firefox, but with internet explorer it doesnt load the content. Could someone pls help me to fix this?
It not go into the success function at all on IE, and i'm getting no html error from IE too.
Best Regards.
Make sure your html is sounds. FF tends to auto fix the syntax.
A button click fires my function that fetches image data via an AJAX-call:
$("#toggle_album").click(function () {
album_id = $("#album_id").val();
$.post('backend/load_album_thumbnails.php', {
id: album_id
}, function(xml) {
var status = $(xml).find("status").text();
var timestamp = $(xml).find("time").text();
$("#album_thumbs_data_"+album_id+"").empty();
if (status == 1) {
var temp = '';
var output = '';
$(xml).find("image").each(function(){
var url = $(this).find("url").text();
temp = "<DIV ID=\"thumbnail_image\">[img-tag with class="faded" goes here]</DIV>";
output += temp;
});
$("#album_thumbs_data_"+album_id+"").append(output);
} else {
var reason = $(xml).find("reason").text();
var output = "<DIV CLASS=\"bread\">"+reason+"</DIV>";
$("#album_thumbs_data_"+album_id+"").append(output);
}
$("#album_thumbs_"+album_id+"").toggle();
});
});
The data is returned in XML format, and it parses well, appending the data to an empty container and showing it;
My problem is that my image overlay script:
$("img.faded").hover(
function() {
$(this).animate({"opacity": "1"}, "fast");
},
function() {
$(this).animate({"opacity": ".5"}, "fast");
});
... stops working on the image data that I fetch via the AJAX-call. It works well on all other images already loaded by "normal" means. Does the script need to be adjusted in some way to work on data added later?
I hope my question is clear enough.
Okay, apparantly I hadn't googled it enough. Surfing my own question here on stackoverflow pointed me to other questions, which pointed me to the JQuery live() function: live().
However, it does not work on hover(), so I rewrote the script to use mouseover() and mouseout() instead:
$("img.faded").live("mouseover",function() {
$(this).animate({"opacity": "1"}, "fast");
});
$("img.faded").live("mouseout", function() {
$(this).animate({"opacity": "0.5"}, "fast");
});
... and now it works flawlessly even on the content I fetch from the AJAX-call.
Sorry if anyone has started writing an answer already.
You have to bind the new events each time you add a DOM element to the page.
There is a built-in function in jquery called live that does that for you.
I noticed you add the images from your xml; you can add there the new binds too.
$(xml).find("image").each(function(){
//this actually creates a jquery element that you can work with
$('my-img-code-from-xml-goes-here').hover(
function() {
$(this).animate({"opacity": "1"}, "fast");
},
function() {
$(this).animate({"opacity": ".5"}, "fast");
}
//i did all my dirty stuff with it, let's add it where it belongs!
).appendTo($('some-already-created-element'));
});
EDIT: corrected a wrong sentence.