A javascript/jquery function to delete itself after execution - javascript

I am sending an ajax request to one of my controller to update the user interaction (which page he visits/likes) for an very insight analytics. I am storing these information in my mongo db.
All I want is, on success of this request, delete this script. But all the alert works, but the script never deletes. The following is my code
<div id="delete_this">
<script>
$(document).ready(function() {
$.ajax({
url: weblink+'user-interactions',
type: 'POST',
dataType: 'html',
data: {
//some post data
},
})
.done(function(html) {
alert("works");
var status = "executed";
alert("works here");
$("#delete_this").remove();
})
.fail(function(html) {
console.log("error");
});
});
</script>
</div>
WHAT I HAVE DONE TILL NOW:
1) tried with adding a div as the parent and pointing to delete that div as shown in script.
2) separated out the .remove() from the script into a new script tag and used something like this.
<script>
$(document).ready(function() {
$("#delete_this").remove();
});
</script>
tried to specify the parentnode and delete the child.
I failed in all three attempts. I am really stuck out here.
Any reasons why it is not working?
I also have another question relating to this.
This link says that the javascript stays in the session till the page is refreshed. So why are'nt we following a standard where we can execute the scripts and delete them
By doing so, we will be able to achieve building a bit more secured webpages. Is'nt it?

You could use plain Javascript to do this (not tested this)
var domNode = document.getElementById('delete_this');
var nodeParent = domNode.parentNode;
nodeParent.removeChild(domNode);
Not sure this is ideal but it should remove it completely from the DOM.

This works :
<button>remove</button>
<script id="test">
$( "button" ).click(function() {
$( "#test" ).remove();
alert("removed " + ($( "#test" ).length == 0));
});
</script>
try it here: http://jsfiddle.net/4ungb/
So either you have a) other errors that prevent that script to complete or b)
your criteria for testing deletion is not correct.

Related

AJAX call to differrent page in same domain works, but does not load everything

So, a little context: I'm trying to do an ajax call to a webpage in the same domain to get a telephone number to show up as soon as I specify the client on the first page. I do get the data but it seems like not the whole page is loaded in.
I need this:
<div id="1">
<div id="2">
<a id="ineedthis"></a>
</div>
</div>
but instead it's giving me this:
<div id="1">
</div>
This is a website that I'm writing a script for, since I can't edit the source code. This is managed from our ERP program and is pretty limited in customizability.
My best guess is that the target webpage is also still loading in the information from the database, but my ajax call returns the webpage before that happens.
Here is my js code:
function updateClasses(){
var link = $('a[href^="/organisatie-beknopt-prs?BcId="]');
var href = "https://52134.afasinsite.nl" + link.attr("href");
console.log(href);
if(href !== "https://52134.afasinsite.nlundefined"){
$.ajax({
url:href,
type:'GET',
success: function(data){
var tel = $(data).find("#P_C_W_Title_Content");
console.log(tel);
}
});
}
}
setInterval(updateClasses, 1000);
I'm running this once per second to check for a change in the input field on the first page, I don't know if there is a better way for this?
Firstly, you could try running the script/function once a change has been detected.
Something along the lines of :
$('input[name="{inputFieldName}"]').on('change',function(){
updateClasses();
});
//You can also use "keyup" instead of "change", depending on the type of action that you are looking for.
For the Ajax, you could try using Promises. Basically, set up the ajax call and then set a ".done" case for the ajax call has been completed and received some result. A ".fail" can also be used to catch non-code related issues.
function updateClasses(){
var link = $('a[href^="/organisatie-beknopt-prs?BcId="]');
var href = "https://52134.afasinsite.nl" + link.attr("href");
var getPhonePromise = $.ajax({
url: href
});
getPhonePromise.done(function(data) {
var tel = $(data).find("#P_C_W_Title_Content");
console.log(tel);
});
getPhonePromise.fail(function(errRes) { console.log(errRes);});
}

the tooltip in bootstrap doesn't work after ajax

