AJAX - how to load javascript code not html? - javascript

I use jQuery with $('#countryid').load('/some/url',{country: country_id}); function to automatically load options for regions depending on selected country before.
And it works fine when I load html through ajax.
But I need to load javascript code. When I try to do that all select fields disappear from page at all...
What am I doing wrong?
Code:
<script type="text/javascript">
$(document).ready(function() {
$('#countrydropdown').change(function() {
var countryvalue = $('#countrydropdown option:selected').val();
if(countryvalue==0){clearlist();}
getarea();
});
});
function getarea(){
var countryvalue = $('#countrydropdown option:selected').val();
var area = $('#areadropdown');
if(countryvalue==0){
area.attr("disabled",true);
}else{
area.attr("disabled",false);
area.load('/ajax/2/',{country: countryvalue});
}
}
function clearlist(){
$('#areadropdown').empty();
}
</script>
<form action="" id="form">
<select id="countrydropdown">
<option value="0">Countries</option>
...
</select>
<select id="areadropdown" disabled="disabled">
</select>
</form>
Thanks!!!

Based on the code your comment on my previous answer suggests you are using:
<script type="text/javascript">for(var i in arr) document.write(arr[i]);</script>
After the page has loaded, the document will enter the closed state.
You cannot document.write to a document in the cosed state, so document.open will be automatically called.
This will trash the existing document so a new one can be written.
Use DOM to manipulate the document, don't go near document.write.

You can use eval to execute javascript code
eval(ajax.request);

If you are loading just JavaScript, then use getScript instead of load.
If you are loading a combination of HTML then JavaScript, then I would give serious consideration to refactoring so that the JavaScript is already in place and events are handled using live instead of being bound directly to the elements themselves.

Related

Select an item or link

Sometimes this script does not work, I am using it in a php file
<script type="text/javascript">
window.onload = function () {
var input = document.body.getElementById("thisActive");
input.focus();
input.select();
}
</script>
here is work
http://cartoon.22web.org/watch/s-watch/index.php
After the page load is complete, the script specifies the link to the page
===========================
But here using multiple pages http://wassim-al-ahmad.22web.org
not selected page selected
Just convert window to document like this:
document.onload = function () {
var input = document.body.getElementById("thisActive");
input.focus();
input.select();
}
JQuery version
$(document).ready(function () {
...
});
You have seen the code and the reason for the priority You are using JavaScript at the beginning of the code and then create a menu to select an item from a database using PHP multiple pages You must use the script at the end of the code
Use PHP to view the data from the database starting with the page order currently displayed. You do not need to use the script you have ever typed in your HTML code.
i had the same problems just you have to change your host if you used free host you must change the host to

Reinitalize Dom after Ajax Request (.on input not working)

I have a bunch of text inputs that are dynamically created through a MySQL query.
At the bottom of my page I have this.. I had to use window.load instead of document.ready as the latter would not work
<script>
$(window).load(function() {
$('.<?php echo $sku; ?>').on('input', function() {
$('.'+$(this).attr('class')).val($(this).val());
});
});
It is my understanding that using .on should relate to both past and present dom objects, but this is not the case.
The (messy) html I'm currently dealing with is
<input type="text" class="mySKU18" id="inputsku" contenteditable="true" onkeydown="if (event.keyCode==13) saveToDatabase2(this,'itemnumber','mySKU18')" onClick="showEdit(this);"></input>
This is generated on the page load, and 'reset' using ajax if a button is clicked.
My issue is with the above script in relation to the html above.
Both HTML's are the same on the initial page load and ajax response.
Right now my solution to get this working is to reinitiate the script at the bottom of my ajax php script.
/// my php
?>
<script>
$('.<?php echo $sku; ?>').on('input', function() {
$('.'+$(this).attr('class')).val($(this).val());
});
</script>
This works and does not provide any console errors, but obviously is not ideal.
Anyone know what could be the issue and how to fix it?
Build your new text input elements like this and they will be in the DOM tree. You can build all of your new elements this way and use appendChild to link them together if you need them to be referenced in the DOM tree.
var text = document.createElement("input");
text.setAttribute('type', 'text')
text.setAttribute('id', 'yourID');
text.setAttribute('name', 'yourName');
text.setAttribute('class', 'yourClass');
text.setAttribute('style', 'yourStyle');
document.getElementById("yourParent").appendChild(text);

