I want to get value of $security_code which is in captchaCode.php file, in captcha.php file through javascript.I can not include this file in captcha.php file . Here is the code of Captcha_code.php and this code not comes inside any function of this file:
$captcha = new CaptchaCode();
$security_code = str_encrypt($captcha->generateCode(6));
And here is my javascript function, through this function i want to get the value of $security:
function refresh_captcha()
{
var img = document.getElementById('captcha_img');
img.src = '<?php echo "/captcha_images.php"?>';
jQuery("#captcha_img").attr("src",img.src);
jQuery("#security_code").val("<?php echo $security_code;?>");
}
Actually this code is for getting new encrypted value when captcha is refreshed without refreshing the page.
You have to change the image source assignment related code. No need to assign PHP tag. Just assign the PHP file name instead like this.
function refresh_captcha()
{
var img = document.getElementById('captcha_img');
img.src = '/captcha_images.php';
jQuery("#captcha_img").attr("src",img.src);
/*This line will not work without Ajax request*/
/*jQuery("#security_code").val("<?php echo $security_code;?>");*/
}
Send an ajax request to a page to output only the code like:
File: outputcode.php (demo only)
$captcha = new CaptchaCode();
$security_code = str_encrypt($captcha->generateCode(6));
echo $security_code;
exit;
Next, grab that value using AJAX, like for example in jQuery
$("#refresh_code").on('click', function() {
$.get("outputcode.php", function(data) {
//data will now hold the new code
});
});
Hope this gives you an idea.
If you cannot include the files, you need to use ajax request.
captcha.php
$captcha = new CaptchaCode();
$security_code = str_encrypt($captcha->generateCode(6));
echo json_encode($security_code);
in your js:
<img src="" id="captcha_img" onclick="refresh_captcha()"/>
<script>
function refresh_captcha()
{
$.ajax({
url : 'captcha.php',
type : 'POST',
dataType : 'json',
success : function (security_code) {
var source = security_code;
var img = document.getElementById('captcha_img');
img.src = source;
jQuery("#captcha_img").attr("src",img.src);
jQuery("#security_code").val(source);
}
});
}
</script>
The onclick event on the img could be totally wrong, but for the excercise purpose, I've put it there.
Depends on what $security_code is, you can for example, not use JSON.
In your php file captcha.php,
$captcha = new CaptchaCode();
$security_code = str_encrypt($captcha->generateCode(6));?>
<script>
var code = '<?= $security_code ?>';
</script><?php // rest of the php codes
In your js file
function refresh_captcha()
{
var img = document.getElementById('captcha_img');
img.src = code;
jQuery("#captcha_img").attr("src",img.src);
}
Related
I have uploaded a fiddle of my JS code (http://jsfiddle.net/3mcm2/), at the very bottom of which is the way in which I am calling the JS in my PHP document. In order to run the script, just remove the PHP code comments from the bottom. I just wanted to add that for you to see how I am outputting it in PHP. Also, above those last comments are three lines of comments in the .js file, which are there for you to see what it is that the PHP is echoing just to help you better understand how everything looks.
/* The following is what is in my .js file: (see the bottom of this script for part of
what is in my PHP file) */
var f = document.createElement("form");
f.setAttribute('method', "get");
f.setAttribute('action', "index.php");
var Category = (function () {
var categoryCount = 0;
function elem(tag) { // shortcut
return document.createElement(tag);
}
function text(str) { // shortcut
return document.createTextNode(str);
}
function Category(node) {
var self = this;
this.categoryId = ++categoryCount;
// make add button
this.addButton = elem('button');
this.addButton.appendChild(text('Add Textbox'));
this.addButton.addEventListener('click', function () {
self.addTextbox();
});
// make wrapper
this.wrapper = elem('section');
this.wrapper.setAttribute('id', 'cat'+this.categoryId);
this.wrapper.appendChild(this.addButton);
// make textboxes
this.textboxes = [];
this.addTextbox();
// append to document
if (node) {
this.append(node);
}
}
Category.prototype.addTextbox = function () {
var e = document.createElement("input");
e.setAttribute('name', 'cat-'+this.categoryId+'-textbox[]');
f.appendChild(e); // this is where each textbox is supposed to be added to the form...
this.textboxes.push(e);
this.wrapper.insertBefore(e, this.addButton);
};
Category.prototype.append = function (node) {
return node.appendChild(this.wrapper);
};
return Category;
}());
var s = document.createElement("input"); //input element, Submit button
s.setAttribute('type',"submit");
s.setAttribute('value',"Submit");
f.appendChild(s);
//var cat1 = new Category(document.body);
//var cat2 = new Category(document.body);
//document.getElementsByTagName('body')[0].appendChild(f);
The above comment is only for you to see what this script is doing and those three lines are not actually in my .js file. the following comments are part of what is in my PHP file, pretty much just outputting the above comments:
$counter = 0;
echo '<script type="text/javascript" src="js/categories.js"></script>';
foreach ($catArr as $category) {
$counter++;
echo 'do<script>var cat'.$counter.' = new Category(document.body);</script>';
}
echo "<script>document.getElementsByTagName('body')[0].appendChild(f);</script>";
My problem is that with the form I created in the JS, the GET is not delivering any data. My php page is simply going from index.php to index.php? with the question mark, and not with any of the textbox variables following the question mark. For some reason, the form is not finding those textboxes that are created or their names. Please help me out.
This code:
var cat1 = new Category(document.body);
function Category(node) {
var self = this;
this.categoryId = ++categoryCount;
// make add button
this.addButton = elem('button');
this.addButton.appendChild(text('Add Textbox'));
this.addButton.addEventListener('click', function () {
self.addTextbox();
});
// make wrapper
this.wrapper = elem('section');
this.wrapper.setAttribute('id', 'cat'+this.categoryId);
this.wrapper.appendChild(this.addButton);
// make textboxes
this.textboxes = [];
this.addTextbox();
// append to document
if (node) {
this.appendChild(node);
}
}
appends all your input text boxes to the body and not the form, so when you press Submit no data is being passed
fiddle with working code: http://jsfiddle.net/5H8Pv/1/
index.html
<script>
function check() {
var id = $('input[name=id]').val();
$("#result").load("/ajax.php", {id:id});
}
</script>
<input type="text" size="3" name="id"><br />
<button onclick="check();">Pay</button>
<div id="result"></div>
ajax.php
<?php
$id = (int)$_REQUEST['id'];
//some validations and SQL executions
echo "<script language=JavaScript src='https://*****/index.php?id=$id&invoice=$invoice&sum=$sum.......etc'></script>";
I try to form javascript in php file and embed it into div with id="result".
I've used get, load, ajax, createElement methods but the script doesn't execute.
try this..
$('#result').load('ajax.php');
In your php file ajax.php include the header.
header('Content-Type: text/javascript');
And in index.html add type=”text/javascript” to the script tag.
<script type=”text/javascript”>
function check() {
var id = $('input[name=id]').val();
$("#result").load("/ajax.php", {id:id});
}
</script>
You must load script as real script element. DOM conversion of "<script>/*...*/</script>" may fail in this case. This is done via standart DOM document.createElement function.
var script = document.createElement("script");
script.src = path;
Other way is to download the script via AJAX and then eval it.
Try using getScript:
$.ajax({
url: url,
dataType: "script",
success: success
});
try this:-
"<script language=JavaScript src='https://*****/index.php?id="'.$id.'"&invoice="'.$invoice.'"&sum="'.$sum.'".......etc'></script>";
Why wouldn't you load directly the script URL using AJAX?
ajax.php only should return path to the script:
$id = (int)$_REQUEST['id'];
//some validations and SQL executions
echo "https://*****/index.php?id=$id&invoice=$invoice&sum=$sum.......etc";
Besides that all HTML element attributes should be enclosed with quotes or apostrohpes.
Then you should load this url in javascript and generate script element here:
function loadScript(url,appendTo) {
var script = document.createElement("script")
script.type = "text/javascript";
script.src = url;
if(typeof appendTo.appendChild == "function") //Chceking if we can append script to given element
appendTo.appendChild(script);
else
document.body.appendChild(script) //This will not work in old IE, where document.body is not defined.
}
You call this function with script url and optional target element (where will be put in) as parameters.
Like this:
$.get("ajax.php",{param1:"value"},function(scriptUrl) {loadScript(scriptUrl, document.getElementById("result");})
I am using tinyMCE for Wordpress.
Which is the way to load text from server via AJAX?
Until now I have:
php:
<?php echo the_editor($_POST ? $_POST['content'] : '', $id = 'content'); ?>
javascript (which is failing...):
$("select[name='tpl']").live("change", function(e) {
var file = $(this).val();
var loadUrl = varsJs.WORDPRESS_PLUGIN_URL + "/templates/" + file;
$.get(loadUrl, function(result) {
$("#content").val(result);
});
});
The variable result is loaded with the desired text. No problem with that. But how pass this content to the tinyMCE?
if (typeof tinymce === "object"){
$("select[name='tpl']").live("change", function(e) {
var file = $(this).val();
var loadUrl = varsJs.WORDPRESS_PLUGIN_URL + "/templates/" + file;
$.get(loadUrl, function(result) {
tinymce.get("content").focus();
tinymce.activeEditor.setContent(result);
});
});
}
Note: varsJs is the second parameter of wp_localize_script function used to pass data from php to javascript. Really no needed in this precise issue but useful to know it.
Try this code, where 'content' is your field #ID
tinymce.init(tinyMCEPreInit.mceInit['content']);
this way and once tinymce is also loaded in current html,
you will reinit only one field, the one you received from Ajax Request.
also set this code before ajax saving Call
tinymce.activeEditor.save(); // get editor instance
I am using jquery + the hashchange plugin from ben alman. Below is a standard way to grab the hash name and load in content
$(window).hashchange(function() {
var hash = location.hash;
var array_url = hash.split('#');
var page = $(array_url).last()[0];
$('#content').load( page + '.php', function(){
});
});
But is there any way to do this by grabbing some other variable assigned on a click function or sorted through php, perhaps?
I am working with a multi-artist portfolio site that hands out unique three-four letter codes to images
I'd like to serve these images up through unique urls. This has to be through ajax for many reasons.
I had difficulty adding other ajax history options because this page is already using ajax pagination (to load this content) and lots of htaccess url modrewrites.
I am thinking this might just be impossible.
Here is my current code
$('a.photo').click(function () {
var url = $(this).attr('href'),
image = new Image();
image.src = url;
var clickedLink = $(this).attr('id');
location.hash = clickedLink;
image.onload = function () {
$('#content').empty().append(image);
};
image.onerror = function () {
$('#content').empty().html('That image is not available.');
}
$('#content').empty().html('Loading...');
return false;
});
$(window).hashchange( function(){
var hash = location.hash;
var url = ( hash.replace( /^#/, '' ) || 'blank' );
document.title = url;
})
$(window).hashchange();
and my html / php :
$thethumb = customuniqueidfunc();
<a href="[IMG URL]"
class="photo gotdesc nohover" rel="<?php echo $row['description'] ?>"
id="<?php echo $thethumb; ?>">
This works insofar as the image from the href attr loads into the #content div and the hash from the id attr is added as a hash to the url and to the title of the page, but I am lacking any mechanism to combine the click and the hashchange function, so that each hash actually corresponds to the image.
One method I've used for this before is to run a hash polling function. You can see it in action at this page:
http://www.webskethio.com/#services
Here is the javascript for that page:
http://www.webskethio.com/ws.js
Relevant code:
function pollHash() {
//exit function if hash hasn't changed since last check
if (window.location.hash==recentHash) {
return;
}
//hash has changed, update recentHash for future checks
recentHash = window.location.hash;
//run AJAX to update page using page identfier from hash
initializeFromUrl(recentHash.substr(1));
}
$(document).ready(function(){
/* code removed for readability */
setInterval('pollHash()',100); // Important piece
/* code removed for readability */
});
and
//AJAX function to update page if hash changes
function initializeFromUrl(fromLink) {
/* code removed for readability */
//take hash from function call or from the URL if not
input = fromLink || window.location.hash ;
//remove # from hash
output = input.replace("#","");
//get the URL of the AJAX content for new page
pageId = output;
var url = $(this).attr('href'),
image = new Image();
image.src = url;
var clickedLink = $(this).attr('id');
location.hash = clickedLink;
image.onload = function () {
$('#content').empty().append(image);
};
image.onerror = function () {
$('#content').empty().html('That image is not available.');
}
$('#content').empty().html('Loading...');
}
[EDIT :] Here is the full code for your page that should work, provided you can create a page that just outputs the image's location from the database.
var recentHash = "";
var image_url ="";
$(document).ready(function() {
$('a.photo').click(function (event) {
var clickedLink = $(this).attr('id');
location.hash = clickedLink;
event.preventDefault();
});
setInterval('pollHash()',100);
});
function pollHash() {
//exit function if hash hasn't changed since last check
if (window.location.hash==recentHash) {
return;
}
//hash has changed, update recentHash for future checks
recentHash = window.location.hash;
//run AJAX to update page using page identfier from hash
initializeFromUrl(recentHash.substr(1));
}
//AJAX function to update page if hash changes
function initializeFromUrl(fromLink) {
/* code removed for readability */
//take hash from function call or from the URL if not
input = fromLink || window.location.hash ;
//remove # from hash
output = input.replace("#","");
//get the URL of the AJAX content for new page
pageId = output;
if(pageId != ""){
var temp_url = 'http://whitecu.be/user/mountain/'+pageId+'.html';
$.get(temp_url, function(data) {
image_url = data;
image = new Image();
image.src = image_url;
image.onload = function () {
$('#content').empty().append(image);
};
image.onerror = function () {
$('#content').empty().html('That image is not available.');
}
$('#content').empty().html('Loading...');
});
}else{
window.location = "http://whitecu.be/user/mountain";
}
}
How to access PHP session variables from jQuery function in a .js file?
In this code, I want to get "value" from a session variable
$(function() {
$("#progressbar").progressbar({
value: 37
});
});
You can produce the javascript file via PHP. Nothing says a javascript file must have a .js extention. For example in your HTML:
<script src='javascript.php'></script>
Then your script file:
<?php header("Content-type: application/javascript"); ?>
$(function() {
$( "#progressbar" ).progressbar({
value: <?php echo $_SESSION['value'] ?>
});
// ... more javascript ...
If this particular method isn't an option, you could put an AJAX request in your javascript file, and have the data returned as JSON from the server side script.
I was struggling with the same problem and stumbled upon this page. Another solution I came up with would be this :
In your html, echo the session variable (mine here is $_SESSION['origin']) to any element of your choosing :
<p id="sessionOrigin"><?=$_SESSION['origin'];?></p>
In your js, using jQuery you can access it like so :
$("#sessionOrigin").text();
EDIT: or even better, put it in a hidden input
<input type="hidden" name="theOrigin" value="<?=$_SESSION['origin'];?>"></input>
If you want to maintain a clearer separation of PHP and JS (it makes syntax highlighting and checking in IDEs easier) then you can create JQuery plugins for your code and then pass the $_SESSION['param'] as a variable.
So in page.php:
<script src="my_progress_bar.js"></script>
<script>
$(function () {
var percent = <?php echo $_SESSION['percent']; ?>;
$.my_progress_bar(percent);
});
</script>
Then in my_progress_bar.js:
(function ($) {
$.my_progress_bar = function(percent) {
$("#progressbar").progressbar({
value: percent
});
};
})(jQuery);
You can pass you session variables from your php script to JQUERY using JSON such as
JS:
jQuery("#rowed2").jqGrid({
url:'yourphp.php?q=3',
datatype: "json",
colNames:['Actions'],
colModel:[{
name:'Actions',
index:'Actions',
width:155,
sortable:false
}],
rowNum:30,
rowList:[50,100,150,200,300,400,500,600],
pager: '#prowed2',
sortname: 'id',
height: 660,
viewrecords: true,
sortorder: 'desc',
gridview:true,
editurl: 'yourphp.php',
caption: 'Caption',
gridComplete: function() {
var ids = jQuery("#rowed2").jqGrid('getDataIDs');
for (var i = 0; i < ids.length; i++) {
var cl = ids[i];
be = "<input style='height:22px;width:50px;' `enter code here` type='button' value='Edit' onclick=\"jQuery('#rowed2').editRow('"+cl+"');\" />";
se = "<input style='height:22px;width:50px;' type='button' value='Save' onclick=\"jQuery('#rowed2').saveRow('"+cl+"');\" />";
ce = "<input style='height:22px;width:50px;' type='button' value='Cancel' onclick=\"jQuery('#rowed2').restoreRow('"+cl+"');\" />";
jQuery("#rowed2").jqGrid('setRowData', ids[i], {Actions:be+se+ce});
}
}
});
PHP
// start your session
session_start();
// get session from database or create you own
$session_username = $_SESSION['John'];
$session_email = $_SESSION['johndoe#jd.com'];
$response = new stdClass();
$response->session_username = $session_username;
$response->session_email = $session_email;
$i = 0;
while ($row = mysqli_fetch_array($result)) {
$response->rows[$i]['id'] = $row['ID'];
$response->rows[$i]['cell'] = array("", $row['rowvariable1'], $row['rowvariable2']);
$i++;
}
echo json_encode($response);
// this response (which contains your Session variables) is sent back to your JQUERY
You cant access PHP session variables/values in JS, one is server side (PHP), the other client side (JS).
What you can do is pass or return the SESSION value to your JS, by say, an AJAX call. In your JS, make a call to a PHP script which simply outputs for return to your JS the SESSION variable's value, then use your JS to handle this returned information.
Alternatively store the value in a COOKIE, which can be accessed by either framework..though this may not be the best approach in your situation.
OR you can generate some JS in your PHP which returns/sets the variable, i.e.:
<? php
echo "<script type='text/javascript'>
alert('".json_encode($_SESSION['msg'])."');
</script>";
?>
This is strictly not speaking using jQuery, but I have found this method easier than using jQuery. There are probably endless methods of achieving this and many clever ones here, but not all have worked for me. However the following method has always worked and I am passing it one in case it helps someone else.
Three javascript libraries are required, createCookie, readCookie and eraseCookie. These libraries are not mine but I began using them about 5 years ago and don't know their origin.
createCookie = function(name, value, days) {
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
var expires = "; expires=" + date.toGMTString();
}
else var expires = "";
document.cookie = name + "=" + value + expires + "; path=/";
}
readCookie = function (name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') c = c.substring(1, c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
}
return null;
}
eraseCookie = function (name) {
createCookie(name, "", -1);
}
To call them you need to create a small PHP function, normally as part of your support library, as follows:
<?php
function createjavaScriptCookie($sessionVarible) {
$s = "<script>";
$s = $s.'createCookie('. '"'. $sessionVarible
.'",'.'"'.$_SESSION[$sessionVarible].'"'. ',"1"'.')';
$s = $s."</script>";
echo $s;
}
?>
So to use all you now have to include within your index.php file is
$_SESSION["video_dir"] = "/video_dir/";
createjavaScriptCookie("video_dir");
Now in your javascript library.js you can recover the cookie with the following code:
var videoPath = readCookie("video_dir") +'/'+ video_ID + '.mp4';
I hope this helps.
Strangely importing directly from $_SESSION not working but have to do this to make it work :
<?php
$phpVar = $_SESSION['var'];
?>
<script>
var variableValue= '<?php echo $phpVar; ?>';
var imported = document.createElement('script');
imported.src = './your/path/to.js';
document.head.appendChild(imported);
</script>
and in to.js
$(document).ready(function(){
alert(variableValue);
// rest of js file