I have a file named index.php, which in I include another file named file1.php (in index.php I include all necessary files for jQuery, js etc.).
In file1.php I have a table with buttons which each opens a modal. the information in the modal is from an ajax call for file2.php. in file2.php I create a table. In the table I have the cell :
<button class='btn btn-default tooltip-default' data-toggle='tooltip' data-trigger='hover' data-placement='top' data-content='content' data-original-title='Twitter Bootstrap Popover'>AAA</button>
and, well, the tooltip doesn't work.
but, when I copy this and get it to file1.php, bellow the table, the tooltip does work.
Can anyone help me fix the tooltip ?
Thx.
Use selector on exist element like body
$('body').tooltip({selector: '[data-toggle="tooltip"]'});
I think you need to initialize the tooltip on the newly arrived data, e.g.
$('[data-toggle="tooltip"]').tooltip();
Place this code to your AJAX success handler, after the DOM manipulation.
You will have to put the tooltip initialization in Ajax callback function:
$.ajax({
method: "POST",
url: "some.php"
}).done(function( msg ) {
$('[data-toggle="tooltip"]').tooltip();
});
-OR-
instead of putting the initialization code in every Ajax callback function
you can implement it globally using the ajaxComplete event:
/* initializate the tooltips after ajax requests, if not already done */
$( document ).ajaxComplete(function( event, request, settings ) {
$('[data-toggle="tooltip"]').not( '[data-original-title]' ).tooltip();
});
This code will initialize the tooltip for every node which has the data-toggle="tooltip" attribute defined but do not have the attribute "data-original-title" (i.e tooltip not initialized).
I've tried everything and nothing worked for me.
So I took a closer look at tooltip when click* and found out that each time the shown.bs.tooltip is fired a aria-describedby property appears and its value changes every time.
So, my approach (and it works) is to change the content of this dynamic element.
I got this code:
$('body').on('shown.bs.tooltip', function(e) {
var $element = $(e.target);
var url = $element.data('url');
if (undefined === url || url.length === 0) {
return true;
}
var $describedByContent = $('#' + $element.attr('aria-describedby')).find('.tooltip-inner');
if ($element.attr('title').length > 1) {
$describedByContent.html($element.attr('title'));
return true;
}
$.ajax({
url: url,
method: 'GET',
beforeSend: function () {
$element.attr('title', 'Cargando... espere por favor.');
$describedByContent.html($element.attr('title'));
}
}).done(function (data) {
$element.attr('title', JSON.stringify(data));
$describedByContent.html($element.attr('title'));
});
return true;
});
In my case my tooltip has a data-url attribute to take the data for the title.
The original title is '-', and I don't want an ajax call every time I click* the element, just the first time.
To me it's not useful to make an ajax every time because I don't expect the data to change that fast.
The dynamic created element has an element with the class .tooltip-inner, so we just need to replace its content.
Hope this might help.
*click: I chose the click event because the default hover sometimes make the system turn crazy and the show.bs.tooltip was fired forever, switching its between the default and new value.
You can do this in one of these two ways:
you can write an ajaxComplete function so that every time after an ajax call completed it reinitialize the tooltip over and over again. This is useful when in most of your pages you have datatables and want to initialize the tooltip after every ajax datatable call:
$(document).ajaxComplete(function() {
$("[data-toggle=tooltip]").tooltip();
});
Or you can call tooltip function after ajax success callback:
function tool_tip() {
$('[data-toggle="tooltip"]').tooltip()
}
tool_tip(); // Call in document ready for elements already present
$.ajax({
success : function(data) {
tool_tip(); // Call function again for AJAX loaded content
}
})
I set up my tool tip by placement like so:
function setUpToolTipHelpers() {
$(".tip-top").tooltip({
placement: 'top'
});
$(".tip-right").tooltip({
placement: 'right'
});
$(".tip-bottom").tooltip({
placement: 'bottom'
});
$(".tip-left").tooltip({
placement: 'left'
});
}
initialize this with a document ready call:
$(document).ready(function () {
setUpToolTipHelpers();
});
This way I can determine the placement of the tool tip, and I only have to assign the tip with using a class and title:
<td class = "tip-top", title = "Some description">name</td>
Then I call, "setUpToolTipHelpers()" inside my success ajax function. Or you can call it on the complete function as well. This seems to work well for me.
run
$('#ding_me_tooltip').tooltip('dispose');
$('#ding_me_tooltip').tooltip();
after the ajax where #ding_me_tooltip is your selector

how to run javascript code that included through ajax process

