Javascript not working in JQuery loaded DIV - javascript

I load pages into a div , my question is i cant execute javascript code in page1.php.. How can i execute code when i load page in to div.. thanks for your help..
here is my codes
index.php :
<script language="JavaScript" type="text/javascript">
function swapContent(cv) {
$("#content").html('<img class="loader" src="images/loader.gif"/>').show();
var url = "load.php";
$.post(url, {contentVar: cv} ,function(data) {
$("#content").html(data).show();
});
}
</script>
Button1
Button2
<div id="content"></div>
load.php :
<?php
if(isset($_GET['contentVar']))
{
$contentVar = $_GET['contentVar'];
}else{
$contentVar = $_POST['contentVar']; }
if ($contentVar == "page1") {
include("page1.php");
} else if ($contentVar == "page2") {
include("page2.php");
}
and example for page1.php
<script type="text/javascript" src="nicEdit.js"></script>
<script type="text/javascript">
bkLib.onDomLoaded(function() { nicEditors.allTextAreas() });
</script>
<textarea name="message" id="message" cols="45" rows="5"></textarea>

Data returned from Ajax is treated like plain text, so any Javascript within it is not executed by default. See this article.
Try using .load() instead of $.post() :
function swapContent(cv) {
$("#content").html('<img class="loader" src="images/loader.gif"/>').show();
var url = "load.php";
$("#content").load(url, {contentVar: cv});
}

Related

How can I load all the website content before call a JavaScript function in php

<?php
$homepage = file_get_contents('https://finance.yahoo.com/quote/0016.HK/news p=0016.HK"');
echo $homepage;
?>
<script type="text/javascript">
function test(){
.....
}
The script was executed before the website load all the contents and thus, I can't get all the content after running the script.
How can I fully get the content from the website first and then run the script? thanks!
<script type="text/javascript">
document.addEventListener( 'DOMContentLoaded', function( event ) {
function test(){
console.log("DOM loaded");
}
});
</script>

I cant see data from the jquery post

I wanted to perform jquery post to php and get the data and post to the console log. But however i cant find data on the console.log after performing post the data. my code is found below...........please help me...
student html page
<html>
<head>
<title>NEW AJAX GET</title>
<script type="text/javascript" src="/Cesium-1.34/ThirdParty/jquery-1.11.3.min.js"></script>
</head>
<body>
<script type="text/javascript">
showData();
function showData()
{
$.post("student.php",
{
PostLastName: "Abdullah",
PostLastReligion: "Muslim"
},
function(data)
{
console.log(data);
});
});
</script>
</body>
</html>
student.php script
<?php
if ((empty($_POST["PostLastName"])) && (empty($_POST["PostLastReligion"])))
{
//Return "Posted Values are empty" if the values is empty
$post_string = 'Posted Values Are Empty';
//echo "<script>console.log(".$post_string.");</script>";
echo $post_string;
}
else
{
//Return the Post Data
$post_string= 'Post Last Name = '.$_POST["PostLastName"]."\n".' Post Last Religion = '.$_POST["PostLastReligion"].'';
//echo "<script>console.log(".$post_string.");</script>";
echo $post_string;
}
?>
I have test your code. i think check first check your loaded jquery included in header.
After change some code like below mention and test your browser console.
<html>
<head>
<title>NEW AJAX GET</title>
<script type="text/javascript" src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<script type="text/javascript">
showData();
function showData()
{
$.post( "student.php", { PostLastName: "Abdullah", PostLastReligion: "Muslim" })
.done(function( data ) {
console.log(data);
});
};
</script>
</body>
</html>
I hope u resolve u r issue.

jQuery loads the content .phtml into a specific <div> (Magento 2)

It is necessary to load via a script content .phtml > in div.
$(document).ready(function(){
$("button").click(function(){
$("#div1").load("demo_test.txt");
});});
I created testinfo.phtml (external content-file)
and created testcms.phtml, put code:
<?php $TestInfo = $this->getLayout()->createBlock("Magento\Framework\View\Element\Template")->setTemplate("Magento_Cms::testinfo.phtml")->toHtml();?>
<div id="div1"></div>
<button class="testinfo">Get External Content</button>
<script type="text/x-magento-init">
{
"*": {
"Magento_Cms/js/testinfo": {
"testinfo": "<?php echo $TestInfo; ?>"
}
}
}
Created file testinfo.js and put code:
define(["jquery"], function($) {
"use strict";
$(document).ready(function() {
$('.testinfo').click(function() {
$("#div1").load( ? ? ? ? ? ? )
});
});
});
In the load() need to place the URL or data. URL string is not working. What need to insert Data, I cannot understand. I need your advice.

Load reCAPTCHA dynamically

