Codeigniter scripts loading twice/not being removed with partial views - php

So, I load partial views inside the "main" view, and put the content inside a div, like this:
<div class="page-content" id="inside_page"></div>
<script>
$("#myTab").click(function() {
location.hash="myTab";
App.blockUI({
boxed: !0
});
$.ajax({
type: 'POST',
url: "<?php echo base_url();?>"+"index.php/welcome/myTabContent",
data: {},
dataType: "html",
success: function(data) {
if (data.status == 2) {
window.location = "/";
}else{
window.scrollTo(0, 0);
App.unblockUI();
$("#inside_page").empty();
$("#inside_page").html(data);
}
},
error: function (xhr, status, errorThrown) {
App.unblockUI();
bootbox.alert("<p>Error</p>");
}
});
});
</script>
The partial view includes tags, and when I change tabs, or load the tab again, scripts that have been already loaded, will not be removed and will keep running until the user reloads the page. How can I stop that from happening?

Related

function loads only on change, i would it to load on document load

My knowledge of this is very limited, but I figured that the problem that I have is in this function. What it does is that it displays some options to be selected in an item post. From what I see it only loads when a category is changed. Because of that when you edit this post, this function will not display unless you change category to another one and then revert back to the one you want. I would like it to display every time, except for those categories that are in the if statement.
Please assist....
$(document).on('change', "#catId", function () {
var optgroups = $(this).children("optgroup[label='Nekretnine'], optgroup[label='Posao'], optgroup[label='Usluge'], optgroup[label='Poljoprivredni oglasi'], optgroup[label='Kućni ljubimci'], optgroup[label='Turizam']");
$(optgroups).each(function(){
if($(optgroups).children("option:selected").length){
$("#condition-container").html('');
} else {
$.ajax({
url: ajaxURL,
type: "get",
data: "request=condition-fields",
dataType: "html",
success: function(data) {
if(data) {
$("#condition-container").html(data);
}
}
});
}
});
});
You just need to trigger your change event on document load. So under you on change function put this code
$(document).on('change', "#catId", function () {
var optgroups = $(this).children("optgroup[label='Nekretnine'], optgroup[label='Posao'], optgroup[label='Usluge'], optgroup[label='Poljoprivredni oglasi'], optgroup[label='Kućni ljubimci'], optgroup[label='Turizam']");
$(optgroups).each(function () {
if ($(optgroups).children("option:selected").length) {
$("#condition-container").html('');
} else {
$.ajax({
url: ajaxURL,
type: "get",
data: "request=condition-fields",
dataType: "html",
success: function (data) {
if (data) {
$("#condition-container").html(data);
}
}
});
}
});
});
//Trigger change
$(document).ready(function () {
$("#catId").trigger("change");
});
hi I assume you want the function fired on document load and on change, but for that you will need to use 2 triggers.
1) you allready have the on change trigger
2) use the $(document).ready() (https://learn.jquery.com/using-jquery-core/document-ready/) wrapper for onload.
There is possibly a much more gracefull solution, but I'm no JS expert so this will only get you to a working, although not the pretiest state

Ajax tooltip doesn't disappear if mouse moves too fast

I have a tooltip loaded with ajax for each item on my webpage. When you move the mouse too fast, it doesn't take the mouseleave event into account. Then, I tried to load the tooltip content with the page. However, there are a lot of contents so it takes four more seconds to load :/
What can I do?
Here is my jquery code :
$('.main').on({
mouseenter: function(){
var id = $(this).parent().data('candy');
if(id != 0){
$.ajax({
url: 'tooltip.php',
type: 'get',
data: { 'type': 'candy', 'item_id': id },
global : false,
success: function(data){
$('.candyTooltip').html(data);
$('.candyTooltip .layer_item').show();
}
});
}
},
mouseleave : function(){
$('.candyTooltip .layer_item').hide();
}
}, '.candy');
Also, I don't know if it's relevant but the SQL query takes 1,2ms and the PHP script takes 3,94ms.
I finally found a way to do it !!!
All I had to do was put the ajax request inside a variable and abort it on mouseleave.
So, now it looks like this :
$('.main').on({
mouseenter: function(){
var id = $(this).parent().data('candy');
if(id != 0){
query = $.ajax({
url: 'tooltip.php',
type: 'get',
data: { 'type': 'candy', 'item_id': id },
global : false,
success: function(data){
$('.candyTooltip').html(data);
$('.candyTooltip .layer_item').show();
}
});
}
},
mouseleave : function(){
if (query) { query.abort(); }
$('.candyTooltip .layer_item').hide();
}
}, '.candy');

jQuery / Ajax to get html and save with php

I am trying to get a jQuery script to run behind the scenes with php. It basically will get the contents of a div with jQuery (works) then calls a script with ajax (works) but I need the ajax script that called the php to send the vars to php so I can save the conents.
Here is the code:
<script>
$( document ).ready(function() {
$( ".tweets" ).click(function() {
var htmlString = $( this ).html();
tweetUpdate(htmlString);
});
});
</script>
<script>
function tweetUpdate(htmlString)
{
$.ajax({
type: "POST",
url: 'saveTweets.php',
data: htmlString,
success: function (data) {
// this is executed when ajax call finished well
alert('content of the executed page: ' + data);
},
error: function (xhr, status, error) {
// executed if something went wrong during call
if (xhr.status > 0) alert('got error: ' + status); // status 0 - when load is interrupted
}
});
}
</script>
and my code for saveTweets.php
<?
// SUPPOSED TO receive html conents called htmlString taken from a div
// and then I will write this code to a file with php and save it.
echo $_POST[htmlString];
?>
You have to give a name to the parameter, so that PHP can retrieve it. Change the $.ajax call to do:
data: { htmlString: htmlString },
Then in your PHP, you can reference $_POST['htmlString'] to get the parameter.
Correct your funcion.
function tweetUpdate(htmlString)
{
$.ajax({
type: "POST",
url: 'saveTweets.php',
data: "htmlString="+htmlString,
success: function (data) {
// this is executed when ajax call finished well
alert('content of the executed page: ' + data);
},
error: function (xhr, status, error) {
// executed if something went wrong during call
if (xhr.status > 0) alert('got error: ' + status); // status 0 - when load is interrupted
}
});
}
then on saveTweets.php page write below line, you will get value on that page.
echo '<pre>';print_r($_REQUEST );echo '</pre>';
Using json is better for sending data:
data_htlm=[];
data_html.push({"htmlString": htmlString});
$.ajax(
{
type: "POST",
dataType: "json",
url: "saveTweets.php",
data: JSON.stringify(data_html),
success: function(html)
{
console.log(html);
}
});
now with php you can just do this:
echo $_POST['htmlString'];
You can use the $.post method to post to a PHP page and then retrieve the result from that page in a callback function.

jQuery AJAX loads twice

I'm programming a site, and I've got a problem.
I have the following jQuery code:
$('input[type="text"][name="appLink"]').keyup(function() {
var iTunesURL = $(this).val();
var iTunesAppID = $('input[name="iTunesAppID"]').val();
$.ajax({
type: 'POST',
url: jsonURL,
dataType: 'json',
cache: false,
timeout: 20000,
data: { a: 'checkiTunesURL', iTunesURL: iTunesURL, iTunesAppID: iTunesAppID },
success: function(data) {
if (!data.error) {
$('section.submit').fadeOut('slow');
//Modifying Submit Page
setTimeout(function() {
$('input[name="appLink"]').val(data.trackViewUrl);
$('div.appimage > img').attr('src', data.artworkUrl512).attr('alt', data.trackName);
$('div.title > p:nth-child(1)').html(data.trackName);
$('div.title > p:nth-child(2)').html('by '+data.sellerName);
$('span.mod-category').html(data.primaryGenreName);
$('span.mod-size').html(data.fileSizeBytes);
$('span.mod-update').html(data.lastUpdate);
$('select[name="version"]').html(data.verSelect);
$('input[name="iTunesAppID"]').attr('value', data.trackId);
}, 600);
//Showing Submit Page
$('section.submit').delay('600').fadeIn('slow');
} else {
$('.json-response').html(data.message).fadeIn('slow');
}
},
error: function(jqXHR, textStatus, errorThrown) {
//$('.json-response').html('Probléma történt! Kérlek próbáld újra később! (HTTP Error: '+errorThrown+' | Error Message: '+textStatus+')').fadeIn('slow');
$('.json-response').html('Something went wrong! Please check your network connection!').fadeIn('slow');
}
});
});
Sometimes (randomly) the content fades out-in twice.
Could you let me know what's wrong?
Thanks in advance.
I guess the page is dynamically generated from javascript,
If you execute the following function twice, then there be two events since it executes twice,
so a better way is to unbind all previus 'keyup' event and bind it again.
Try this,
$('input[type="text"][name="appLink"]').unbind('keyup').keyup(function() {
});

zClip not copying specific ID's text

I have set up links that when clicked I want it to copy the text. It outputs many links so I have to make sure zClip copies the right one:
<a class="copy-callbacks" id="coupon-code-copy-<?php echo $couponid ; ?>" href="#"><?php echo $info['coupon'] ; ?></a>
This is the jQuery I am using but it is not working:
$(document).ready(function(){
$("a.copy-callbacks").zclip({
path:'scripts/ZeroClipboard.swf',
copy: $('#' + myCopyID).text(),
beforeCopy:function(){
var myCopyID = $(this).attr("id");
},
afterCopy:function(){
}
});
});
Using this code the flash object doesn't even load. I'm not quite sure what is going wrong. I've tried using:
copy: $(this).text(),
The flash object loads, but for some weird reason it copies some text in the footer. Any help is greatly appreciated!!
I've never had to use the .attr("id"), I always do the following.
<span class="swfTitle" style="position: relative; onmouseover="this.style.cursor='pointer'">
Text
</span>
$('.swfTitle').zclip({
path: '/js/ZeroClipboard.swf',
copy: function () {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
async: false,
data: JSON.stringify(PageInfo),
url: "dosomethinghere.aspx&query=string",
timeout: 30000,
success: function (data) {
PageInfo = JSON.parse(data);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
return PageInfo.PostHTML;
}
Where PageInfo is a js object. Overall, id tags are different than the class tags, .swfTitle is different than #swfTitle.

Categories