Initialize more than one html element using jQuery and Javascript

I have tried to lead my html element to fire my customized JS file's method.
Third textarea appears nicely.
First and second textareas does not effect any of the settings i am trying to change in myJSFile.js file.
Here's my problem : js file loads the last textarea nicely, but cannot initialize previous ones properly using my js methods.
I'm doing something wrong with my JS file, and i'd appreciate if you help me.
P.S. : Initalizing some plugin and working on CKEditor.
Here's my HTML file :
<textarea id="myTextAreaID" name="myTextArea"></textarea>
<script type="text/javascript" src="../public/js/myJSFile.js"onload="setTextAreaValues('myTextAreaID')"></script>
<textarea id="myTextAreaID2" name="myTextArea2"></textarea>
<script type="text/javascript" src="../public/js/myJSFile.js"onload="setTextAreaValues('myTextAreaID2')"></script>
<textarea id="myTextAreaID3" name="myTextArea3"></textarea>
<script type="text/javascript" src="../public/js/myJSFile.js"onload="setTextAreaValues('myTextAreaID3')"></script>
Here's myJSFile.js file
var textAreaID;
$(function(){
var myTextArea = $('#'+textAreaID);
//something is being loaded here, and it is loaded fine.
});
function setTextAreaParameters(param){
textAreaID = param;
}
Thanks in advance.
This is not very good idea to do it like this, however it's interesting to understand why it happens. In your code below you are defining global variable textAreaID:
var textAreaID;
$(function() {
var myTextArea = $('#' + textAreaID);
//something is being loaded here, and it is loaded fine.
});
function setTextAreaParameters(param) {
textAreaID = param;
}
This script is injected three times into document. After the last script tag the value of textAreaID variable will be myTextAreaID3, because it's global and the last setTextAreaParameters invocation will override previous. Remember that scripts are loaded synchronously in your case (no async or deferred attribute), it means that onload callbacks don't wait and immediately set textAreaID to new values.
However DOMContentLoaded event has not yet fired. This is the event you are subscribing with this code:
$(function() {
// DOMContentLoaded
});
When it eventually does - only the third textarea will be processed - the one with id myTextAreaID3.
Better approach would be to have only one script tag and set textareas the same className attribute:
<textarea id="myTextAreaID2" name="myTextArea2" class="editor"></textarea>
Then in the script probably have some sort of map with configuration parameters for each individual textarea.
You are including the same script three times, but the browser is probably smart enough to only load it once (no reason to load the same script on the same page more than once).
What you need to do is to include the script only once, say before the end of the body tag
...
<script type="text/javascript" src="../public/js/myJSFile.js"></script>
</body>
and then in the JS file, wait for the document to load, and handle all text areas accordingly:
$(function() {
$('textarea').each(function(i, j) {
console.log('do something for the ' + i + 'th text area');
});
})

jquery .load() function only working the first time