There are several ways to load reCAPTCHA using javascript such as below:
<html>
<head>
<title>Loading captcha with JavaScript</title>
<script src="https://code.jquery.com/jquery-1.12.0.min.js"></script>
<script type='text/javascript'>
var captchaContainer = null;
var loadCaptcha = function() {
captchaContainer = grecaptcha.render('captcha_container', {
'sitekey' : 'Your sitekey',
'callback' : function(response) {
console.log(response);
}
});
};
</script>
</head>
<body>
<div id="captcha_container"></div>
<input type="button" id="MYBTN" value="MYBTN">
<script src="https://www.google.com/recaptcha/api.js?onload=loadCaptcha&render=explicit" async defer></script>
</body>
</html>
This code load captcha on pageload. I want load reCAPTCHA just when clicked on "MYBTN". So the code changes into:
<html>
<head>
<title>Loading captcha with JavaScript</title>
<script src="https://code.jquery.com/jquery-1.12.0.min.js"></script>
<script type='text/javascript'>
$('#MYBTN').on('click',function(){
var captchaContainer = null;
var loadCaptcha = function() {
captchaContainer = grecaptcha.render('captcha_container', {
'sitekey' : 'Your sitekey',
'callback' : function(response) {
console.log(response);
}
});
};
});
</script>
</head>
<body>
<div id="captcha_container"></div>
<input type="button" id="MYBTN" value="MYBTN">
<script src="https://www.google.com/recaptcha/api.js?onload=loadCaptcha&render=explicit" async defer></script>
</body>
</html>
But this code didn't work when I click on "MYBTN" and reCAPTCHA not load.
Help me plz. Thanks.
You just need to call loadCaptcha()
$('#MYBTN').on('click',function(){
var captchaContainer = null;
var loadCaptcha = function() {
captchaContainer = grecaptcha.render('captcha_container', {
'sitekey' : 'Your sitekey',
'callback' : function(response) {
console.log(response);
}
});
};
loadCaptcha(); // THIS LINE WAS MISSING
});
<script src="https://code.jquery.com/jquery-1.12.0.min.js"></script>
<div id="captcha_container"></div>
<input type="button" id="MYBTN" value="MYBTN">
<script src="https://www.google.com/recaptcha/api.js?onload=loadCaptcha&render=explicit"></script>
Simple situation
Html
<input type="button" id="MYBTN" value="create captcha">
<div id="captcha_container"></div>
JS
var testSitekey = '6LeLzA4UAAAAANNRnB8kePzikGgmZ53aWQiruo7O';
$('#MYBTN').click(function() {
$('body').append($('<div id="captcha_container" class="google-cpatcha"></div>'));
setTimeout(function() {
grecaptcha.render('captcha_container', {
'sitekey': testSitekey
});
}, 1000);
});
Online demo (jsfiddle)
You just mentioned onload in your embedded script. Either you just remove onload from your embedded script or just keep your code outside of the onclick event in the function name loadCaptcha.
1. First Solution:
$('#MYBTN').on('click',function(){
var captchaContainer = null;
var loadCaptcha = function() {
captchaContainer = grecaptcha.render('captcha_container', {
'sitekey' : 'Your sitekey',
'callback' : function(response) {
console.log(response);
}
});
}
});
<script src="https://www.google.com/recaptcha/api.js?render=explicit"></script>
2. Second Solution
<script type='text/javascript'>
var captchaContainer = null;
var loadCaptcha = function() {
captchaContainer = grecaptcha.render('captcha_container', {
'sitekey' : 'Your sitekey',
'callback' : function(response) {
console.log(response);
}
});
};
</script>
<script src="https://www.google.com/recaptcha/api.js?onload=loadCaptcha&render=explicit" async defer></script>
In first Solution your code will work when you click your button. Even you don't have to put then in loadCaptcha function you can directly call grecaptcha.render.
But when you mention onload in your script tag then it will not work according to your click then it will find the callback function you mentioned in the script. And as you wrote the loadCaptcha in onload of script and you wrote this function inside the onClick event. When the script tag executed, the code tried to find the loadCaptcha function which was not initialised till the script tag executed (as it would initialise on click event), So your script was not working.
JS
// Loading captcha with JavaScript on button click
jQuery(document).ready(function ($) {
$('#MYBTN').on('click',function() {
$.getScript( "https://www.google.com/recaptcha/api.js?render=__YOUR_KEY__" )
.done(function( script, textStatus ) {
if(typeof grecaptcha !== "undefined") {
grecaptcha.ready(function () {
grecaptcha.execute('__YOUR_KEY__', {
action: 'homepage'
})
.then(function (token) {
var recaptchaResponse = document.getElementById('captcha_container');
recaptchaResponse.value = token;
});
// Your other code here
// You can control captcha badge here
});
}
});
});
});
HTML
// Required HTML:
<body>
<input type="button" id="MYBTN" value="MYBTN">
<div id="captcha_container"></div>
</body>
I've implemented the captcha to be loaded only after one of the required fields of my form was focus. I also implemented a check variable to see if the captcha's dependencies were inserted before.
Here is is:
jQuery('#MyRequiredInputId').focus(function () {
if(typeof loadedRecaptcha != 'undefined'){
return;
}
jQuery.getScript("https://www.google.com/recaptcha/api.js?render=___YOURKEY__")
.done(function (script, textStatus) {
if (typeof grecaptcha !== "undefined") {
grecaptcha.ready(function () {
var siteKey = '___YOURKEY___';
jQuery('body').append(jQuery('<div id="captcha_container" class="google-cpatcha"></div>'));
setTimeout(function() {
grecaptcha.render('captcha_container', {
'sitekey': siteKey
});
}, 1000);
});
}
loadedRecaptcha = true;
});
});
Note that in my case, I have a <div id= "captcha_container"></div> where I want to display my captcha.
Result:
I got the same issue today when I discovered that there are about 21 requests for Google Recaptcha even without open the login modal, this is indeed too much ):
After trying this method:
HTML
<div class="row">
<div class="col-sm-12 btm10">
<div id="captcha_container"></div>
</div>
</div>
JS
<script>
var Sitekey = '<?php echo config('google_key') ?>';
$('#loginbtn').click(function() {
$('body').append($('<div id="captcha_container" class="google-cpatcha"></div>'));
setTimeout(function() {
grecaptcha.render('captcha_container', {
'sitekey': Sitekey
});
}, 1000);
});
</script>
finally, I get the results I want, now the recaptcha only loads when the login modal opens (based onClick function).
Unfortunately, I found that the main Google Recaptcha script still loads in console even while using the delay method mentioned above because the main script is declared on the page head:
<script src="https://www.google.com/recaptcha/api.js"></script>
So, I removed it from the page head then combined some lines of codes together to get it to work and only loads when the modal opens as follow:
Final code:
<div class="row">
<div class="col-sm-12 btm10">
<div id="captcha_container"></div>
</div> //Wherever you want the reCaptcha to appear
</div>
<script>
//Add to the header or the footer it doesn't matter
var Sitekey = '<?php echo config('google_key') ?>';
$('#loginbtn').click(function() {
$.getScript("https://www.google.com/recaptcha/api.js") //The trick is here.
$('body').append($('<div id="captcha_container" class="google-cpatcha"></div>'));
setTimeout(function() {
grecaptcha.render('captcha_container', {
'sitekey': Sitekey
});
}, 1000);
});
</script>
You can view it in action here:
https://youtu.be/dAZOSMR8iI8
Thank you
Tell Google you want to render the recaptcha explicitly (when you are ready). https://www.google.com/recaptcha/api.js?render=explicit
After the api script has run grecaptcha is available globally.
<!DOCTYPE html>
<html lang="en">
<head> </head>
<body>
<div id="whereIWantRecaptcha"></div>
<button id="myButton">show Recaptcha</button>
<script
src="https://www.google.com/recaptcha/api.js?render=explicit"
async
defer
></script>
<script>
var button = document.querySelector('#myButton');
button.addEventListener('click', function(){
grecaptcha.render('whereIWantRecaptcha', {
'sitekey' : '6LeIxAcTAAAAAJcZVRqyHh71UMIEGNQ_MXjiZKhI'
});
});
</script>
</body>
</html>

