if u see this function <?= input_txt('+order_id+') ?>
have jquery variable but jquery send error
function order_status(type, order_id) {
var value = type.value;
var info = document.getElementById("cancel_id_" + order_id).value;
document.getElementById("my_cancel_info").innerHTML = "Determine the reason for cancellation of the order number " + info;
document.getElementById("cancelled_info").innerHTML = '<?= input_txt('+order_id+') ?>';
if (value == 2) {
$('#order_cancelled').modal('show');
}
}
You first need to understand the order in which PHP and javascript execute. PHP is rendered server-side, while javascript is rendered client-side. I suggest that you look into http://api.jquery.com/jquery.ajax/ where you can pass your javascript variable to a PHP script via AJAX and then return your result.
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.
design.php file:
<script>
$(".colr_sldr li img").click(function(){
var src = $(this).attr('src');
var value=src.substring(src.lastIndexOf('/')+1);
<?php $var = "<script>document.write('" + value + "')</script>";?>
});
</script>
and use this variable in index.php file:
<?php
include('design.php');
echo $var;
?>
here while i am printing this variable it is getting zero can any one help
you can't take var like this in php..
$var = "<script>document.write('" + value + "')</script>";?>
because php is server side language ..
and javascript is client side.
For this you have to use ajax ,get and post methods
the only solution I may know is using jquery on client side an sending your variable via ajax :
script.js
$('document).ready(function(){
var myVar="Hello";
$.post('design.php',myVar);
});
and in design.php you have acces to your variable with $_POST
design.php
<?php
$myVar = $_POST['myVar'];
echo $myVar;?>
please check http://api.jquery.com/jQuery.ajax/ for more details
or http://api.jquery.com/jQuery.post/
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.
Is it possible in the line that begins with $sql = to use the variables that were defined earlier in javascript?
var southWestLat = map.getBounds().getSouthWest().lat();
var southWestLng = map.getBounds().getSouthWest().lng();
var northEastLat = map.getBounds().getNorthEast().lat();
var northEastLng = map.getBounds().getNorthEast().lng();
var coordinatesMap =
<?php
global $wpdb;
$sql = "SELECT user_id, lat, lng FROM coordinates WHERE lat>southWestLat and lat<northEastLat and lng>southWestLng and lng<northEastLng";
$rows = $wpdb->get_results($sql, OBJECT_K);
...
?>;
Since javascript is a client side language if is not possible to directly use them. You can however use AJAX to transfer values of those JS variables to the server. Execute your sql statement and return back the results in some JSON object for example.
HTH :)
Oki so say we have the following in JS
var myvar1 = "HELLO WORLD 1";
var myvar2 = "HELLO WORLD 2";
Now we want to send myvar to the server via AJAX. Here is how.
$.ajax({
type: "POST",
url: "some.php",
data: ({'action' : 'action1' , 'myvar1' : myvar1 , 'myvar2' : myvar2 }),
success: function(msg){
alert( "Data Saved: " + msg );
}
});
The url must be some script that will handle the ajax request. What will be echoed by that script will end up in the msg variable of the success callback.
AJAX Handler
To do this you will need to send an extra parameter with each AJAX request. If you look at the above example I added the action parameter. This will allow us to identify which action should be executed by the AJAX Hander.
ajaxhandler.php
switch($_POST["action"]) {
case "action1":
action1($_POST["myvar1"]);
break;
case "action2":
action2($_POST["myvar2"]);
break;
}
function action1($myvar1){
do your action logic here
}
function action2($myvar2){
do your action logic here
}
PHP runs on the server while JavaScript runs in the client's browser.
So you need to use AJAX to do this - have a look at jQuery's AJAX functions.
no, it's absolutely different things. javascript executes on client side, php code executes on server side. your objective is possible only if you pass your js values to php script via HTTP request
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;