How to load more jquery script to DOM by jquery ajax - javascript

I am creating an application that may become very large over time. So in order to keep things simple, we have decided to keep Javascript (mostly jQuery code), CSS and html for one particular feature in one file. for example, if upload is a function, then we have all the jQuery validation and css, html for upload in one file (without head and html tags).
We have a home dashboard in which a click handler will load all the links by ajax and append to the designated DIV of class indicated by additional attribute in links called "whereTOadd". so if a link has its "WhereTOadd" attribute set to ".here" and href set to upload.php then the contents of upload.php will be added to a div of class 'here' in the same page. it is done using script given below.
But the problem i am facing is that I need to include jQuery file again in every file to get the codes working, which is a terrible thing. What can be done to avoid this?
This is html of my dashboard:
<html>
<head>
..
<script src="Path-to-jquery-min-file.php" ></script>
<script>
$( document ).ready(function(){
$(document).on("click","a",function(e){
if( $(this).attr('href'))var ajaxurl = $(this).attr('href').valueOf();
if( $(this).attr('whereTOadd'))
var target = $(this).attr('whereToadd').valueOf();
/*for ajax request */
var options= {
type: 'GET',
url: ajaxurl,
dataType: 'html',
success: function (html, textStatus){
$(target).empty().append(html);
},
error: function(xhr, textStatus){
alert('error');
}
}
$.ajax(options);
return false;
});
});
</script>
</head>
<body>
<a href="upload.php" >Upload data</a>
<div class=".here" ></div>
</body>
upload.php contains:
<script type="javascript" >
$('body').append('load successful!');
</script>
This setup will not work until I make change in upload.php as:
<script src="Path-to-jquery-min-file.php" ></script>
<script type="javascript" >
$('body').append('load successful!');
</script>
Please help in solving this because loading jQuery again and again in the same page may cause errors and conflicts. Please suggest me a better approach to what I am doing.
Thanks

Related

How to load <script type=module> in AJAX?

How can I load the module script via jQuery AJAX? I like to load PhotoSwipe via AJAX because my gallery depends on the user's input.
<script type="module">
import PhotoSwipeLightbox from 'photoswipe/dist/photoswipe-lightbox.esm.js';
const lightbox = new PhotoSwipeLightbox({
gallery: '#my-gallery',
children: 'a',
pswpModule: () => import('photoswipe/dist/photoswipe.esm.js')
});
lightbox.init();
</script>
We have a HTML form. After user submits the form, the server will return the content and jQuery will insert the response into the DOM. The response is stored and displayed inside a div.
$('#form').ajaxForm({
target: '#feedbackSection',
url: 'server.php',
type: 'post',
beforeSubmit: beforeSubmit,
success: showResponse
});
Typically, I include some JavaScript codes in the response code. I've noticed that the type=module is not loaded:
<script type='module'>
//This code is not loaded.
</script>
<script type="text/javascript">
$(document).ready(function(){
//This code is loaded.
});
</script>
Is there any way I can fix this issue? Thanks.
This is a bug of jQuery.
Updating jQuery version to 3.3.0+ should solve the issue.

Get a javascript derived dom-tree element

