x-editable form loaded with ajax into a div - javascript

I want to load a form directly into a using ajax call.
The container page has already all the needed css/scripts inclusion for x-editable forms.
I can load the html code directly inside the div, but the problem is that the x-editable fields are not rendered.
Here is my code:
The div that will contain the remote content
<div id="mycontent">
....
</div>
And the javascript function:
$("#create-button").click(function(){
document.location.href = '/fip-dt/insertProject';
$('#mycontent').html('');
ajaxRead('/insertProject');
});
function ajaxRead(file){
var htmlObj = null;
if(window.XMLHttpRequest){
htmlObj = new XMLHttpRequest();
} else if(window.ActiveXObject){
htmlObj = new ActiveXObject("Microsoft.XMLHTTP");
} else {
return;
}
htmlObj.onreadystatechange = function(){
if(htmlObj.readyState == 4){
updateObj(htmlObj);
}
}
htmlObj.open ('GET', file, true);
htmlObj.send ('');
}
function updateObj(data){
document.getElementById("mycontent").innerHTML=data.responseText;
}
I cannot use jquery directly to updated the content of div, because it seems to entirely remove the tags.
Into the remote div, i have the following javascript code:
$.fn.editable.defaults.mode = 'inline';
$('table#projectform > tbody > tr > td > a').editable();
$('.myeditable').editable({
url: '/post'
});
$('#project-name').editable('option', 'validate', function(v){
if(!v) return 'Required Field';
});
$('#save-btn').click(function(){
$("p#prova").html("TEST");
});
It seems that this piece of code is not executed when the remote content is loaded into the div.
Any idea?

Try adding your code after the div has been renderd

Related

HTML added from another HTML file using JS displays correctly, but JS functions do not work

I would like an element of my html page to be taken from another html file. So, such a widget displayed on many pages at once.
I was able to write JS code so that the content of the element is taken from another file. Code below:
//* Accordion - replace */
var fn = (event) => {
var xhr = new XMLHttpRequest();
xhr.open("GET", '/widgets/accordion.html', true);
xhr.onload = function (e) {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
console.log(xhr.responseText)
document.getElementById("accordion").innerHTML = xhr.responseText;
}
else {
console.error(xhr.statusText);
}
}
};
xhr.onerror = function (e) {
console.error(xhr.statusText);
};
xhr.send(null); }
document.addEventListener('DOMContentLoaded', fn, false);
document.addEventListener
The item (accordion) displays correctly, as in the code here:
https://codepen.io/jakub-czeszejko-sochacki/pen/rNWNwrN
But unfortunately it doesn't work properly as if JS code is not being read for this element. As a result, when you click on the accordion button, the accordion does not open.
Is it even possible for this to work with JS?
Problem solved.
It turned out that the JS accordion initiation took place before its html was loaded with the line:
document.getElementById ("accordion"). innerHTML = xhr.responseText;
It was enough to put the initialization code (the accordion opening code) in the function and call this function after the above line of code.

Hide a div of the child using AJAX

I am loading pages using AJAX. In every web page I have 2 div common - header div and content div. Now when I navigate from one one page to another than I load the content div of the next page into the current page by using
$("#content").load(URL+" #content");
Now as I am using AJAX to load pages so I am changing the URL and manipulating history using History API.
So now when someone press the back button of the browser then there is a problem, both the header div of both the pages is being showed during loading but disappears after loading is finished . So can anyone help me how to hide the header div of the loading page.
Here is the code that I am using to handle back button of browser
function swap(href) {
var x = document.getElementById("myTopnav");
x.className = "topnav";
var req = new XMLHttpRequest();
req.open("GET",
"http://localhost/" +
href.split("/").pop(),
false);
req.send(null);
if (req.status == 200) {
document.getElementById("content").innerHTML = req.responseText;
$("#content").load(" #content");
return true;
}
return false;
}
window.addEventListener("popstate", function(e) {
swap(location.pathname);
e.preventDefault();
});
I think this should work. It wraps the response in a DIV in case #content is the outermost element, since .find() only searches contents.
function swap(href) {
$("#myTopNav").addClass("topnav");
var url = href.split('/').pop();
$.get('http://localhost/' + url, function(response) {
var fragment = $("<div>", {
html: response
});
$("#content").replaceWith(fragment.find("#content"));
}
});
}
window.addEventListener("popstate", function(e) {
swap(location.pathname);
e.preventDefault();
});

AJAX callback in a form element not working after an AJAX load in bootstrap modal

