jquery php variable - php

I have a variable hard coded in to my html inside script tags like this(it calls meta information from a wordpress post and I've checked that the meta is being pulled)
<script type="text/javascript">
var jg_product_price = "<?php echo get_post_meta($post->ID , 'productprice' , true); ?>";
</script>
my jquery code reads;
.prepend('<span>'+jg_product_price+'</span>');
the html output is:
<span></span>
i.e an empty span
Is it something to do with the "'" in the var jg_product_price? Many thanks

It looks like jg_product_price is empty. Have a look at
alert(jg_product_price);
or view the source code of the page. Make sure get_post_meta($post->ID , 'productprice' , true); is not empty.

Open the resulting page in Firebug (or whatever) and check what, if anything, the php actually outputs into the source.
Try hard coding the value: var jg_product_price = "test";.
Try hard coding the value in php: var jg_product_price = "<?php echo "test2"; ?>".

Related

How to send php variable to AJAX

I need to retrieve session variable data inside an ajax call. Here is my try.
$('#update').click(function(){
var number = $('#num').val();
var curuser = <?php echo $_SESSION['userName'];?>
if( number != '' && number.length==9 )
{
$.ajax({
data:{number:number},
success:function(data){
$('#number_add').val(number);
$('#new_data_Modal').modal('show');
}
});
}
});
Seems like var curuser = <?php echo $_SESSION['userName'];?> prevents opening my model(new_data_Modal) after button(update) click. When I remove that line it works fine(Model is opening as previous).
But alert("<?php echo $_SESSION['userName'];?>") is working and it prints the session variable as well.
Can someone show me where I made the wrong?
If this is a string you need to wrap the variable in quotes:
var curuser = '<?php echo $_SESSION['userName'];?>';
otherwise, when PHP code is executed you will get a syntax error:
var curuser = John
You can check the source code of the generate HTML to see what is the output.
NOTE: Your javascript code needs to be a PHP file with a PHP extension, it can be your HTML or JavaScript file. You can use JS file as PHP script in script tag <script src="code.php"></script>
If you're outputting JavaScript values from your php script you should use json_encode, that way any data type will work and there is no risk of your code breaking if you data has a quote or new line in it.
var curuser = <?php echo json_encode($_SESSION['userName']);?>

Storing php get value inside ajax data

I have like:
<script type="text/javascript">
$(document).ready(function() {
var n = $('<?php echo $_GET['name'];?>').val();
var e = $('<?php echo $_GET['email'];?>').val();
$.ajax({
method: "POST",
url: "file.php",
data: {name: n, email: e},
success: function(status) {
$('#result').append(status);
}
});
});
</script>
Why does it store empty values inside e and n?
And inside file.php when I echo em they are empty.
But here when I echo $_GET['name'] or email it show real values?
Thanks
you have a mistake in your code. you have to store that variable like below.
var n = '<?php echo $_GET['name'];?>';
var e = '<?php echo $_GET['email'];?>';
Why does it store empty values inside e and n?
My guess is that jQuery isn't finding the matching elements you're looking for. For example, if I go to your page with this:
page.php?name=David
Then that code will emit this:
var n = $('David').val();
That jQuery selector would be looking for this:
<David />
Which probably doesn't exist on that page. (With an email address it would be even stranger.)
If you want to store the values themselves in a JavaScript variable, you don't need any jQuery for that:
var n = '<?php echo $_GET['name'];?>';
If, on the other hand, the $_GET['name'] value is supposed to be the name of the HTML input and you want to use jQuery to find that input, it would be more like this:
var n = $('input[name=<?php echo $_GET['name'];?>]').val();
It's not entirely clear if that's what you're looking to do, though. Depends on what you expect $_GET['name'] to contain.
You can confirm all of this using the debugging tools in your browser. (Usually opened by pressing F12.) Examine the page source client-side (after the PHP code has been processed) to see what your JavaScript is actually doing, look at the jQuery selector(s) you're trying to build, debug the JavaScript to see if the target elements are found, etc.

Issue with displaying PHP code in HTML

I am using a slider in one HTML page and sending its value to the next page using a hidden textbox like this :
Page1.html
<script type="text/javascript">
var flowPercent = document.querySelector('#flow');
function sliderFunc()
{
var f = function(){
var x = flowPercent.value;
window.open('Page3.html?val=x','_parent');
};
f();
};
</script>
And then I would like to display this in the next HTML page using PHP echo like this :
<?php
$val=$_POST['val'];
echo "Value is $val";
?>
But neither the value nor "Hello" is being displayed. Why is this ?
How do I fix this ?
Thanks !
If your PHP-Code is contained in Page3.html, that page should have a .php-extension in order to execute the code. And also you are not posting anything, so $_POST will be useless...
Try window.opener.getElementById('textbox') instead to query the value...
Just change your page3.html to page3.php because you can't use php code in html file but you can use html code in php

I want to use session variable value in javascript

Here I want to use session variable's value in javascript function. I tried
var varname = '<?php echo $_SESSION["variable_name"]; ?>';
But it doesn't pass the value it shows the string
so how can i use session variable of php inside the javascript.
Actually I want to check captcha code in java script side.
Here i already make contactus.php file where I generat captcha value from rand function. Then i store this value in session variable. Here I already made validation.js file to validate contact us form fields so in same file i want to validate captha so for that I has been trying below code but its not working .
var cap = document.frm.captcha.value;
var ca = '<?= addslashes($_SESSION["code"]); ?>';
alert (cap); //ITs shows my entered value perfectly
alert (ca); //but it doesn't show generated captcha value. it simply print '<?= addslashes($_SESSION["code"]); ?>'//
if(cap!=ca)
{
alert("Insert correct captcha code");
document.frm.captcha.focus();
return false;
}
I checked session variable value it works fine on php page but dosen;t work on javascript page.
<script type="text/javascript">
<?php echo "var variable = '". $_SESSION['variable']."';" ?>;
</script>
The file which contains this code must be named .php and has to be a session_start(); at the beginning of the PHP-File.
Then this code should work.
There is several posibilities, why your code isn`t working.
There is an error in variable (Eg unescaped quote)
Code is outside of Javascript code.
Session is not started in the moment of getting variable
For fixing this 3 errors you need to use following code -
<?php session_start(); ?>
<script type="text/javascript">
var varname = '<?= addslashes($_SESSION['variable_name']); ?>';
</script>
If in your session variable is not a string or number you need to pack it to the JSON object. In this case you can just make following:
<?php session_start(); ?>
<script type="text/javascript">
var varname = <?= json_encode($_SESSION['variable_name']); ?>;
</script>
Last variant of code will make all types of variable are frendly to JS. Also string.
For example with json_encode from asd'd"sa string you will get "asd'd\"sa" string.
UPD:
If you use this file like JS file like follows:
<script type="text/javascript" src=".../path/to/file.php"></script>
for correct work you need to use following code.
<?php
session_start();
header('Content-Type: text/javascript');
?>
var varname = '<?= addslashes($_SESSION['variable_name']); ?>';
Try like this:
<script type="text/javascript">
var varname = <?php echo $_SESSION["variable_name"]; ?>;
</script>

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;

Categories