How to include a php page through javascript and update it every so often? [duplicate]

I got this code from a website which I have modified to my needs:
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>
</head>
<div id="links">
</div>
<script language="javascript" type="text/javascript">
var timeout = setTimeout(reloadChat, 5000);
function reloadChat () {
$('#links').load('test.php #links',function () {
$(this).unwrap();
timeout = setTimeout(reloadChat, 5000);
});
}
</script>
In test.php:
<?php echo 'test'; ?>
So I want test.php to be called every 5 seconds in links div. How can I do this right?
Try this out.
function loadlink(){
$('#links').load('test.php',function () {
$(this).unwrap();
});
}
loadlink(); // This will run on page load
setInterval(function(){
loadlink() // this will run after every 5 seconds
}, 5000);
Hope this helps.
Try using setInterval and include jquery library and just try removing unwrap()
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script language="javascript" type="text/javascript">
var timeout = setInterval(reloadChat, 5000);
function reloadChat () {
$('#links').load('test.php');
}
</script>
UPDATE
you are using a jquery old version so include the latest jquery version
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
Try to not use setInterval.
You can resend request to server after successful response with timeout.
jQuery:
sendRequest(); //call function
function sendRequest(){
$.ajax({
url: "test.php",
success:
function(result){
$('#links').text(result); //insert text of test.php into your div
setTimeout(function(){
sendRequest(); //this will send request again and again;
}, 5000);
}
});
}
you can use this one.
<div id="test"></div>
you java script code should be like that.
setInterval(function(){
$('#test').load('test.php');
},5000);
<script type="text/javascript">
$(document).ready(function(){
refreshTable();
});
function refreshTable(){
$('#tableHolder').load('getTable.php', function(){
setTimeout(refreshTable, 5000);
});
}
</script>

Categories