I am writing a program where a click event handler fires an ajax request to my node server, which then renders info inside of a handlebars partial and sends it back to the client (res.render("partials/scraped-article", data);). The client-side javascript appends this html to the document and shows a modal using the bootstrap .modal("show") function. The program shows the modal the first time the click event handler gets fired, but does not recognize the .modal("show") function afterwards. Is there a way to fix this?
Client-Side Javascript:
$(document).on("click", "#scrape-options li", function(){
var choice = $(this).text();
var request;
if(choice === "website1")
request = "/scrape/website1";
else
request = "/scrape/website2";
$.ajax({
type: "GET",
url: request
}).then(function(response){
$(".news-article").remove();
$("footer").append(response);
$('.news-article-img').each(function(i, element){
$(this).css({'height': ($(this).next().height() + 'px')});
});
$("footer h1").addClass("display-none");
$("#articles-added").text($(".news-article").length);
$(".modal").modal("show");
});
});
It turns out that even if you are rendering a partial, the response sent from the server will be embedded in the default template (i.e. it will be a full HTML document). If you simply add this to the DOM, you will be inserting the script for Bootstrap a second time, which will do weird things like disable the $(...).modal function. Instead, you should use the array.split method to extract the body HTML and then append this to the DOM.
Related
I'm using the dialog widget from jquery.
The content for the dialog (id='juiDialog') is generated by ajax request.
The content contains html code (<form id='formId'...>.. </from>) and javascript on each request.
Javascript code contains the ajax request function
jQuery(function($) {
jQuery('#juiDialog').delegate('#formId','submit',function(e){
e.preventDefault();
e.stopPropagation();
jQuery.ajax({
global : false,
async : false,
cache : false,
type : 'POST',
url : jQuery(this).attr('action'),
data:jQuery(this).serialize()
})
.done(function(){
var tr=$('#data-grid').find('#updateTr');
$(tr).css('color','red');
$('#juiDialog').dialog('close');
$('#juiDialog').empty();
alert('Data Saved');
});
});
});
After each ajax complete function I remove the content form the dialog using $('#juiDialog').empty();
This dialog can be called multiple times in the same page for different items.
The problem is that the script runs each time once more so: called 1 time runs 1 time; called the second time runs 2 times (the alert message is showed twice)
When I put the ajax function into the main page not jquery dialog , the problem stops!!!
I need some help in order to make the script run only once with each ajax request but when the ajax function is retrived into the dialog <div> body.
I think that the javascript code is not removed from the DOM on $('#juiDialog').empty() so it is like I am inserting it each time once more.
If you go to this website: http://www.w3schools.com/ajax/
You wil see an example where on the click of a button an ajax call is made to this URL: /ajax/ajax_info.txt
You can see the request in console. I'm trying to get this URL with Jquery like this:
$( document ).ready(function() {
$(document).ajaxSend(function(evt, request, settings) {
alert("Starting request at " + settings.url + ".");
});
});
The problem is that it is not alerting anything. Why is that? I'm testing this in two ways, first: implementing the jquery library and code in the console and second: scraping with PHP and injecting the code. Neither method is working. So how can I get the last URL?
The event being fired on the page you have listed is a jquery ajax event - from the jquery docs.
Description: Attach a function to be executed before an Ajax request
is sent. This is an Ajax Event.
The page you are trying to test the code on is using plain ol' javascript and not jquery, therefore, the ajax event is never fired, and the ajaxSend function is never triggered.
You would need to get the data via a jquery ajax call to get the correct functionality.
I'm developing a web based document management for my final year project. The user interacts with only one page and the respective pages will be called using AJAX when the user click the respective tabs (Used tabs for navigation).
Due to multiple user levels (admin, managers, etc.) I've put the javascripts into the correspondent web pages.
When user requests the user request everythings work perfectly except some situations where some functions are triggered multiple times. I found the problem. It is each time the user clicks a tab it loads same scripts as new instance and both of them will be triggered when I call a function.
to load the content I tired
.load and $.ajax(); non of them address the issue.
I tried to put all into the main page at that time my jQueryUI does not work. I tired
$(document).load('click', $('#tab_root li'), function(){});
Same issue remain.
Can anyone help me out this issue?
--Edit--
$(function){
$(document).on('click','#tabs',function(e){
getAjax($(this))
});
}
//method to load via AJAX
function getAjax(lst){
var cont = $(lst).text();
$.ajax({
url:'../MainPageAjaxSupport',
data: {
"cont":cont
},
error: function(request, status, error){
if(status==404){
$('#ajax_body').html("The requested page is not found. Please try again shortly");
}
},
success: function(data){
$('#ajax_body').html(data);
},
});
}
You can't undo JavaScript after it has been executed by simply unloading the file or removing the script element.
The best solution would probably be to set a variable in each JavaScript file you include in your ajax data and include them from an online inline JavaScript inside the ajax data along with a conditional like such:
<script>
if(!tab1Var) $.getScript("filename");
<script>
Older Solutions
You can manually unbind each event before setting them with off.
$(function){
$('#tabs').off('click');
$('#tabs').on('click',function(e){
getAjax($(this));
});
}
Alternatively you can initialize a global variable (eventsBound1=false) for each tab in the main html:
$(function){
if(!eventsBound1){
$('#tabs').on('click', function(e){
getAjax($(this));
});
eventsBound1 = true;
}
}
The tabs click event is only an example you have to do this for each time you bind an event in the scripts that are being reloaded.
if all the events are bound to things inside ajax_body, a final thing you can try is:
success: function(data){
$('#ajax_body').empty();
$('#ajax_body').html(data);
},
You have bind an event click on 'document' so getAjax() only replace the '#ajax_body' not the 'document'.
This means old event is still attached to the 'document' all you need is to unbind event by using $(document).off('click'); or change 'document' to other elements.
I'm currently in the midst of creating a generator which echoes a random line from a .txt file. All is well and good however I need to have this certain part of the page which echoes the random line refresh when a button is clicked. I've tried multiple methods to no avail and I'm running out of ideas - I'm still quite new to JavaScript/AJAX and have no idea on how to go about it. Any help would be brilliant, thanks!
Use Jquery Ajax to get contents from the file and display the contents into a div
$.ajax({
type: "GET",
url: "yourfilename.txt"
}).done(function( msg ) {
$("#YOURDIVID").html(msg.d);
});
Bind click event of your button
$(function(){
$("#YOURBUTTONID").on("click",function(){
//do your work
});
});
Refreshing logic can be wrapped into a function and called on click of button OR you can use javascript settimeout method.
I have an issue on a website where a page content (results) are updated via AJAX. Contained within this AJAX returned content is a script tag which renders the LinkedIN "share" button.
When the page first loads with the initial resultset the layout looks like this:
Each of these buttons is within a left-floated div, and the HTML looks like this in Chrome developer tools:
As you can see the script tag is appearing where it is supposed to be, in the div, and the dynamically generated span containing the button is just above.
Now, when i append more results via an AJAX request, things go a bit haywire, and look like this:
As you can see the LinkedIN button is way out of place, and the reason is apparent when looking at the HTML in developer tools:
The script tag is not within the div where it appears in the code file, instead appearing after the closing tr tag - and the span with the button is just above.
So, why is this, and more importantly what can be done to ensure that the script tag is where it belongs so that the layout is correct?
FYI - At the foot of the body is javascript which loads the LinkedIn .js file and after the AJAX request for more results completes there is an invocation of the LinkedIn .parse() method which is supposed to parse the full document and render the buttons.
EDIT
The application is built using ASP.NET MVC and the response returned uses the same .ascx control to format the results as the initial page load does.
EDIT - AJAX request used to retrieve extra data
function LoadMore(uri, last, loader, end)
{
isLoading = true;
$(loader).show();
$.post(uri, function(data)
{
if (data != "")
{
$(last).after(data);
isLoading = false;
// re-do social media share initialisation on the new AJAX-added content
gapi.plusone.go('container');
twttr.widgets.load();
FB.XFBML.parse();
IN.parse(document.body);
}
else
{
$(end).show();;
}
$(loader).hide();
});
}
EDIT
The actual HTML returned from the server is correct. Viewing the source shows the script tag in the correct location, but viewing the page in Chrome developer tools, as shown in the images above, shows the script in the wrong place in the DOM. This occurs in both IE9 and Chrome.
Are you building the html dynamically ? Maybe it has something to do with misconfigured callbacks. If you are using $.ajax({...}), make sure that the next iteration is specified into the "success:" property to prevent unordered render.
Use ajax call like this
$.ajax({ url: 'url',
type: 'POST',
data: json,
dataType: 'json',
contentType: 'text/html',
success: function (data) {
//you response will be data
}
});