I am trying to load a form inside a boostrap modal through AJAX ,with another AJAX callback in it. The form is loaded through a menu_hook with a delivery callback where I set the js and css necessaries.
The problem is that, after the AJAX callback to load the modal, the AJAX callback for the select list does not work, and I think is because the scripts are not executing, I tried to eval() them but it is not working either.
This is a general explanation of what I have till now:
Menu_hook that returns the html for the form and the scripts and css
Button with id
<button type="button" id="show-modal" class="btn btn-warning"></button>
JQuery to show the loading modal when the id of the button is clicked and to trigger the JavaScript function for AJAX load
$("#buy-hours").click(function () {
$('#loading-modal').modal("show");
_load_ajax(link_to_menu_hook, '#modal-body-wrapper');
}
JavaScript to load the html through the menu_hook1 and replace it in the loading modal
function _load_ajax(url, wrapper) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == XMLHttpRequest.DONE ) {
if (xmlhttp.status == 200) {
//loads the html
document.querySelector(wrapper).innerHTML = mlhttp.responseText;
var newElement = document.createElement('div');
newElement.innerHTML = xmlhttp.responseText;
var scripts = newElement.getElementsByTagName("script");
for (var i = 0; i < scripts.length; ++i) {
var script = scripts[i];
eval(script.innerHTML);
} else if (xmlhttp.status == 400) {
alert('There was an error 400 in _load_ajax');
} else {
alert('something else other than 200 was returned');
}
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
** I am loading the modal with Javascript and not with JQuery because when I use load() or $.ajax() the console.log outputs "Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience.", and still does not work. By loading with Javascript I don't get any error in the console.
Thanks a lot!

Javascript not working when 'alert; is removed

I have the following JS on my html and my obervations are:
1) When I removed the line for "alert" display it is not working as expected, the SAVE button is not trigerring when clicked.
2) Even with the "alert", it is not working in CHROME.
function save() {
alert('View Full List triggered!');
var $form = $('.fancybox-inner').find('[data-area="funder-detail"]');
$form.on('click', '[data-action="save-funder"]', function () {
var selected1 = $form.find('input[type="radio"]:checked').val();
if ($('input[type="radio"]:checked').length == 0) {
parent.$.fancybox.close();
} else {
document.getElementById("txtFunder").value = selected1;
parent.$.fancybox.close();
}
});
}
Perhaps the script runs too early, when the form is not yet in the DOM?
This can happen when the script tag is in the header.
Try moving the script tag in front of the closing tag.
I was able to make it work by using onclick="setTimeout(save, 1000)"

Capture embedded variable from jQuery Ajax call

I'm trying to convert our current javascript framework to jQuery cause we'll need the additional functionality of jQuery for further projects. There is one particular function that is all over the place (and it was setup how it was setup......) that I'd like to just override with a jQuery equivalent. Here's the original Javascript function that makes an ajax call to a php page.
function ajax(n,f,v){
var ajaxRequest;
if(window.XMLHttpRequest){// code for IE7+, Firefox, Chrome, Opera, Safari
ajaxRequest=new XMLHttpRequest();
}
else{// code for IE6, IE5
ajaxRequest=new ActiveXObject("Microsoft.XMLHTTP");
}
ajaxRequest.onreadystatechange=function(){
if(ajaxRequest.readyState==4 && ajaxRequest.status==200){
//This is where the result is stored
result = ajaxRequest.responseText;
//parseScript pulls out the content and the div and populates the div with the retrieved content.
parsed_result = parseScript(result);
document.getElementById(parsed_result.div).innerHTML = parsed_result.source;
}
}
ajaxRequest.open("GET","view.php?n="+n+"&f="+f+"&v="+v+"&time="+(new Date).getTime(),true);
ajaxRequest.send();
}
function parseScript(_source) {
var source = _source;
var scripts = new Array();
while(source.indexOf("<script") > -1 || source.indexOf("</script") > -1) {
var s = source.indexOf("<script");
var s_e = source.indexOf(">", s);
var e = source.indexOf("</script", s);
var e_e = source.indexOf(">", e);
scripts.push(source.substring(s_e+1, e));
source = source.substring(0, s) + source.substring(e_e+1);
}
for(var i=0; i<scripts.length; i++) {
try {
eval(scripts[i]);
var div = div;
}
catch(ex) {
}
}
return {source: source, div: div};
}
This is at the top of page that was just retrieve (hence the parseScript function). This div variable tells where to put the retrieved content.
<script>
var div = 'content_1';
</script>
<!-- some retrieved html -->
The jQuery function I'd like to just "set on top" of the javascript function would require that I don't edit the retrieve ajax file at all. See below for my attempt at the jQuery call.
function jAjax(n,f,v) {
$.get('view.php', 'n='+n+'&f='+f+'&v='+v, function(result) {
if(result) {
if($('#'+result.div).length) {
$('#'+result.div).html(result);
} else {
console.log("Couldn't find the div= "+result.div);
}
} else {
console.log("Couldn't find the names for n="+n+' f='+f+' v='+v);
}
});
}
So the question I have is how to I use jQuery to capture a variable from an ajax call so that I can populate that capture div with the retrieved html?
One other thing, yes I can can think of a bunch of ways to do it besides doing this, but this way would be easiest with the current framework that was already set in place when I got here. So, please only suggest ways of retrieving the variable from the ajax script. Thanks muchly!
There is no built in way to get the value of variables in a javascript file that you retrieved through jquery ajax methods. You could, however, just call the parseScript function inside the $.get callback:
$.get('view.php', 'n='+n+'&f='+f+'&v='+v, function(result) {
if(result) {
parsed_result = parseScript(result);
if($('#' + parsed_result.div).length) {
$('#' + parsed_result.div).html(parsed_result.source);
} else {
console.log("Couldn't find the div= " + parsed_result.div);
}
} else {
console.log("Couldn't find the names for n="+n+' f='+f+' v='+v);
}
});
EDIT:
You may have to make this call with the longer $.ajax(...) method, setting the content type to text, because you have a script tag in the page.
EDIT (ALTERNATIVE):
You could simply reference the variable 'div' in the $.get callback because at that point the script would have been executed:
$.get('view.php', 'n='+n+'&f='+f+'&v='+v, function(result) {
if(result) {
if($('#' + div).length) {
$('#' + div).html(result);
} else {
console.log("Couldn't find the div= " + div);
}
} else {
console.log("Couldn't find the names for n="+n+' f='+f+' v='+v);
}
});

Categories