My aim is to get an element <div id="calender"> and all what is in the element shown in a browser. The point is that normal get-html-source won't do the thing. The element what I am looking for does not exists in the html output of php-function file_get_contents.
I have tried to get the source by php with xpath byt the help of http://us3.php.net/manual/en/class.domxpath.php which inludes a nice tool to get what is in any tag in the html page. But the problem here might be that the element (a calender) is formed to the loaded page by javascript and cannot be caught by server side php. So, is there a way I can catch such element (div) by javascript instead.
There are script examples of javascript for this kind of problem (if I have understood them correctly) but currently I cannot get a simple javascript to work. An example below shows how I have tried to built up a code. $ajax thing here is just one path I have tried to solve the problem but don't know how to use it. More here I cannot figure out why the simple javascript functions do not work (just test purposes).
<!doctype html>
<html lang="fi">
<head>
<meta charset="utf-8">
<title>load demo</title>
<style>
body {
font-size: 12px;
font-family: Arial;
}
</style>
<script type="text/javascript">
function ok {
alert "OK";
}
function get_html (my_html){
alert "OK";
var l = document.getElementById('my_link').value;
alert l;
alert my_html;
var url = my_html;
$.ajax({
url: url,
dataType: 'html'
success: function(data){
//do something with data, which is the page 1.html
var f = fs.open("testi_kalenteri.html", "w");
f.write(data);
f.close();
alert "data saved";
}
});
}
</script>
</head>
<body>
<p id ='my_link' onclick='get_html("lomarengas.fi/en/cottages/kuusamo-rukasaukko-9192")'>html-link</p>
<p id ='ok' onclick='ok()'>show ok</p>
</body>
</html>
Briefly, I have a link to a web page, which shows up a (booking) calendar in it but this calendar is missing in the "normal" source code, by file_get_contents (php). If I browse the html source with Chromes tools (F12) I can find the calendar there. T want that information get by javascript or by php or such.
If you read the source code of the page you point to (http://www.yllaksenonkalot.fi/booking/varaukset_akas.php), you notice that the calendar is loaded via an iframe.
And that iframe points to that location :
http://www.nettimokki.com/bookingCalendar.php?id_cottage=3629&utm_source=widget&utm_medium=widget&utm_campaign=widget
Which is in fact the real source of the calendar...
EDIT following your comment on this answer
Considering the real link : http://www.lomarengas.fi/en/cottages/kuusamo-rukasaukko-9192
If the calendar is not part of the generated html, it is surely asynchronously generated (in javascript, client side).
From this asumption, I inspected the source code (again).
In the developper tools of my browser, in the Network section, where you can monitor what files are loaded, I looked for
calls to server (everything but calls to resources : images, stylesheets...).
I then noticed calls to several urls with json file extensions like http://www.lomarengas.fi/api-ib/search/availability_data.json?serviceNumber=9192&currentMonthFirstDate=&duration=7.
I felt I was on the right track (asynchronous javscript calls to generate html with json datas), I looked for javascript code or files that was not the usual libraries files (jquery, bootstrap and such).
I stumbled upon that file : http://www.lomarengas.fi/resources_responsive/js/destination.js.
It contains the code that generates asynchronously the calendar.
tl;dr
The calendar is indeed generated asynchronously.
You can't get the full html with a curl or file_get_content in PHP and
you can't access it with ajax code (due to Same-origin policy).
By the way, you should contact the site to see if you can access their api via PHP with their consent.
Hope it helped you understand the whole thing...
To get <div id="calender"> you can use next code (jquery):
<div id="calender"></div>
<script>
$("#calendar").click(function(){
alert('calendar was clicked');
});
</script>
If I understand you correctly. I think you need appropriate php respond with some correct code inside php file:
// json_handler.php
<?php
if (is_ajax()) {
$return = $_POST;
$return["ok"]="ok";
$return["json"] = json_encode($return);
echo json_encode($return);
}
function is_ajax()
{
return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
}
and this is script wich is inside html:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
</head>
<body>
<a id="click">click</a>
<script>
$("document").ready(function(){
$("#click").click(function(){
var data = {
"request": "request"
};
data=$.param(data);
// alert(data);
$.ajax({
type: "POST",
dataType: "json",
url: "json_handler.php",
data: data,
success: function(data) {
// here you will see echo respond from your php json_handler.php
// also you can add here more javascript (jquery code) to change your page after respond
alert();
}
});
return false;
});
});
</script>
<body>
<html>
http://www.w3schools.com/jquery/jquery_ajax_intro.asp

post JSON object into specified div

Trying to create a FAN area on facebook where I need to post all products available only to my facebook fans.
My php file creates plain HTML, which I would like to grab from Facebook end.
How this can be done if this can be done at all?
The following is entire content of my script.js file
$.ajax({
type:"POST",
url:"https://www.mysite.com/includes/facebook_fan_page.php",
data: data,
dataType:"html",
error:function(){},
success:function(response){
$('#products').html(response);
}
})
and here is my index.html
<html>
<head>
[[style.css]]
<script type="text/javascript" src="https://www.mysite.com/js/jquery-
1.8.2.min.js"></script>
[[script.js]]
</head>
<body>
<div class="content">
<div id="products"></div>
</div>
</body>
</html>
I do not know how to write output in to the empty div that I have on my apps index.html page <div id="products"></div>
Also, the app I use on facebook is Static HTML iFrame Tabs, if it makes any difference
Please help
Thanks to you all in advance
My skills of ajax and js are very limited, so please be patient with me on this one.
This is also a method for Ajax Post request, I find it simple. Tell me if you find this useful
In HTML Page
In script file or tag
$.POST("filename.php", data, function(response) {
if(!response) {
alert("Oh Snap! I hate this part");
}
else {
$("#div").html(response.field);
}
});
Read about his here AJAX POST REQUEST

run jQuery when HTML is loaded

jQuery:
$(document).ready(function(){
var url='http://query.yahooapis.com/v1/public/yql?q=select * from html where url=\'http://stackoverflow.com/\' and xpath=\'//div[#id="question-mini-list"]//h3//a \'&format=json&callback=?';
$.getJSON( url, function(data){
$.each(data.query.results.a, function(){
$('#stack').append('<div>'+this.content+'</div>')
})
})
});
HTML
<section id="stack">
</section>
The jQuery code is borrowed from an earlier post (Thanks!), but my question is: Shouldn't the jQuery code run when the page loads, the way it's displayed here? Im using coda 2. The jQuery is saved as .js-file, and the html is saved as .html. Both files are located in the same directory.
Thanks for any and all help!
Make sure you define a link to your javascript file in the <head> of your index.html page.
<script rel="javascript" type="text/javascript" src="path/to/javascript.js"></script>

Cant load 2 jquery scripts

I have javascript, that loads new posts on website from database before :
<script type="text/javascript">
function LoadContent() {
patch = window.location.toString();
if (patch!== undefined && patch=="http://i-sc.ru/" || patch=="http://i-sc.ru/index.php") {
$.ajax({
url: patch,
success: function(content) {
$('#dle-content').html($('#dle-content', content).html());
}})}
setTimeout("LoadContent()", 50);
}
</script>
<script type="text/javascript">
$(document).ready(function(){
LoadContent()
});
</script>
And after i have set up script for
<script type="text/javascript" src="js/jquery.fancyzoom.js"></script>
that i put in <head>
set up:
<script type="text/javascript">
$(function() {
//Set the default directory to find the images needed
//by the plugin (closebtn.png, blank.gif, loading images ....)
$.fn.fancyzoom.defaultsOptions.imgDir='../images/'; //very important must finish with a /
$('a.tozoom').fancyzoom({Speed:0});
$('a').fancyzoom({overlay:0.6});
//new rev > 1.2
//apply fancyzoom effect on all image whose class is fancyzoom !!
$('img.fancyzoom').fancyzoom();
});
</script>
Well, now about the problem:
When the website is loaded, i cant zoom images because of conflict, i think
How to solve it?
Don't reference jquery.js file multiple times, from the second script, remove the reference to the file.
And ensure you are not referencing different versions of .js files any where in your script.

Categories