PHP equivalent to jQuery html() or text() - php

Im trying to print the result of a php function to specific html id or class
the php function is called by a button input
jQuery code:
function myfunction() {
$answer = 'random text <b>' + $radomvar +'more random';
$('#resultline').html($answer);
}
is there an equivalent for the
$('#resultline').html($answer);
in php?

What you're asking doesn't make sense. You can can embed PHP code alongside HTML code and it is processed by the server before the HTTP response is sent back to the client.
Therefore, why not do something like:
<span id="resultline"><?php echo myFunction(); ?></span>
Where myFunction is a PHP function that returns the string you want to embed?

You can write your javascript code in .php file and then use your JavaScript function like this:
function myfunction() {
$answer = 'random text <b>' + '<?php echo myfunc($radomvar); ?>' +'more random';
$('#resultline').html($answer);
}

No there isn't. PHP is server side so after the request is done it can't change the webpage anymore. If you want to do that the only option is an AJAX call with for example JQuery as framework.

You can't do proper DOM Manipulation with PHP. For the purpose of your question, you'd have to use jQuery's ajax function to request the variable value from the backend, and fill the container when you retrieve it.
js script:
jQuery.ajax({
url: 'myfunction.php',
data: {varname: randomvar},
type: 'POST'
}).done(function(response) {
$('#resultline').html(response);
});
myfunction.php
<?php
function myfunction($radomvar) {
$answer = 'random text <b>'. $radomvar .'more random';
return $answer;
}
echo myfunction($_POST['varname']);
Please note that you don't need PHP to interpolate variables in a string. That function doesn't need PHP whatsoever to run. If the only purpose of PHP here is to get $radomvar value, and you're positively sure you want to have PHP in your frontend, then it would suffice to do something like
<script>
function myfunction(radomvar) {
var answer = 'random text <b>' + radomvar +'more random';
$('#resultline').html(answer);
}
var randomvalue='<?php echo $radomvar; ?>';
myfunction(randomvalue);
</script>

Well their is no function equal to that in php, however you can easily achive the same effect rather easy by writing few more lines of code.
<div id="resultline"><?php echo $answer; ?></div>
instead you have to place php echo code where you want printed out on the html page, otherweise you have to use ajax or something else than php.

Related

How to call $_SESSION in javascript

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.

How to make the JS function get the data from the database everytime I call it?

I am using a code look like this:
<script>
function getdata()
{
var employee =
<?php
//connect to database and get employee name
echo "'" . $row['empnm'] "'";
?>;
}
</script>
print them
It works, but the function is running the PHP code only on the page loading and not every time I call the function. So, if the target employee name is changed the JS function will show the old name untill the page is reloaded. How to make the JS function get the data from the database everytime I call it?
look into a library like jQuery
Then using the following code
function getdata(){
$.post("path/to/file.php", function(data) {
var employee = data;
// do whatever with the data.
});
}
and you can still use your same html
print them
and file.php
<?php
// connect to your db, get your results, echo them back
echo $row['empnm'];
?>
When you first request the page, PHP renders out a whole string of html, then your browser executes that generated HTML, not the original PHP. i.e. your server is going to send something like
<script>
function getdata()
{
var employee =
"hello world";
}
</script>
print them
So, as far as the web browser knows, "hello world" is just hardcoded there.
You'll need to look into AJAX for how to make it work. Check out this beginners' tutorial on using jQuery for ajax: http://www.devirtuoso.com/2009/07/beginners-guide-to-using-ajax-with-jquery/
Define a global variable
<script>
var employee = <?php echo "'" . $row['empnm'] "'";?>;
function getdata(){
return employee;
}
</script>
Now keep on changing variable employee whenever it is changed
print them
If you're in a PHP loop -- it does looks like you are, since -- you can use PHP to define the parameter to be passed into getdata() in your loop; e.g.
<script type="text/javascript">
function getdata(employee) {
// connect to database and get employee name
}
</script>
<?php
foreach ($loopData as $row) {
print 'print them';
}
?>

Php to return value