So I have a website I am working on just as a personal website that uses jQuery and jQuery UI
Previously I have been using hidden html code and just using jquery to show it.
But its making my html file messy so I wanted to use jquery's .load() to do the same thing but from an external file.
Right now, its set to a .click function.
For my hidden html it shows it every time when I click a particular element.When you click on a different element it. It hides the first one. I am doing it by having a div with 2 classes. The problem is when I tried to load html into a hidden div, and then show it and hide it, it only worked the first time.
Enough talk, here is my code. #1 works , #2 only works on the first click. And leaves imagearea blank every time after.
$(".jquery").click(function(){
clearImageArea();
hideThumbnails(5);
showThumbnails();
$("#1").click(function(){
$(".imagearea").html(js);
$(".jscode").show(1000);
$(".title").text("Extending jQuery");
});
$("#2").click(function(){
$(".jquery2").empty();
$(".jquery2").load("jqueryEx.html");
var jquery2 = $(".jquery2");
$(".imagearea").html(jquery2);
$(".jquery2").show(1000);
$(".title").text("Extending Jquery Example");
});
});
now my hidden stuff in my html file
First my html and js code is loaded into here from jqueryEx.html and is being hidden elsewhere in my javascript via $(".hidden").hide(); and loaded then into into imagearea via .html() and shown via .show()
<div class="jquery2 hidden">
</div>
My other div looks like this which is put into imagearea by clicking on #1
<div class="jscode hidden">
<div class="block">
//lots of js code escaped out into html
</div> <!-- end of block-->
</div>
elsewhere in my JS code at the beginning I have var js=$(".jscode"); to load it into the js variable you saw earlier.
if you want to see an out of date example of what I am working on
go to www.3realsoft.com (only cs and js work on skills)
if you want to see any additional parts of my code, just ask. Most of it is there on my website though.
I got to this item in my search results, when I was trying to have a button both load and refresh the content, and the load was working but the refresh was not working.
Here's a shorter version of the solution, setting Cache to false was the key. Solution found over at this other link, but I'm posting this concept here because if Google dropped me in this item, others looking for the same will also probably find themselves here. Props to John Millikin, make sure to go over to his answer and upvote him: Stop jQuery .load response from being cached
<script type="text/javascript">
$(document).ready(function () {
$.ajaxSetup({
// Disable caching of AJAX responses
cache: false
});
$('.detail-expand').click(function () {
var detailRowElement = $(this).closest('.session-row-tr').next();
var detailElement = detailRowElement.find('.detail-row-div');
var sessionId = detailElement.data("sessionId");
detailElement.empty();
detailElement.load('/Admin/WebLogPartial/' + sessionId, function () {
$.bootstrapSortable(true, 'reversed');
});
detailRowElement.show();
});
});
</script>
Anything that depends on the HTML being loaded must be done in the callback function, because the first A in AJAX stands for asynchronous.
$("#2").click(function(){
$(".jquery2").empty();
$(".jquery2").load("jqueryEx.html", function() {
var jquery2 = $(".jquery2");
$(".imagearea").html(jquery2);
$(".jquery2").show(1000);
$(".title").text("Extending Jquery Example");
});
});
I'm not really sure what you're trying to do with .html(jquery2), since the argument to .html() is supposed to be a string, not a jQuery object. Maybe you meant:
var jquery2 = $(".jquery2").html();

Page finish loading, load in jQuery content via Jquery .load, execute jQuery elements

If I want to be able to load in content (containing elements depending on jQuery) after main page has finish loading, the content will be retrived from another page on my site (div). How do I then get those element depending on jQuery to execute (work)?
How do I make these different jQuery elements to work with some easy method after they being loaded into the main page? I dont know much about jQuery, it would be great if I could just ad/edit a function on the scripts to make them work after inload, but ofcurse its propably more difficult than that. In the passed days I have tried initialize the different object that loads in but notice that it was quite difficult with complicated scripts.
The page load in new content like this (selectbox):
<select id="selectbox">
<option>1</option>
</select>
jQuery code to the selectbox:
$(document).ready(function(){
$("#selectbox").change(function(){
var selectedOption = $('#selectbox :selected').val();
$containerDiv = $('#div_that_will_get_content');
$containerDiv.html("");
switch (selectedOption)
{
case "1":$containerDiv.load( "Page.html #div1 );break;
}
return true;
});
});
Selected option in selectbox (1) collects data from Page.html #div1, then send the data to div "#div_that_will_get_content". So the div get loaded in after the main page have finish loading.
Now if I want to put a jQuery element in this div and then load that div into the main page via the selectbox and to "#div_that_will_get_content", those elements dont work. Can anybody show a easy jQuery example with a smal explanation how the script was written from the begining and what you changed to make it work after it was loaded in?
Thanks.
Not entirely sure what you are needing but part of the answer lies in using the success callback of load()
/* define this cached elemn outside change handler so don't have to search DOM each time*/
$containerDiv = $('#div_that_will_get_content');
$("#selectbox").change(function() {
/* val() of select is same as searching for selected option val() but less code*/
var url = 'Page.html #div' + $(this).val();
$containerDiv.load(url, function() {
/* new ajax loaded html exists you can run code here*/
$containerDiv.find('#someOtherDiv').doSomething()
})
});
API Reference: http://api.jquery.com/load/
If your problem relates to binding events to elements that will be loaded any time in the future such as click handlers, you can delegate these in your page load script using on()
$(document).on('click', '.className', function(){
doSomething();
})

Categories