Pass and print a $_GET variable through php load file by javascript - javascript

I searched for a solution of passing a get variable obtained from index.php page to included.php file[ loaded by javascript ]. A nice solution by php require function is given Pass and print a $_GET variable through an included file by php require function
However, in my case I have
for index.php => url[ index.php?var=item]
<?php
if(isset($_GET['var'])) {
$var=$_GET['var'];
}
?>
<script>
$(document).ready(function(){
$("#ok").load("included.php");
});
</script>
<div id='ok'>
</div>
in included.php [which will be loaded in index.php by javascript load function]
<?php
echo $var;
?>
The error was the undefined var in included.php file.How Can I echo this variable with a combination of php and javascript ?

If you want to pass these variables on to the included file you could go with
$("#ok").load("included.php?<?php echo $urlString; ?>");
The URL string can be generated with this function
function GenGetVars(){
$Base = NULL;
foreach($_GET as $key => $variable){
$Base .= '&'.$key.'='.$variable;
}
return(rtrim($Base, '&'));
}
Another option would be :
$( "#ok" ).load( "included.php", { "choices[]": [ "Jon", "Susan" ] } );
Based upon the first example:
index.php:
<?php
function GenGetVars(){
$Base = NULL;
foreach($_GET as $key => $variable){
$Base .= '&'.$key.'='.$variable;
}
return(rtrim($Base, '&'));
}
if(isset($_GET['var']) === true) {
$var=$_GET['var'];
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<title>Test</title>
<script type="text/javascript">
$(document).ready(function(){
$("#ok").load("included.php?<?php echo GenGetVars(); ?>");
});
</script>
</head>
<body>
<div id='ok'>
</div>
</body>
</html>
included.php
<?php
echo print_r($_GET, true);
?>

index.php:
<?php
function GenGetVars(){
$Base = NULL;
foreach($_GET as $key => $variable){
$Base .= '&'.$key.'='.$variable;
}
return(rtrim($Base, '&'));
}
if(isset($_GET['var']) === true) {
$var=$_GET['var'];
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<title>Test</title>
<script type="text/javascript">
function LoadScriptFile(){
/// SENDING THE INFORMATION BY AJAX
$.ajax({
type : "POST", /// SEND TYPE
url : "getScriptName.php", /// TARGET FILE TO RETRIEVE INFORMATION
data : {
'SomeParamID' : 1,
'AnotherParamID' : 'Dunno.. just something'
},
///######## IN CASE OF SUCCESS
success:function(response){
if( response != "" ){
$.getScript( 'js/' + response + '.js', function( data, textStatus, jqxhr ) {
console.log( data ); // Data returned
console.log( textStatus ); // Success
console.log( jqxhr.status ); // 200
console.log( "Load was performed." );
});
}
else{
alert( "Error retreiving data" );
}
}
}
);
}
</script>
<script type="text/javascript">
$(document).ready(function(){
$("#ok").load("included.php?<?php echo GenGetVars(); ?>");
});
</script>
</head>
<body>
<div id='ok'>
</div>
</body>
</html>
included.php
<?php
echo print_r($_GET, true);
?>
getScriptName.php
<?php
switch($_POST['SomeParamID']){
case 1:
echo 'MyGreatJSFile';
break;
case 2:
echo 'MyNotSoGreatJSFile';
break;
}
?>
You could try this.

Related

Not fetch data using below code

I need to get data from mysql database without refreshing the page using jquery ajax. I have a php script which is working fine. However, my JS seems to be having some problem. Here is the jquery script.
index.php
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery.post demo</title>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<form action="/" id="searchForm">
<input type="text" name="s" class="s" placeholder="Search...">
<input type="submit" value="Search">
</form>
<!-- the result of the search will be rendered inside this div -->
<div id="item"></div>
<script>
// Attach a submit handler to the form
$( "#searchForm" ).submit(function( event ) {
// Stop form from submitting normally
event.preventDefault();
// Get some values from elements on the page:
var $form = $( this ),
url = $form.attr( "action" );
// Send the data using post
var posting = $.post( 'test.php', { s: $(".s").val() } ).done(function( data ) {
alert( "hiiiiiiiiii" + $(".s").val() );
});
// Put the results in a div
});
$.getJSON(
'fetch_data.php',
's='+$('.s').val(),
function(result){
$('#item').empty();
$.each(result.result, function(){
$('#item').append('<p>'+this['s']+'</p>');
});
});
</script>
</body>
</html>
This code is not working. pleas give me solution how it work?
fetch_data.php
<?php
if(!mysql_connect("localhost","root",""))
{
echo "db connection error : ".mysql_error();
exit;
}
else
{
if(!mysql_select_db("test"))
{
header('Content-type: application/json');
echo "db selection error : ".mysql_error();
exit;
}
}
$sql = "select s from test ";
$res = mysql_query($sql);
$result = array();
while($row = mysql_fetch_array($res)){
echo $row[0];
array_push($result,
array('s'=>$row[0]));
}
echo json_encode(array('result'=>$result));
?>

React JS got error of Error: Parse Error: Line 27: Unexpected token . at http://localhost/PHP-React-Demo/ajax_call.html return {cell.data.row}

I want to display the content from database in a react js
React JS got error of
Error: Parse Error: Line 27: Unexpected token . at http://localhost/PHP-React-Demo/ajax_call.html return {cell.data.row}
my code is:
Index.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<link rel="stylesheet" type="text/css" href="css/machineTest.css">
<head>
<title>Index</title>
</head>
<body>
<?php
$servername = "localhost";
$username = "root";
$password = "";
$db_name = "anand";
$conn = new PDO("mysql:host=$servername;dbname=$db_name",$username,$password);
$result = $conn->prepare("SELECT * FROM student");
$result->execute();
?>
<?php
foreach($result as $row){
echo "$row[0]$row[1]$row[2]$row[3]$row[4]";
}
?>
</body>
</html>
and react code is :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Initial Data Via AJAX</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.13.3/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.13.3/JSXTransformer.js"></script>
</head>
<body>
<div id="example"></div>
<script type="text/jsx">
var ImageCollect = React.createClass({
getInitialState: function() {
return {
phpData: []
};
},
componentDidMount: function() {
var self = this;
$.get(this.props.source, function(result) {
var collection = result.data.children;
if (this.isMounted()) {
this.setState({
phpData: collection
});
}
}.bind(this));
},
render: function() {
BDdata = this.state.phpData || [];
return (
<div>
Images:
{BDdata.map(function(cell){
return {cell.data.row}// I think i want to change this line.
})}
</div>
);
}
});
React.render(
<ImageCollect source="http://localhost/PHP-React-Demo/index.php" />,
document.getElementById('example')
);
</script>
</body>
</html>
I just want to display the content retrived from the index.php on react page
In a JSX context, {} denotes a JavaScript expression. In a JavaScript context, {} either denotes a block or an object literal.
return {cell.data.row} is in a JavaScript context (the .map callback), and because of the position of the {...}, they are interpreted as object literal.
But {cell.data.row} is not a valid object literal and I doubt you want to create an object here anyway. Use
return cell.data.row;
instead.

I'm having trouble passing a PHP array to Javascript [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I'm using PHP and javascript to create a banner function. All of my images are in the folder Images/banners, and are being dynamically added by PHP, and then added to theJavaScript array "adImages". That part is working fine, as I can see the array in the JavaScript when I viewsouce. However, the images are not being placed on the page.
Here is my code, what am I missing?
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Rotating Banners</title>
<?php
$dir = 'Images/banner';
$files = scandir($dir);
array_shift($files);
array_shift($files);
?>
<script language="Javascript" type="text/javascript">
// Setting variables
dir = Images/banner/
adImages = <?php echo json_encode($files); ?>;
thisAd = 0
imgCt = adImages.length
// Rotate function
function rotate() {
if (document.images) {
thisAd++
if (thisAd == imgCt) {
thisAd = 0
}
document.adBanner.src=dir+adImages[thisAd]
setTimeout("rotate()", 1 * 1000)
}
}
</script>
</head>
<body onload="rotate()">
<center>
<img src="" name="adBanner" alt="Ad Banner" />
</center>
</body>
</html>
Seems to work for me after making your dir var a string. Using your Chrome Developer Tools / Console pointed the errors out for you. The following code works for me with two sample images:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Rotating Banners</title>
<?php
$dir = 'Images/banner';
$files = scandir($dir);
array_shift($files);
array_shift($files);
?>
<script language="Javascript" type="text/javascript">
// Setting variables
var dir = "Images/banner/",
adImages = <?php echo json_encode($files); ?>,
thisAd = 0,
imgCt = adImages.length;
// Rotate function
function rotate() {
if (document.images) {
thisAd++
if (thisAd == imgCt) {
thisAd = 0
}
document.adBanner.src=dir+adImages[thisAd]
setTimeout("rotate()", 1 * 1000)
}
}
</script>
</head>
<body onload="rotate()">
<center>
<img src="" name="adBanner" alt="Ad Banner" />
</center>
</body>
</html>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script src="jquery.js"></script>
<?php
$dir = '';
$files = array();
$dir = 'Images/banner';
$aExclusion = array( '..', '.' );
$files = array_diff(scandir($dir), $aExclusion);
$files = array_values( $files );
echo '<script>';
echo "var adImages = [];";
echo 'var oData = ' . json_encode( $files ) . ';';
echo '</script>';
?>
<script>
$(document).ready(function()
{
// Get banner count minus one for array offset.
iBannersSize = Object.keys(oData).length - 1;
// Ensure we have at least 1 banner to rotate.
if( iBannersSize > 0 )
{
window.setInterval(function(){
iChangeToImage = Math.round( Math.random() * ( iBannersSize - 0 ) );
$("div#banner_wrapper img").attr("src", 'Images/banner/' + oData[ iChangeToImage ] );
console.log( oData[ iChangeToImage ] );
}, 2000 );
}
});
</script>
</head>
<body>
<center>
<div id="banner_wrapper">
<!-- Render first banner on page load -->
<img src="<?php echo 'Images/banner/' . $files[ 0 ]; ?>" alt="Ad Banner">
</div>
</center>
</body>
</html>

how to auto refresh multiple php variables without refreshing page? I can only do one atm

I'm trying to auto-refresh multiple PHP variables. So far I can only auto-refresh one variable and the rest do not work (it will always be the last one that works, so var2).
I was thinking of making a JSON script and trying to do it like that but how would I go about making each array in the JSON to auto-refresh on my PHP page without refreshing the whole page?
index.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script language="javascript" src="jquery-1.2.6.min.js"></script>
<script language="javascript" src="jquery.timer-1.0.0.js"></script>
<link rel="stylesheet" href="css/bootstrap.css">
<link rel="stylesheet" href="css/bootstrap.min.css">
<script src="jquery-1.9.0.min.js"></script>
<?php $ra = "<div id='c1b'></div>
<script type='text/javascript'>
$(document).ready(function() {
$('#c1b').load('var1.php');
refresh();
});
function refresh(){
setTimeout( function() {
$('#c1b').fadeOut('slow').load('var1.php').fadeIn('slow');
refresh();
}, 2000);
}
</script>";
$rb = "<div id='c2b'></div>
<script type='text/javascript'>
$(document).ready(function() {
$('#c2b').load('var2.php');
refresh();
});
function refresh(){
setTimeout( function() {
$('#c2b').fadeOut('slow').load('var2.php').fadeIn('slow');
refresh();
}, 2000);
}
</script>"; ?>
<?php echo $ra . ' & ' . $rb ?>
var1.php
<?php
include_once 'connect.php';
$d= 'var1';
$q = $handler->prepare("SELECT * FROM var WHERE name = ?");
$q->bindParam(1, $d);
$q->execute();
while($r = $q->fetch()){
$e = $r['names'];
}
echo $e;
?>
var2.php
<?php
include_once 'connect.php';
$d= 'var2';
$q = $handler->prepare("SELECT * FROM var WHERE name = ?");
$q->bindParam(1, $d);
$q->execute();
while($r = $q->fetch()){
$e = $r['names'];
}
echo $e;
?>
As best as I can read this, you're going to have two functions named "refresh" defined on your page.
Try changing the script in your second one to a unique name, e.g.
$(document).ready(function() {
$('#c2b').load('var2.php');
refreshvar2();
});
function refreshvar2(){
setTimeout( function() {
$('#c2b').fadeOut('slow').load('var2.php').fadeIn('slow');
refreshvar2();
}, 2000);
}

getting errors in php coding something undefined variable

I am getting following error in this code : Strict Standards: Only variables should be passed by reference in C:\xampp\htdocs\uploader\upload.php on line 12
Success
also other error are Notice: Undefined variable: fulltarget in C:\xampp\htdocs\uploader\upload.php on line 101
Notice: Undefined variable: fulltarget in C:\xampp\htdocs\uploader\upload.php on line 101
Here is the pastebin link to see the whole code : http://pastebin.com/JKegmNHC
Also here is the code also available.. you can see it through here or using the pastebin link to get the error indication right from the related line....
Here is the code :
<?php
$submit=$_POST['sub'];
if(isset($submit))
{
$name=$_FILES['img']['name'];
$type=$_FILES['img']['type'];
$size=($_FILES['img']['size'])/1024;
$ext=end(explode('.',$name));
if (($ext == "gif")
|| ($ext == "jpeg")
|| ($ext == "jpg")
|| ($ext =="png")
&& ($size > 30))
{
############################## File Renaming ###################################################
$newname=uniqid();
//$ext=end(explode('.',$name));
$fullname=$newname.".".$ext;
$target="pics/";
$fulltarget=$target.$fullname;
if(move_uploaded_file($_FILES['img']['tmp_name'],$fulltarget))
{
echo "Success";
}
else
{
echo "Failed";
}
############################## File Renaming end ###################################################
}
else{
echo "not successful";
}
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<link rel="stylesheet" type="text/css" href="abhi.css" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Php Image Uploader</title>
</head>
<body>
<div id="a1">
<form name="frm" method="post" enctype="multipart/form-data">
<input type="file" name="img" /><br />
<input type="submit" name="sub" value="Store" />
</form>
</div>
<div id="a2">
<?php echo "
<html>
<head>
<title>Aviary Photo Editer</title>
<!-- Load Feather code -->
<script type='text/javascript' src='http://feather.aviary.com/js/feather.js'></script>
<!-- Instantiate Feather -->
<script type='text/javascript'>
var featherEditor = new Aviary.Feather({
apiKey: 'ceegvx4siylhayrr',
apiVersion: 3,
theme: 'dark', // Check out our new 'light' and 'dark' themes!
tools: 'enhance,frames,crop,orientation,brightness,saturation,sharpness,draw,redeye,blemish,effects,stickers,resize,focus,contrast,warmth,colorsplash,text,whiten',
appendTo: '',
onSave: function(imageID, newURL) {
var img = document.getElementById(imageID);
img.src = newURL;
},
onError: function(errorObj) {
alert(errorObj.message);
}
});
function launchEditor(id, src) {
featherEditor.launch({
image: id,
url: src
});
return false;
}
</script>
</head>
<body>
<div id='injection_site'></div>
<img id='image1' src='$fulltarget'/>
<p><input type='image' src='http://images.aviary.com/images/edit-photo.png' value='Edit photo' onclick=\"return launchEditor('image1', '$fulltarget');\" /></p>";
?>
</body>
</html>
As per the [PHP: end - Manual], when you use end() it passes the last element in the array as a reference.
You can try a couple things:
Don't use explode() in end(). Try doing the explode when you declare $name:
$name = explode( '.', $_FILES['img']['name'] );
Use array_slice() and list() instead of end():
list($ext) = array_slice( explode( '.' , $name ), -1 );
Either one would probably work.
You get 'Notice: Undefined variable' errors because you try to use a variable without initializing it first. In your HTML you use '$fulltarget', but it's only set after you submitted the form. If you want to get rid of this notice you should put something like $fulltarget = ''; after your PHP opening tag.
If you will check the PHP end() function documentation http://php.net/manual/en/function.end.php you will see that the function takes an array as a parameter through reference. To fix this error you should save your explode() results as a variable and then pass that variable to end() function. For example: $arr = explode('.', $name); $ext = end($arr);

Categories