EDIT: Check at the end of this for the solution
I am new to php, ajax and all other things :)
My question is: is there a way for a php file to return a value?
I have:
a file "loadImages.php" containing the script to get the paths to images from the database.
an image gallery where I want to load images via ajax.
a database containing the path to the images (/images/image1.jpg, /images/image2.jpg).
4 categories of images.
What i'm trying to do is :
When clicking on a link (example, first category), I want to call via jquery's ajax(), loadImages.php with the category passed via POST (cat0, cat1, cat2, ...)
I want to return the value from this php file for example : <img src="image/image1.jpg" />, so via javascript, I can retrieve this string. Using only return in my php file returns XMLHttpRequest when i'm putting the ajax() function in a variable instead of the string <img>.
Is there a way to do it? Or maybe a better way, as I don't fully understand ajax.
Thank you! Sorry for my bad grammar.
Below is a more precise map of what i'm trying to do.
JavaScript:
var test = $.ajax({
type: "POST",
url: "loadImages12.php",
data: "category=0",
complete: function() {
alert("COMPLETE");
},
error: function (){
alert("NOT LOADED");
}
});
PHP (loadImages.php)
function createThumb() {
if(isset($_POST['category'])) {
$imageQuery = mysql_query("SELECT * FROM t_pictures WHERE p_category = 0");
$thumbHtml = '';
while ($tempImageQueryFetch = mysql_fetch_assoc($imageQuery)){
$thumbHtml .= '<img src="ressources/images/' . $tempImageQueryFetch["p_fileName"] . 'Small.jpg" />';
}
return $thumbHtml;
}
else {
$noCategory = "NO CATEGORY TEST";
return $noCategory ;
}
}
createThumb();
SOLVED
Php File
function createThumb(){
//Mysql request
$someVar = //Result of request
return $someVar
}
echo createThumb()
Javascript
$("#someDiv").load("loadImages.php", {category:0});
An AJAX request to PHP is exactly the same as a normal request for a website. You request data from example.com/foo/bar and in return you receive text. The return statement of PHP has nothing to do with what's returned to the client. Only things you echo or otherwise output will be received by the client. That's the same for normal pages and AJAX requests.
So, to "return" <img src="image/image1.jpg" /> to your Javascript AJAX call, echo that string in PHP.
if you want to use the php file that you already have (loadImages.php) just echo the result of the function:
echo createThumb();
Just make the php script to return the path to thumbnail.
and then do something like this in js
somediv.html('<a href="#" class="thumbnail"><img src="">');
and just use the path returned by the php file for the img src ..

Cakephp: how to pass values into a javascript file?

I have some javascript that is being included in a view and I used inkedmn's method in this thread:
adding-page-specific-javascript-to-each-view-in-cakephp
So I now have the following code in my view:
$this->set('jsIncludes',array('google')); // this will link to /js/google.js
But I need to pass some values from the view into the javascript file and I'm unsure of how to accomplish this.
Update: I guess one option would be to echo the values in the php file, enclose in a div tag, and then use a getElementById() in the javascript code.
You should be able to inject a <script> tag directly into the HTML with the data you want:
<script type="text/javascript">
var mynum = <?php echo intval($num); ?>;
var mystring = "<?php echo addslashes($string); ?>";
var myarray = <?php echo json_encode(array("one" => 1, "two" => 2)); ?>;
</script>
Any javascript elsewhere should be able to use these variables.
Note: if the code using this data runs earlier in the page, they obviously won't see these variables yet. If that's the case, either ensure that your data is loaded first, or you can delay the code from running until the page is fully loaded, using either setTimeout() or a document.onready event.
Do you have some code that runs automatically? You could wrap it inside a function, and pass the function the necessary parameters.
For example, let's you currently have the following code in my-script.js:
window.onload = function() {
alert('My favorite fruits are apples, and my favorite color is red.');
}
Wrap it in a function like this:
function initialize(args) {
window.onload = function() {
alert('My favorite fruits are ' + args.fruit +
', and my favorite color is ' + args.color + '.');
}
}
Then, output a <script> element using PHP somewhere after my-script.js is loaded, and call the function. Here's an example output:
<script>
initialize({fruit: 'apples', color: 'red'});
</script>
$this->Js->set('varname',$value);
from js file
var myvar = window.app.varname;
These are following step:
1) Include the js helper in AppController.php
public $helpers = array('Js');
2) Now Declare js variable in ctp file
Like that way :
$state = 'rajasthan';
$this->Js->set('state_name',$state);
echo $this->Js->writeBuffer(array('onDomReady' => false));
3) Now Use this js vairable "state_name" in js file
Like that way :
console.log(window.app.state_name);
var state = window.app.state_name;

Using oninput function with php?

As far as I've seen, the oninput funciton in HTML is always used with Javascript. Is it possible to add PHP into it?
<input name="boxNo" type="number" value="1" oninput="<?php $intro = $intro . "boxNo.value"?>"/>
If it is possible, how should I structure my code?
Of course you can't call php directly from html as shown in your example.
But you can use AJAX to do it, using JS, jQuery and PHP script placed on your server.
For example:
JavaScript:
$('input[name=boxNo]').input(function(){
var inputObject = $(this);
var value = inputObject.val();
$.post('/yourfileOnServer.php', {value: value}, function(data){
//in the variable data you've already got your info from the php
inputObject.val(data); //inserting data to the value of your input
});
});
PHP:
if(!isset($_POST['value'] || empty($_POST['value'])){
exit; //Avoiding security problems
}
$value = $_POST['value']; //In this variable you store your value, entered to the input
// DO something with this value
echo $value; //and print it (return to the JS)
Good luck!

Categories