How to send php variable to AJAX - php

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']);?>

Related

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>

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 do I use PHP variables as values for the <script> tag when rendering jQuery code in my CakePHP view?

I m new to CakePhp and JQuery.
I am getting an error in using the cakephp code inside my JQuery.
My code
<script type="text/javascript">
$(document).ready(function(){
var attributeid;var fieldname;
$("#"+<?=$r['Attribute']['id'];?>).change(function () {
fieldname=<?=$r['Attribute']['label'];?>;
alert(fieldname);//this show me that undefined
attributeid=<?=$r['Attribute']['id'];?>;
alert(attributeid);//But this works
});//attribute change
});//ready function
if I echoed ($r['Attribute']['label'];) this value is coming inside my <?php ?>.
But not inside my JQuery.
Note :
attributeid=<?=$r['Attribute']['id'];?>;
alert(attributeid);//But this works
Error:
Name is not defined
fieldname=name;
alert(fieldname);
You are not thinking about how this is translating over once the variables are echoed.
If you have a variable $x with the contents "test", doing this:
var x = <?=$myvar?>;
Will result in:
var x = test;
This is not valid (unless test is a variable) because you need quotations around it to make it a string:
var x = "<?=$myvar?>";
Which then results in the valid:
var x = "test";
The reason it works with the other variable is because you are echoing an ID, which is an integer:
var x = <?=$myid?>;
Would translate to:
var x = 5;
Which is perfectly valid.
All this being said, you should put all the stuff you want to send over to Javascript in an array and call json_encode on it to easily and safely print the values over. Without it, you have to worry above about escaping quotes in the string and such.

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