This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 4 years ago.
I have index.html where there is nav menu, header, footer and div.content where jQuery parses html of page1.html.
page1.html loads fine, but when I add function to .nextPage2 to load page2.html, it wont work.
page1.html does not have head, body and script.
$( document ).ready(()=> {
//Ajax
$.ajax({
url: 'page1.html',
dataType: "html",
success: function(result){
$('.content').html(result);
}});
$(".nextPage2").click(()=>{
$(".content").html("");
$.ajax({
url: 'page2.html',
dataType: "html",
success: function(result){
$('.content').html(result);
}});
})
//Ajax
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<nav class="navMenu">
<div class="container">
<div class="logo">
</div>
<ul>
<li class="page1">page</li>
<li class="page2">page</li>
<li class="page3">page</li>
</ul>
</div>
</nav>
<div class="container">
<div class="content">
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript" src="script.js"></script>
</body>
</html>
<!--page1.html
<section class="page1">
Bunch of code without head, script, body etc
<button type="button" class="nextPage2" name="button">page2</button>
</section>
-->
Like #Justinas said, you need http://api.jquery.com/on/
$(document).on("click",".nextPage2",()=>{
$(".content").html("");
$.ajax({
url: 'page2.html',
dataType: "html",
success: function(result){
$('.content').html(result);
}});
})
Related
var quoteUrl='http://api.forismatic.com/api/1.0/?method=getQuote&lang=en&format=json';
$(document).ready(function() {
var $loader = $("#btn"),
$insertion=$("#insertionPoint");
$loader.click(function() {
$.ajax({
url:quoteUrl ,
dataType: 'json',
success:function(data){
var quote=data.quoteText;
$insertion.replaceWith('<p>'+quote+'</p>');
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>Random quote Machine</h1>
<div id="insertionPoint">
<p>Quotes come here</p>
</div>
<button id="btn">Next Quote</button>
Task:To gain a quote from forimastic.com's Api
Result: Nothing is Happening
Additional:How can I add codes to make it to gain random quotes if this works?
I got it to work by using jsonp and its callback, following the manual from the API's website.
And I even made it prettier :D
var quoteUrl='http://api.forismatic.com/api/1.0/?method=getQuote&format=jsonp&jsonp=parseQuote&lang=en';
$(document).ready(function() {
$("#btn").click(function() {
$.ajax({
url:quoteUrl ,
crossDomain: true,
jsonpCallback: 'parseQuote',
dataType: 'jsonp',
success:function(data){
$("#insertionPoint>#quote").html(data.quoteText);
$("#insertionPoint>#author").html(data.quoteAuthor);
}
});
});
});
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<h1>Random quote Machine</h1>
<blockquote id="insertionPoint">
<span id="quote">Quotes come here</span>
<footer id="author">Author comes here</footer>
</blockquote>
<button class="btn btn-info" id="btn">Next Quote</button>
You should change #insertionPoint's html instead of replacing it, otherwise the function will no further work since this element will no longer exist.
Replace
$insertion.replaceWith('<p>'+quote+'</p>');
with
$insertion.html('<p>' + quote + '</p>');
i know that this question is a bit childish but i am unable to find the correct solution to this problem...
i am using jquery and ajax call to user search functionality in website with php returning json objects...
when i search users using php file, if the json return is only one array, the jquery prints it on the screen, but when multiple results are returned, i don't know to print them out....
here are the results returned from the php:
{"search":"10
junaid
saleem
junaid#yahoo.com
"}{"search":"13
zzz
aaa
zzz#yahoo.com
"}
and here is the jquery webpage:
<?php
session_start();
require("secure_scripts/getusers.php");
require("secure_scripts/getdp.php");
require("secure_scripts/getusersinfo.php");
if(!isset($_SESSION['id'])){
header("location: index.php");
}else{
$zxcv_lgn = base64_encode($_SESSION['id']);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Welcome <?php echo getusers("first_name"); ?> | Addressbook.com</title>
<script src="jquery.js" type="text/javascript" ></script>
<link rel="stylesheet" href="style.css">
<script type="text/javascript">
$(document).ready(function(){
$("#search_button").click(function(){
$("#search_button").click(function(){ $("#console_loader").hide(); });
$("#console_loader").fadeIn("slow").html("<img src='images/ajax-loader.gif' id='ajax-loader' />");
var send = $("#search").val();
$.ajax({
type: "POST",
url: "secure_scripts/search_users.php",
data: {search: send},
dataType: "json",
success: function(msg){
$("#ajax-loader").fadeOut("slow", function(){
$("#console_loader img").remove();
$("#console_loader").fadeIn("slow").html(msg.search);
});
}
});
});
});
</script>
</head>
<body>
<div id="header">
<p><img src="images/header_logo.png" /><span>AddressBookâ„¢</span></p>
</div>
<div id="wrapper" align="center">
<div id="main">
<div id="content">
<div id="top_nav">
<div class="userinfo"><span class="user_title">Welcome <?php echo getusers("first_name")." ".getusers("last_name"); ?></span></div>
<div class="search">
<form onsubmit="return false" id="search_form">
<input type="text" name="search" class="search_box" id="search" placeholder="Type in to search...">
<input type="button" id="search_button" class="sea" name="search_submit"value="search">
</form>
</div>
</div>
<div id="left_nav">
<div id="dp"><img src="<?php echo getdp(); ?>"></div>
<div class="left_nav_links">Profile</div>
<div class="left_nav_links">Contacts</div>
<div class="left_nav_links">Settings</div>
<div class="left_nav_links">privacy</div>
<div class="left_nav_links">logout</div>
</div>
<div id="console">
<div id="console_top_nav">Your Contacts:</div>
<div id="console_content">
<div id="console_loader" style="display: none;"></div>
</div>
</div>
</div>
</div>
</div>
<div id="footer">
<div id="links"><ul><li>Home</li><li>About</li><li>Contact</li></ul></div>
<div id="copyrights">© 2014 Addressbook.com All Rights Reserved</div>
</div>
</div>
</body>
</html>
whenevery only one object is returned from php, like:
{"search":"13
zzz
aaa
zzz#yahoo.com
"}
it works perfectly, but not with multiple json objects....
thanks in advance!
You need to use jQuery's .each() method, like this:
$(document).ready(function(){
$("#search_button").click(function(){
$("#search_button").click(function(){ $("#console_loader").hide(); });
$("#console_loader").fadeIn("slow").html("<img src='images/ajax-loader.gif' id='ajax-loader' />");
var send = $("#search").val();
$.ajax({
type: "POST",
url: "secure_scripts/search_users.php",
data: {search: send},
dataType: "json",
success: function (msg) {
$.each(function (index, item) {
$("#ajax-loader").fadeOut("slow", function () {
$("#console_loader img").remove();
$("#console_loader").fadeIn("slow").html(item.search);
});
});
}
});
});
});
When your json is received, it is more than likely an array of objects
[{"search":"10
junaid
saleem
junaid#yahoo.com
"}{"search":"13
zzz
aaa
zzz#yahoo.com
"}]
Therefore, by using $.each() to loop through the collection and return the value (index, item) you can get the object's value by referencing it like so:
$("#console_loader").fadeIn("slow").html(item.search);
since json is returning a JavaScript object literal.
Something like this should work:
$.ajax({
type: "POST",
url: "secure_scripts/search_users.php",
data: {search: send},
dataType: "json",
success: function(msg){
$.each(function() {
$("#ajax-loader").fadeOut("slow", function(){
$("#console_loader img").remove();
$("#console_loader").fadeIn("slow").html(msg.search);
});
});
}
});
We're adding $.each() method to the success function in order to run it for each JSON object that gets returned, not just the first.
Here's the jQuery.each() doc for further reading.
edited for clarity
I am trying the following code to call .asmx webserivce, however, its returning [object Object]
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title> </title>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.3/jquery.mobile-1.4.3.min.css" />
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="http://code.jquery.com/mobile/1.4.3/jquery.mobile-1.4.3.min.js"></script>
<link rel="stylesheet" href="icon.css" type="text/css">
<script type="text/javascript" charset="utf-8" src="js/wormhole.js"></script>
<script type="text/javascript">
document.addEventListener(
"backbutton",
function()
{
mosync.app.exit();
},
true);
$(document).bind("mobileinit",function(){
$.mobile.page.prototype.options.addBackBtn = true;
$.mobile.allowCrossDomainPages=true;
$.support.cors= true;
});
$(document).ready(function(e) {
$.ajax({
url: 'http://webservice.gkg4.com/Test.asmx/HelloWorld',
type: 'POST',
crossDomain: true,
contentType: "application/json; charset=utf-8",
dataType: 'json',
success: function(result){
alert(result);
},
error: function(result){
alert(result);
}
});
});
</script>
</head>
<body>
<div data-role="page" id="home">
<div data-role="header">
<img src="image/png/chat.png" alt="image">
Menu
<div data-role="popup" id="popupPanel" >
<ul data-role="listview" data-inset="true" style="min-width:210px;" data-theme="b">
<li data-role="divider" data-theme="a">Menu</li>
<li>About Us</li>
<li>Contact Us</li>
<li><a href="#" id="chat" rel="external" >Live Chat</a></li>
<li>Exit</li>
</ul>
</div>
</div>
<div data-role="content" data-theme="b">
<div style="text-align:center">
</div>
<h4><center> Member's Login</center></h4>
</div>
<div data-role="footer" data-position="fixed">
<div data-role="navbar" data-iconpos="left">
</div>
</div>
</div>
</body>
</html>
The URL for webservice is live so you can check the same at your end.
Any help appreciated.
Code in in document.Ready section
Is the page where you are calling from also from webservice.gkg4.com? If not, it is illegal to call ajax from a different domain, and the alert that you are seeing is actually from the error handler.
Another problem is that the contentType is json, whereas the web service is returning XML.
I am trying to create a small angular that takes a json file and displays the data on an html page. However I am getting the following error: POST bookmarks/data/bookmarks.json 405 (Method Not Allowed).
Here is my code:
<html lang="en" ng-app="bookmarksApp" id="ng-app">
<head>
<link rel="stylesheet" href="css/styles.css" />
</head>
<body ng-controller="BookmarkController as bookmarksCtrl">
<article class="main-content" role="main">
<section class="row">
<div class="content">
<div class="bookmarks-list">
<h1>Christine's Bookmarks</h1>
<ul>
<li ng-repeat="bookmark in bookmarksCtrl.bookmarks" class="">
<h3>{{bookmark.name}}</h3>
{{bookmark.url}}
</li>
</ul>
</div>
</div>
</section>
</article>
<script type="text/javascript" src="scripts/angular.min.js"></script>
<script type="text/javascript" src="scripts/main.js"></script>
</body>
</html>
and my angular code:
(function() {
var app = angular.module('bookmarksApp', []);
app.controller('BookmarkController', function($scope, $http) {
$http({ method: 'POST', url: 'data/bookmarks.json' }).success(function (data) {
console.log('hello');
$scope.bookmarks = data; // response data
}).
error(function (data) {
console.log(data);
});
});
})();
Any ideas where I am going wrong? Thanks.
Try to change the POST to GET.
Also fix the problem in ng-repeat
use
<li ng-repeat="bookmark in bookmarks" class="">
at the place of
<li ng-repeat="bookmark in bookmarksCtrl.bookmarks" class="">
If POST is not allowed try GET, if you have to use POST then you need to change backend to allow post requests
$http({ method: 'POST', url: 'data/bookmarks.json' }).success(function (data) {
I have one main page with menu buttons. When clicked, they change the main "content" area with AJAX. In the header of this page I have all of the appropriate Dojo references.
I know the AJAX works because i have successfully pulled in and displayed data in the content area, and I know the Dojo Dijit TimeTextBox works because I have successfully displayed it before I make any calls with AJAX.
When I try to make a call with AJAX and pull in new input fields for the TimeTextBox widget, they display only as regular text boxes, and seem to ignore the fact that I have them set to be the TimeTextBox.
Can anyone tell me how to fix this issue?
EDIT:
Here is the code:
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Admin Page</title>
<link rel="stylesheet" type="text/css" href="styles/adminPage.css" />
<link rel="stylesheet" type="text/css" href="styles/adminStyle.css" />
<link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/dojo/1.6.1/dojo/resources/dojo.css">
<link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/dojo/1.6.1/dijit/themes/claro/claro.css">
<script
type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/dojo/1.7.2/dojo/dojo.js"
djConfig="parseOnLoad:true"></script>
<script type="text/javascript">
dojo.require("dojo.parser");
dojo.require("dijit.form.Button");
dojo.require("dijit.form.TimeTextBox");
</script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
require(["dojo/ready", "dijit/form/TimeTextBox"],
function(ready, TimeTextBox){
ready(function(){
new TimeTextBox({name: "timeInput", value: new Date(),
constraints: {
timePattern: 'HH:mm:ss',
clickableIncrement: 'T00:15:00',
visibleIncrement: 'T00:15:00',
visibleRange: 'T01:00:00'
}
}, "timeInput");
});
});
function getPage(page)
{
$.ajax({
url: "admin"+page+".php",
type: "POST",
cache: false,
success: function (html) {
$('#content').html(html);
$('#content').fadeIn('slow');
}
});
}
</script>
</head>
<body class="claro">
<div id="container">
<div id="header">
<span class="headerTitle">Lehman Nursery</span>
</div>
<div id="content">
<input type='text' name='date1' id='time1' value='T15:00:00'
data-dojo-type='dijit.form.TimeTextBox'
required='true' />
</div>
<div id="menu">
<a onclick="getPage('Home')">
<div id="homeButton" class="menuAppearance">
<img src="images/icons/home.png"/><br />
</div>
</a>
<a onclick="getPage('Links')">
<div class="button menuAppearance">
<div class="menuTitle"><img src="images/icons/links.png"/><br />Links</div>
<div class="description">
</div>
</div>
</a>
<a onclick="getPage('Hours')">
<div class="button menuAppearance">
<div class="menuTitle"><img src="images/icons/pictures.png"/><br />Pictures</div>
<div class="description">
</div>
</div>
</a>
<a onclick=getPage('Events')>
<div class="button menuAppearance">
<div class="menuTitle"><img src="images/icons/events.png"/><br />Events</div>
<div class="description">
</div>
</div>
</a>
<a onclick=getPage('Feedback')>
<div class="button menuAppearance">
<div class="menuTitle"><img src="images/icons/feedback.png"/><br />Feedback</div>
<div class="description">
</div>
</div>
</a>
</div>
</div>
</body>
<form>
<input type="text" name="date1" id="time1" value="T15:00:00"
data-dojo-type="dijit/form/TimeTextBox"
onChange="require(['dojo/dom'], function(dom){dom.byId('val').value=dom.byId('time1').value.toString().replace(/.*1970\s(\S+).*/,'T$1')})"
required="true" /></form>
^^That is the data being pulled in
Are the css files for those dijits pulled up? You might want to require them at the beginning (when the page loads) which get cached and will be used when the dijits are pulled via AJAX.
EDIT: Not sure but can suggest you try to add startup() call for the widget you created.
it apears to me like you are forgoetting to call:
dojo.parser.parse();
after setting the content i your ajax call. it should look like this:
function getPage(page)
{
$.ajax({
url: "admin"+page+".php",
type: "POST",
cache: false,
success: function (html) {
$('#content').html(html);
dojo.parser.parse();
$('#content').fadeIn('slow');
}
});
}
the dojo parser will not execute by itself, it is too resourses expensive to do that, so each time the content changes so you add a dijit you moust call dojo.parser.parse();