Currently I have a PHP file and a .js file. In my PHP file I have div class called wrapper_tab-content. Now the code for this is present in my js file which shows the following code:
$(document).ready(function() {
portalarray = new Array();
$('input.checkbox').change(function(){
portalname = $(this).attr('data-name'); pid= $(this).attr('id');
if ($(this).is(':checked')) {
portalarray.push(pid);
$(".wrapper_tab-content").append('<div class="portalcontent content--active" id="'+pid+'"><div class="col-md-12 text-left">
<label class="control-labels ">Title</label><input id="'+pid+'" name="'+portalname+'" placeholder="'+portalname+' Title" type="text"></div></div>');
}else {
$(".portaltabs .container--tabs li#"+pid).remove();
$(".wrapper_tab-content #"+pid).remove();
tabslength = $(".wrapper_tab-content").length;
}
});
});
Now I have to enter the property title inside value attribute that I can get by using <?php get_portals[0]['property_title'] ?> inside my .js file for which I'm assuming there needs to be an AJAX call being made?
To clear things up for you Javascript is client side and PHP is server side .
What you looking at doing is getting PHP value's into Javascript .There are a few ways to do this . Most programmers use events as server side could have updated during the lifetime of the page
most common is post and get requests through Ajax but you could also get data through an event
<script type='text/javascript'>
document.body.onclick(function(){
var Variable = <?php echo(json_encode($Variable)); ?>;
};
</script>
Related
I have a database table which I am trying to retrieve data from using JQUERY AJAX. When my first page loads it does a php call to a table and populates a select form element. - This works
I then want to select one of the options submit the form and have the row returned via Ajax.
Previously I had the script working with just PHP files but am having trouble getting it to work. When submitting the form my URL is changing:
http://localhost/FINTAN/testertester.php?name=Specifics.
I am not getting anything back. In addition when looking at my console I get a jquery not defined
factory (jquery). I can find the line in question in my jquery ui.js. Not sure if this is the issue or my code has caused the issue. I have cleard the firefox cache and due to the fact I have not had a successful AJAX call via jquery method am guessing it my code.
To get the code below I have mixed and matched a book and an online tutorial and many other sources and this is not my first attempt. Ideally I would like to output table row. However just getting a request working and knowing its not a conflict or compatability issue would makeme feel better and not hindered before I start
<script src="jquery/jquery-ui-1.11.2/jquery-ui.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#btn").click(function(){
var vname = $("#name").val;
}
}
$.post("addithandle1.php",
{
name:vname};
function(response,status){
alert("recieved data-------*\n\nResponse : " + response
+"\n\nStatus : " + status);
}
}
</script>
</head>
<body>
<?php
include "config.php";
if (mysqli_connect_errno($con))
{
}
else
{
$result = mysqli_query($con, "SELECT * FROM script ");
echo " <Form method='post'> <label>Script :</label> <select id='name' name='name' >";
}
while($row = mysqli_fetch_array($result))
{
echo "<option value = '".$row['scriptname']."'>".$row['scriptname']."</option>";
}
echo "</select>";
echo "<button id='btn' class='btn-search'>Load Script </button></form>";
?>
</body></html>
This is my PHP file that I am trying to retrieve from
<?php
include 'config.php';
$batchtype2 = $_POST['name'];
$batchtype2 = mysqli_real_escape_string($con,$batchtype2);
$sql = "SELECT * FROM script WHERE scriptname = '".$batchtype2."' ";
$result = mysqli_query($con,$sql);
$count=mysqli_num_rows($result);
if($count==0 ){
echo "</br></br></br></br></br></br></br><p> No Matching results found</p>";
}
else{
while($row = mysqli_fetch_array($result)) {
echo '<tr><td>'.$row['scriptname'].'</td></tr>';
echo '<tr><td>'.$row['scripthours'].'</td></tr>';
echo '<tr><td>'.$row['scripttotal'].'</td></tr>';
}
}
mysqli_close($con);
?>
Thanks in advance for any help
By making the following corrections (you have some syntax issues as well as usage issues which should be revealed in your browser's console when you load this page) in your JavaScript/jQuery this will work like you expect -
Make sure to change this line -
var vname = $("#name").val;
to this -
var vname = $("#name").val(); // note the parentheses
in your function -
$(document).ready(function(){
$("#btn").click(function(e){
e.preventDefault(); // prevent the default action of the click
var vname = $("#name").val();
$.post("addithandle1.php", {name:vname}, function(response, status) { // POST instead of GET
// never use alert() for troubleshooting
// output for AJAX must be in the callback for the AJAX function
console.log("recieved data-------*\n\nResponse : " + response +"\n\nStatus : " + status);
$('#table').html(response); // put response in div
});
});
});
Now $_POST['name'] should get populated properly.
To get the table to appear in your requesting page first make sure that your PHP forms the table completely.
Add a div to your requesting page and modify the AJAX call above as shown.
<div id="table"></div>
Now, when you make a request the div on the requesting page will be updated with whatever comes back from the PHP script.
There are a couple of things about your script.
First make sure you write well structured code and that it is nothing in the wrongplace / broken.
You have in the $(document).ready(function(){ only the .click event of the button, but you left the ajax request outside, I imagine you did that so it will also make the ajax request in the first page load
The problem is that now it will only make it in the first page load, but not when you click the button, on clicking button you are only getting the value of name.
I recommend you to try something like this:
<script>
$(document).ready(function() {
// bind button click and load data
$("#btn").click(function(){
loadData();
return false; // prevent browser behaviour of the button that would submit the form
}
// load data for the first time
loadData();
};
function loadData() {
var vname = $("#name").val;
$.post("addithandle1.php", { name:vname }, function(response, status) {
alert("recieved data-------*\n\nResponse : " + response
+"\n\nStatus : " + status);
});
}
</script>
A few notes:
I would recommend always putting jquery code inside $(document).ready since that guarantees that jquery was loaded before running it
By default a form that has a submit button that you click, will get the form submitted by the browser, if you use ajax, you should prevent that behaviour, either on the button click event or on form with onsubmit="return false".
I have some pages. In these pages i want to show the error message.
Now i am showing these message through JavaScript.But the code is repeated so many times that's why i have decided to define this message as a constant in config file.
I accessed this constant STORE_OFFLINE_MSG in a div. And then I am using the html of this div , this function return the text of the div as defined in config file and passes it in the variable of JS
this is the code in my config file config.php:
define('STORE_OFFLINE_MSG','hello');
This is the sort of code of php file abc.php
<div class="storeOfflineMsg"><?php echo STORE_OFFLINE_MSG;?></div>
<script type="text/javascript">
var msg = $(".storeOfflineMsg").html();
$.prompt('<h3 Store unavailable</h3>'+msg);
</script>
but if i used this variable in other file only by using the div class then .html() returns NULL.
My second file xyz.php is as:
<script type="text/javascript">
var msg = $(".storeOfflineMsg").html();
$.prompt('Store unavailable</h3>'+msg);
</script>
Please suggest me what to do. and how can i get a php constant in the Java Script through div class.
You can store the variable directly in javascript variable.
<script type="text/javascript">
var msg = "<?php echo STORE_OFFLINE_MSG;?>";
If you want to pass data from PHP to Javascript try this:
echo the data out in the of your page within a script section.
<script type="text/javascript">
<?php
echo 'var offlineMsg = ' . STORE_OFFLINE_MSG . ';';
echo 'var onlineMsg = ' . STORE_OnLINE_MSG . ';';
?>
</script>
These Javascript variables will then be availabe globally to all other javascript code on the page. Much better than placing it in a hidden div.
<button type="button" id="okButton" onclick="funk()" value="okButton">Order now </button>
<script type="text/javascript">
function funk(){
alert("asdasd");
<?php echo "asdasda";?>
}
</script>
When the button is pressed I want to execute PHP code (at this point to echo asadasda)
You could use http://phpjs.org/ http://locutus.io/php/ it ports a bunch of PHP functionality to javascript, but if it's just echos, and the script is in a php file, you could do something like this:
alert("<?php echo "asdasda";?>");
don't worry about the shifty-looking use of double-quotes, PHP will render that before the browser sees it.
as for using ajax, the easiest way is to use a library, like jQuery. With that you can do:
$.ajax({
url: 'test.php',
success: function(data) {
$('.result').html(data);
}
});
and test.php would be:
<?php
echo 'asdasda';
?>
it would write the contents of test.php to whatever element has the result class.
Interaction of Javascript and PHP
We all grew up knowing that Javascript ran on the Client Side (ie the browser)
and PHP was a server side tool (ie the Server side). CLEARLY the two just cant interact.
But -- good news; it can be made to work and here's how.
The objective is to get some dynamic info (say server configuration items) from the server into the Javascript environment so it can be used when needed - - typically this implies DHTML modification to the presentation.
First, to clarify the DHTML usage I'll cite this DHTML example:
<script type="text/javascript">
function updateContent() {
var frameObj = document.getElementById("frameContent");
var y = (frameObj.contentWindow || frameObj.contentDocument);
if (y.document) y = y.document;
y.body.style.backgroundColor="red"; // demonstration of failure to alter the display
// create a default, simplistic alteration usinga fixed string.
var textMsg = 'Say good night Gracy';
y.write(textMsg);
y.body.style.backgroundColor="#00ee00"; // visual confirmation that the updateContent() was effective
}
</script>
Assuming we have an html file with the ID="frameContent" somewhere,
then we can alter the display with a simple < body onload="updateContent()" >
Golly gee; we don't need PHP to do that now do we! But that creates a structure for
applying PHP provided content.
We change the webpage in question into a PHTML type to allow the server side PHP access
to the content:
**foo.html becomes foo.phtml**
and we add to the top of that page. We also cause the php data to be loaded
into globals for later access - - like this:
<?php
global $msg1, $msg2, $textMsgPHP;
function getContent($filename) {
if ($theData = file_get_contents($filename, FALSE)) {
return "$theData";
} else {
echo "FAILED!";
}
}
function returnContent($filename) {
if ( $theData = getContent($filename) ) {
// this works ONLY if $theData is one linear line (ie remove all \n)
$textPHP = trim(preg_replace('/\r\n|\r|\n/', '', $theData));
return "$textPHP";
} else {
echo '<span class="ERR">Error opening source file :(\n</span>'; # $filename!\n";
}
}
// preload the dynamic contents now for use later in the javascript (somewhere)
$msg1 = returnContent('dummy_frame_data.txt');
$msg2 = returnContent('dummy_frame_data_0.txt');
$textMsgPHP = returnContent('dummy_frame_data_1.txt');
?>
Now our javascripts can get to the PHP globals like this:
// by accessig the globals
var textMsg = '< ? php global $textMsgPHP; echo "$textMsgPHP"; ? >';
In the javascript, replace
var textMsg = 'Say good night Gracy';
with:
// using php returnContent()
var textMsg = '< ? php $msgX = returnContent('dummy_div_data_3.txt'); echo "$msgX" ? >';
Summary:
the webpage to be modified MUST be a phtml or some php file
the first thing in that file MUST be the < ? php to get the dynamic data ?>
the php data MUST contain its own css styling (if content is in a frame)
the javascript to use the dynamic data must be in this same file
and we drop in/outof PHP as necessary to access the dynamic data
Notice:- use single quotes in the outer javascript and ONLY double quotes in the dynamic php data
To be resolved: calling updateContent() with a filename and
using it via onClick() instead of onLoad()
An example could be provided in the Sample_Dynamic_Frame.zip for your inspection, but didn't find a means to attach it
You can't run PHP with javascript. JavaScript is a client side technology (runs in the users browser) and PHP is a server side technology (run on the server).
If you want to do this you have to make an ajax request to a PHP script and have that return the results you are looking for.
Why do you want to do this?
If you just want to echo a message from PHP in a certain place on the page when the user clicks the button, you could do something like this:
<button type="button" id="okButton" onclick="funk()" value="okButton">Order now</button>
<div id="resultMsg"></div>
<script type="text/javascript">
function funk(){
alert("asdasd");
document.getElementById('resultMsg').innerHTML('<?php echo "asdasda";?>');
}
</script>
However, assuming your script needs to do some server-side processing such as adding the item to a cart, you may like to check out jQuery's http://api.jquery.com/load/ - use jQuery to load the path to the php script which does the processing. In your example you could do:
<button type="button" id="okButton" onclick="funk()" value="okButton">Order now</button>
<div id="resultMsg"></div>
<script type="text/javascript">
function funk(){
alert("asdasd");
$('#resultMsg').load('path/to/php/script/order_item.php');
}
</script>
This runs the php script and loads whatever message it returns into <div id="resultMsg">.
order_item.php would add the item to cart and just echo whatever message you would like displayed. To get the example working this will suffice as order_item.php:
<?php
// do adding to cart stuff here
echo 'Added to cart';
?>
For this to work you will need to include jQuery on your page, by adding this in your <head> tag:
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
Any server side stuff such as php declaration must get evaluated in the host file (file with a .php extension) inside the script tags such as below
<script type="text/javascript">
var1 = "<?php echo 'Hello';?>";
</script>
Then in the .js file, you can use the variable
alert(var1);
If you try to evaluate php declaration in the .js file, it will NOT work
put your php into a hidden div and than call it with javascript
php part
<div id="mybox" style="visibility:hidden;"> some php here </div>
javascript part
var myfield = document.getElementById("mybox");
myfield.visibility = 'visible';
now, you can do anything with myfield...
We can use php in JavaScript by creating a form element and put the action as a .php page.
Then we use JavaScript to submit that form.
EX:
<!doctype html>
<html>
<head>
<title>PHP Executed with JS</title>
</head>
<body>
<form action="phpCode.php" id="phpCode">.
</form> <!-- This is the form-->
<script>
function runPhp() {
var php =
document.getElementById("phpCode")
php.submit() //submit the form
}
</script>
</body>
The PHP file name would be phpCode.php.
In that file would be your PHP code.
May be this way:
<?php
if($_SERVER['REQUEST_METHOD']=="POST") {
echo 'asdasda';
}
?>
<form method="post">
<button type="submit" id="okButton">Order now</button>
</form>
If you do not want to include the jquery library you can simple do the following
a) ad an iframe, size 0px so it is not visible, href is blank
b) execute this within your js code function
window.frames['iframename'].location.replace('http://....your.php');
This will execute the php script and you can for example make a database update...
Use ajax to send request and echo the response
when successfully executed. Like this:
$.get("site.com/ajax", function(status,data){
alert(status);
});
This can be achieved with jquery library.
You could run PHP at the start of the Page and grap the results from inputs
<?php
c = a * b;
?>
<input type="hidden" name="c" value="<?php c ?>"/>
<button type="submit">Submit</button>
</form>
<script>
let cValue = $('input[name="c"]').val();
alert(cValue);
</script>
I have two separate pages, one page is where it uploads the file and the other page displays the information.
In the imageupload.php page, I have this session below:
$_SESSION['fileImage']['name'] = $_FILES['fileImage']['name'];
I also have a javascript function which calls back to the javascript functiom:
<script language="javascript" type="text/javascript">window.top.stopImageUpload();</script>
Now on a seperate page (QandATable.php), I have a javascript function, but my question is how can I call the $_SESSION code above in the javascript function so I can append it to $('.list')?
Below is javascript function:
function stopImageUpload(success){
var result = '';
if (success == 1){
result = '<span class="msg">The file was uploaded successfully!</span><br/><br/>';
$('.listImage').append('<br/>');
}
else {
result = '<span class="emsg">There was an error during file upload!</span><br/><br/>';
}
return true;
}
You cant, because $_SESSION is a server side variable but you can access it by.
For the entire session variable
<script type="text/javascript" >
var session = <?php echo json_encode($_SESSION); ?>;
</script>
For a particular variable in session.
<script type="text/javascript" >
var session_var = <?php echo json_encode($_SESSION['VAR_NAME']); ?>;
</script>
Now you have js variable called session with that information. However it is not advisable in most situation to output all that info to public pages.
Session variables are stored on the server. JavaScript is executed on the cliend side, so it knows nothing about the server side. It know only as much as you pass to it.
To pass a variable to javascript, use an ajax request, or simply output the values:
<script>
var sesionValue = <?=json_encode($_SESSION['value']);?>;
</script>
You should look into using JQuery, as it makes these AJAX-like tasks much easier.
See my function I wrote just today to do something similar to what you're asking.
This takes some PHP output (returned in the success part of the call to ajax(). The format it takes is in JSON, which is compatible by both PHP and JavaScript (JSON: JavaScript Object Notation).
function viewClientDetails(id) {
var clientParams;
clientParams.clientID = id;
$.ajax({
url: BASE_URL + '/clients/get-client-details.php',
type: 'POST',
data: clientParams,
dataType: 'JSON',
success: function(myClient) {
var name = myClient.name;
$('td#name').html(name);
},
error: function(e) {
console.log(e.responseText);
}
})
}
In my PHP file (called /clients/get-client-details.php) I have something like this:
<?php
...
$myClient = array('name' => 'Mr Foobar');
print json_encode($myClient);
?>
This simply writes my PHP object to JSON format.
In the JS code above, the code inserts a part of the JSON data into an HTML table-data element whose CSS selector ID is #name, with the line: $('td#name').html(name);
Apologies if this confuses you more, I thought I'd show an example of what you can try some time..
This may help you a bit along the way...keep trying things, you'll get there :)
You can't. $_SESSION is a PHP variable, and that code runs server-side.
You'll need to store the value as a Javascript variable in the output from your PHP file, then access that variable in your Javascript.
I have a Flash movie that is embeded in a PHP page. The PHP page displays a value to the user (the number of images they have uploaded). When the user uploads a new image I want the value on the PHP page to reflect the change without refreshing the page.
This value is retrieved from database using MySQL. So heres what Ive done so far -
On the PHP page where I want to show the value I have a div
<div id="content_info"><script type="text/javascript" src="getInfo.php?group= <?php echo($groupid); ?> "></script></div>
This calls an external PHP file that queries the database and outputs the result like this
Header("content-type: application/x-javascript");
//do the query with PHP and get $number and then output
echo "document.write(\" (".$number.")\")";
When the page loads for the first time the correct number shows in the div and so all works fine. The next step is to call something to update the contents of this div when the value changes. So I will set up externalInterface in flash to call a javascript function to do this.
This is where Im stuck, I want to be able to do something like this -
function ReplaceContentInContainer(id) {
var container = document.getElementById(id);
container.innerHTML = getInfo.php?type=new&group= <?php echo($groupid) ?>;
}
and call this by
ReplaceContentInContainer(content_info)
I realise this isnt going to work but can anyone show me how to get this result?
many thanks
group= <?php echo($groupid); ?> will be executed only when PHP creates the page. You should store that value inside a variable in the javascript. See if this works.
<div id="scriptDiv">
<script type="text/javascript">
<!-- store the group id -->
var groupID = <?php echo($groupid); ?>;
function getGroupID()
{
return groupID;
}
function updateValue(value)
{
document.getElementById("content_info").innerHTML = value;
}
</script>
<div id="content_info">
<!-- for initial value -->
<script type="text/javascript"
src="getInfo.php?group= <?php echo($groupid); ?> ">
</script>
</div>
</div>
Now you can use flash's URLLoader:
var ldr:URLLoader = new URLLoader();
var gid:String = ExternalInterface.call("getGroupID");
var req:URLRequest = new URLRequest("getInfo.php");
req.data = {type:"new", group:gid};
ldr.addEventListener(Event.COMPLETE, onLoad);
ldr.addEventListener(IOErrorEvent.IO_ERROR, onError);
ldr.load(req);
private function onLoad(e:Event):void
{
var data:String = URLLoader(e.target).data;
ExternalInterface.call("updateValue", data);
}
private function onError(e:IOErrorEvent):void
{
trace("ioError");
}