I have a php page which has lot's of code of html and javascript inside it.Ihe other page use ajax to send an id to the first page and get the results and put it inside a div element. Now I want to run those returned codes which contains javascript and html codes.
How should that be done?
This is my ajax request to the first page:
$(document).ready(function() {
$.ajax({
type: "POST",
url: "showing.php",
data: "s_id="+s_id+"&submit=true",
success: function(msg){
str=$.trim(msg)
document.getElementById('tabs-2').innerHTML = str;
document.getElementById("ui-id-2").click();
}
})
I think event delegation can solve your problem.
Like below:
Use $.on(). Instead of registering events on the element you register on a parent which will not be removed
Ex:
$('#tabs-2').on('click', '#ui-id-2', function(){
//do something
})

jQuery stops working after ajax loading

some info
I'm working on a webpage that can load data on multiple layouts, so user can choose which one is best. It can be loaded in a list or a cards like interface, and the data is loaded using ajax.
In this page I also have a notifier for new messages that the user received. The ajax function is new, and when page was loaded by the php scripts, the js script (that add a badge with the number of unread messages to a link on a menu item) was working ok.
I'm using HTML5, PHP, jQuery and a mySQL DB.
jQuery is imported onto the HTML using
<script src="https://code.jquery.com/jquery.js"> </script>
So it's a recent version.
the problem
Now, when I load the data onto the page using ajax, the js script won't work anymore. I had the same issue with another js script and I managed to solve it by using the delegate event binder.
But my unread messages updater runs on a time interval, using
<body onload="setInterval('unread()', 1000)">
the unread() js is quite simple:
function unread() {
$(document).ready(function(){
$('#menu_item').load('ajax_countNewMsgs.php');
});
}
it calls a php script which grabs the unread msgs count from the DB and echo into a element that jQuery will point. Hope I'm being clear.
The problem is that I cannot figure out how I would call a timed event using delegate. Without much hope I've tried
$(document).on('ready()','#menu_item', function () {
$(this).load('ajax_countNewMsgs.php');
});
That didn't work.
I read many posts about js stop working after changes in the DOM, but, again, I couldn't figure out a way to solve that, nor found a similar question.
Any help or tips would be highly appreciated.
EDITED to change second php script's name
2nd EDIT - trying to make things clearer
I tried the way #carter suggested
$(document).ready(function(){
function unread(){
$.ajax({
url: 'ajax_countNewMsgs.php',
type: 'GET',
dataType: 'html',
success: function(response){
$('#menu_item').html(response);
},
error: function(response){
//no error handling at this time
}
});
}
setInterval(unread(), 1000);
});
the ajax_countNewMsgs.php script connects to the DB, fetch the unread messages, and echoes the number of unread messages.
If I try to apply the ajax reponse to another element, say, the <body> the results are as expected: at each 1 sec , the body html is changed. So the function is working.
As I said, none of my JS changes the #menu_item. Actuallly this element is part of another php scritp (menu.php) which is imported to the top of the page.
the page structure is this way:
<html>
<head>
some tags here
</head>
<body>
<?php include (php/menu.html); ?>this will include menu with the #menu_item element here
<div id='wrapper'>
<div id='data'>
here goes the data displayed in two ways (card and list like). Itens outside div wrapper are not being changed.
</div>
</div>
</body>
</html>
Even though the elemente is not being rewritten js cannot find it to update it's value.
It's not the full code, but I think you can see what is being done.
$(document).on('ready()','#menu_item', function () {
is an invalid event listener. If you wanted to be made aware of when the DOM is ready you should do this:
$(document).ready(function () {
However I don't think that is actually what you want. Your function unread will fire repeatedly but it attaches an event listener everytime. Instead if you want to make an ajax call every so many seconds after initial page load, you should do something like this (dataType property could be html, json, etc. pick your poison):
$(document).ready(function(){
function makeCall(){
$.ajax({
url: 'ajax_countNewMsgs.php',
type: 'GET',
dataType: 'html',
success: function(response){
//handle your response
},
error: function(response){
//handle your error
}
});
}
setInterval(makeCall, 1000);
});
remove that on your unread function:
$(document).ready(function(){
WHY?
The Document is already "ready" and this document state will only fired 1x - After that the "ready state" will never ever called. Use follwing syntax:
jQuery(function($){

Can't access Elements previously created by innerHTML with Javascript/Prototype

I am setting the innerHTML variable of a div with contents from an ajax request:
new Ajax.Request('/search/ajax/allakas/?ext_id='+extid,
{
method:'get',
onSuccess: function(transport){
var response = transport.responseText || "no response text";
$('admincovers_content').innerHTML=response;
},
onFailure: function(){ alert('Something went wrong...') }
});
The response text cotains a form:
<form id="akas-admin" method="post" action="/search/ajax/modifyakas/">
<input type="text" name="formfield" value="i am a form field"/>
</form>
Then I call a functiont that should submit that form:
$('akas-admin').request({
onComplete: function(transport){
//alert('Form data saved! '+transport.responseText)
$('admincovers_content').innerHTML=transport.responseText;
}
});
The problem is $('akas-admin) returns null , I tried to put the form with this id in the original document, which works.
Question: Can I somehow "revalidate" the dom or access elements that have been inserted with innerHTML?
Edit Info: document.getElementById("akas-admin").submit() works just fine, problem is i don't want to reload the whole page but post the form over ajax and get the response text in a callback function.
Edit:
Based on the answers provided, i replaced my function that does the request with the following observer:
Event.observe(document.body, 'click', function(event) {
var e = Event.element(event);
if ('aka-savelink' == e.identify()) {
alert('savelink clicked!');
if (el = e.findElement('#akas-admin')) {
alert('found form to submit it has id: '+el.identify());
el.request({
onComplete: function(transport){
alert('Form data saved! '+transport.responseText)
$('admincovers_content').innerHTML=transport.responseText;
}
});
}
}
});
problem is that i get as far as alert('savelink clicked!'); . findelement doesnt return the form. i tried to place the save link above and under the form. both doesnt work.
i also think this approach is a bit clumsy and i am doing it wrong. could anyone point me in the right direction?
So $('akas-admin') returns null but document.getElementById("akas-admin") does not. The $ function is mostly just a wrapper for document.getElementById so it's unusual for this to break down. Have you tried using Element.extend(document.getElementById('akas-admin'))?
Do you have any other libraries loaded? Can you recreate the problem in jsFiddle?
Try using live; since your form is added after the DOM has loaded. Try this:
$("#akas-admin").live('request',function(){
//Do your stuff here })
Hope this helps.
When you hear hoof beats, think horses not zebras. Do you actually have an element with the id 'admincovers_content'?

Categories

Resources