This question already has answers here:
Call php function from JavaScript
(5 answers)
Closed 7 years ago.
I'm trying to use my PHP function in JavaScript like this:
PHP code:
function checkevents($date){
$ev = new CalendarModelEventss();
$wh = "`event_date` = '".$date."'";
$all = $ev->getAllEvents('event_date', $wh);
if($all == $date){
//echo 'event is available'.$all;
return true;
} else {
return false;
//echo 'event is NOT available' .'--'. $all;
}
}
and JavaScript code:
var yyyy = date.getLocalFullYear(true, this.dateType);
var mm = date.getLocalMonth(true,this.dateType);
var dd = iday;
var ddddd = yyyy+'/'+mm+'/'+dd;
if(<?php checkevents( ?>ddddd<?php ) ?>){
cell.className += " eventsss ";
}
but it doesn't work, and I have PHP error (syntax error, unexpected ';', expecting ')' in ...).
As the previous speaker said, it's impossible to directly call php functions from javascript. PHP could be used to output javascript though.
In your case you would need to send an ajax-request from the client side (with javascript) that executes the php code (on the server side), fetches the output and puts it into your if-statement.
If you do not know alot about javascript/AJAX you could take a look at jQuery or another similar framework.
Javascript is parsed on client side and PHP on Server side.
Without AJAX this is impossible.
Example with JQuery:
PHP:
...
echo "true";//or something else that indicates the success
} else {
echo "false";//or something else that indicates the failure
}
...
Javascript:
$.ajax({
url: "URL TO YOU PHP SCRIPT",
cache: false
}).done(function( html ) {
if(html.match(/true/g)){
cell.className += " eventsss ";
}
});
You cannot directly call php function using javascript directly as both of them are on different sides.So what you do is make an AJAX call with certain parameters and after that call that php function directly from that php file with the parameters to be validated.
And Send back the output back to javascript by echoing the output and do whatever with it on javascript.
Related
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.
This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 9 years ago.
I want to set session inside the javascript. But all the time this function return false value. Please tell me the error of this code.
<script>
function myFunction(){
var r=confirm("Would you like to add another item ?");
if (r==true) {
alert('ok');
var varname = '<?php echo $_SESSION["redirect"]=1; ?>';
}
if(r==false) {
alert('bad');
var varname = '<?php echo $_SESSION["redirect"]=2; ?>';
}
}
</script>
You can't evaluate PHP on the client. Do an AJAX request to the server setting the session variable instead.
Javascript runs on the client side, so you'll need to perform an AJAX call to a server side script that will change the sessions value.
Something in the lines of:
function changeSession()
{
$.ajax({
url: /change_session.php?value=1&key=redirect,
dataType:"html"
});
}
And in change_session.php:
<?php $_SESSION[$_REQUEST['key']]=$_REQUEST['value'] ?>
After searching for internet and even here for 5 hours, i am still stuck at getting value of a local variable in a function and sending it to PHP.
I have tried different syntaxes but none of them seems to be working. This code below, takes an input field from PHP and assign some value to it (having problem send this value back to PHP)
$(document).ready(function() {
//select all the a tag with name equal to modal
$('form[name=modal]').click(function(e) {
//Cancel the link behavior
e.preventDefault();
//Dont go until value is not 7
console.log('i am Now waiting for input');
var s = $('#serial').val();
console.log('searching for ' + s);
while(s.length != 7) return;
//When code value reaches 7
var code = $('#serial').val();
console.log('Value is reached ' + s);
});
});
In PHP
echo "<script>document.write(code);</script>";
Uncaught ReferenceError: code is not defined
please help
You should do somthing like this in javascript when $('#serial') is your input field.
$.ajax({'url':'your_php_file_url', 'type':'post', 'data':{'str':$('#serial').val()}}).done(function(data){
console.log(data.code);
});
And in php
$output = Array('code' => 'not set');
if (isset($_POST['str']))
{
//do your search and assigne value to output
$output['code'] = 'some value';
}
echo json_encode($output);
In short - you send your search string via ajax to php and make your searches. Then you echo it out as json, then ajax will read it as an object and you can use those values you want.
ok, i have almost tested every possible solution but all in vain... so i am off and try to use some normal method rather than javascript. Thanks for all your answers guys.
I have a little problem. I want to pass two variables from PHP to $.ajax success function
I have this code written in JS:
$.ajax({
type:"POST",
url:path,
data: "value="+info,
success:function(data,data1)
{
if(data==1)
{
$(id).css("backgroundColor","green");
$(id).attr("readonly","readonly");
$(image).attr("src",data1);
}
else
{
$(id).css("backgroundColor","red");
}
}
});
And my PHP code is :
if(isset($_POST['value']) and !empty($_POST['value']))
{
$result=0;
$image="src/photo1.jpg";
$value=trim($_POST['value']);
if($value=="Abracadabra" or strcmp($value,"Abracadabra")==0)
{
$result=1;
$image="src/abracadabra.jpg";
}
else
{
$result=0;
$image="src/photo1.jpg";
}
echo $result;
echo $image;
}
There, I want to "echo" two variables simultaneously to pass to $.ajax success function.
It is possible ? I don't refer to JSON, I refer only PHP with POST method.
Thank you
the response from php code will be something like:
0src/photo1.jpg
and you will have to parse it with the javascript (probably with regex or substring)
success:function(data,data1) {
var result = data.substring(0,1);
var image = data.substring(1);
// ... your code
}
keep in mind that it could cause you trouble if the $result variable is more than one character long :)
have PHP echo a string like "value1|value2|etc" (or whatever other character(-sequence) is unlikely to wind up in the actual data)
then on the javascript side do a string.split('|') to break the returned string up into a neat little array. you could even do key1:value1|key2:value2
and then use the solution presented here to split the key:value pairs up into an object.
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 ..