var attribute echoed with php and not submitted from form - php

Using this
`$(function(){$(".signaler").click(function(){var element=$(this);var I = element.attr("id");var page = $('#page').attr('value');var info = "id="+I+"& page="+ page;$("#signaler"+I).hide();$("#load"+I).html('<img class="think" src="load.gif" >');$.ajax({type:"POST",url:"signaler.php",data:info,success:function(){$("#load"+I).empty();$("#ok"+I).fadeIn(200).show();}});return false;});});`
but have a form with hidden inputs only so i can echo current user info into it, was wondering if I could put it straight into jquery? Working fine though.
With a form you would use the following
var page=$('#page').attr('value');
I would like to set the id with php echoing user name/id..
Something like var id=$('<?php echo $user/$id... ?>');
If someone could point out the right jquery syntax, would be very greatful!

var id = $(<?= $_POST["whatever_it_was"] ?>)

pretty much what you used as an example...
<?php echo $user . '/' . $id ?>
As long as the file in question is being parsed as php by the server that is...

Firstly you should get the value of a form input using the val() method:
$('input#id').val();
Then on the PHP side if you POST to the page using AJAX then do:
'var id=$('<?php echo $_POST['user'] . '/' . $_POST['id'] ?>')';

What you have is essentially a string you wish to use for somewhere in you jQuery. Well in that case what you have is essentially correct. If in your PHP file you do (notice the quotation marks:
var id = "<?php echo $yourId ?>";
You can then use that variable (which holds your PHP string) normally. The following would for example select the element with the id in the variable id:
$('#' + id)

Related

php how to handle hyperlink like a POST instead of GET?

I will have a query that return a set of results, and these results will be in hyperlink form as shown below:
echo "<td><a href='abc.php?cif=" . $row['cif'] . "'>{$row['cif']}</td>";
Now user get to click on this hyperlink and get routed to abc.php?cif=$cif..
My question is, is it possible to only show abc.php to user, just like a POST method, and $cif remains available at abc.php?
As #Flosculus said above, the "best" solution to simulate a post request is doing something like proposed here: JavaScript post request like a form submit
However, despite it's surely a reliable solution, I'm wondering you just don't use sessions instead, something like:
From the page where you set the cif variable:
session_start();
$_SESSION['cif'] = $row['cif'];
In abc.php:
session_start();
if (isset($_SESSION['cif'])) {
// Do what you need
}
EDIT::
Another (possible) solution is setting an hidden input and silently submit a form when you click on an anchor, like this:
From your example, instead of:
echo "<td><a href='abc.php?cif=" . $row['cif'] . "'>{$row['cif']}</td>";
You do this:
When you print all the entries, please add this first (from PHP):
<?php
echo <<<HEADER
<form action="abc.php" method="post" id="submitAble">
<input type="hidden" name="cif" id="cif" value="{$row['cif']}">
<table>
HEADER;
// Get data from your query.. Here is an example:
while ($row = mysli_fetch_assoc($query)) {
echo <<<ENTRY
<tr>
<td>{$row['cif']}</td>
</tr>
ENTRY;
}
echo "</table> <!-- \table collapse --></form> <!-- \form collapse -->";
?>
Then, if you're using jQuery (thing that I'm recommending), simply add an event listener in javascript, like this:
$('.cifSetter').on('click', function(e) {
e.preventDefault();
$('#cif').val($(this).data('cif'));
$('#submitAble').submit();
});
If you don't have jQuery, use this instead:
var cifSetter = document.getElementsByClassName('cifSetter');
for (var i = 0; i < cifSetter.length; i++) {
cifSetter[i].addEventListener('click', function(e) {
e.preventDefault();
var cif = document.getElementById('cif');
cif.value = this.dataset.cif;
document.getElementById('submitAble').submit();
});
}
In both ways, whenever an anchor gets clicked, it will prevent its standard behavior (redirecting) and will instead set the value of an hidden field to the value of the CURRENT "cif" and submit the form with the desired value.
To retrieve the desired value from abc.php, just do this:
$cif = $_POST['cif'];
However, keep in mind that the hidden field is editable by the client (most persons won't be able to edit it, though), therefore you should also sanitize your data when you retrieve it.
Sessions could do it but I'd recommend to just use $_POST. I dont get why you wouldn't want to use POST.

How to reach php $_SESSION array in javascript?

I am trying to build some javascript function and I need to check if the users are logged in or not. When a user log in to my site I set a variable in session array named is_logged. I want to reach that variable in javascript is it possible???
I tried some ways but did not work like following:
var session = "<?php print_r $_SESSION['is_logged']; ?>";
alert(session);
and:
var session = '<?php echo json_encode($_SESSION['is_logged']) ?>';
alert(session);
It is either show a text or never alert at all
Just echo it:
var session = <?php echo $_SESSION['is_logged']?'true':'false'; ?>;
alert(session);
You need tertiary operator, as false is echoed as empty string so it would lead to var session = ; which is a JS syntax error.
If you want to reach all elements of $_SESSION in JavaScript you may use json_encode,
<?php
session_start();
$_SESSION["x"]="y";
?>
<script>
var session = eval('(<?php echo json_encode($_SESSION)?>)');
console.log(session);
//you may access session variable "x" as follows
alert(session.x);
</script>
But note that, exporting all $_SESSION variable to client is not safe at all.
Try the following code:
var session = "<?php echo $_SESSION['is_logged'] ?>";
In a js file you cant get the value of a php variable or php code doesnt works on a js file because php code will works in a .php extension file.
So one method is to set the session value as a hidden element value and in your js file get the value of the hidden element.
In the html:
<input type="hidden" id="sess_var" value="<?php echo $_SESSION['is_logged']; ?>"/>
In your js:
var session = document.getElementById('sess_var').value;
alert(session);
You can do things like this
Just insert the $_SESSION['is_logged'] in a hidden field like
<input type = "hidden" value = "<?php echo $_SESSION['is_logged']; ?>" id = "is_logged" />
Then you can access that in your jquery like this
var is_logged = jQuery.trim($('#is_logged').val());
//then do validation here
var get_session=<?php echo $_SESSION['is_login']
alert(get_session);
?>
## *Just try this * ##

How to pass variable from PHP to JS, perform math on the variable then output to an on page element [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
how to access PHP variables from within JavaScript?
I am trying to pass a variable from mySQL to PHP then to JavaScript to perform some math on it then have the result displayed on page in a specific area (in a <p> element with a specific ID assigned to it). Is this possible or is there an easier solution?
Thanks!
I already know how to get the variable from MySQL to PHP just having trouble on what to do after that.
Here is my updated code after reading responses. Still not working but I am sure I'm doing something wrong!
<p id="p_id"><?php echo $price; ?></p>
<input type="radio" group="radio_group" value="Reduce 10%" onclick="radio_click();" />
<script type="text/javascript">
var price = <?php echo $price; ?>;
function radio_click() {
var target = document.GetElementById('p_id');
var final_number; // this will be variable your store the final number in
final_number = price * .9;
target.innerHTML = final_number;
}
</script>
In short, you have to pass the variable to the <script> tag as a string in a JavaScript friendly format (quotes and stuff).
<?php
$variable = 5;
$javaScriptAccessible = '
<script type="text/javascript">
var javaScriptAccessible = "'. $variable . '";
</script>
';
echo $javaScriptAccesible;
Also, you could JSON it:
<?php
$variable = 5;
$javaScriptAccessible = '
<script type="text/javascript">
var javaScriptAccessible = '. json_encode($variable) .';
</script>
';
echo $javaScriptAccessible;
With JSON, the quotes would be appended automatically.
Here you can see both in action: http://codepad.viper-7.com/Jyfw31
Update:
Here are more refined and, I think, better to understand examples: http://codepad.viper-7.com/1cloyB
Only thing you have to do, is use it on your radio buttons / elements.
I'd strongly suggest going with JSON, because it actually stands for JavaScript Object Notation, it has libraries in, probably, every single programming language on planet, and is specifically designed to pass JS data from one environment to other.
http://php.net/manual/en/function.json-encode.php here you can see multiple options you're able to pass in order to render it differently.
Just output the variable from PHP into a <script> item. Then set the innerHTML property of your <p> based on your calculation. You can put this into a function and call it from your radio button's onclick.
<p id="p_id"><!-- Your value will be inserted here --></p>
<input type="radio" group="radio_group" value="some_value" onclick="radio_click();" />
<script type="text/javascript">
var your_number = <?php echo $php_number; ?>;
function radio_click() {
var target = document.GetElementById('p_id');
var final_number; // this will be variable your store the final number in
// do your math here using your_number variable
target.innerHTML = final_number;
}
</script>
To pass the data from PHP to JavaScript, just echo it.
For example, say you want to display the data in a message box:
$data="something";
echo "<script>";
// Do the maths
echo 'var = ' . $data . ' + 1';
echo 'document.write("<p id=\"someID\">" + var + "</p>");' // PHP code writing Javascript code to write HTML code. Wow.
echo "</script>";
If you want to display the data on click of a radio button:
<input type="radio" onClick="someFunction();">
<?php
echo "<script>function someFunction() {";
// Do the maths
echo 'var = ' . $data . ' + 1';
echo 'document.write("<p id=\"someID\">" + var + "</p>");' // PHP code writing Javascript code to write HTML code. Wow.
echo "}</script>";
?>
*Edit: If the <p> tag already exists, use document.GetElementById(\"someID\").innerHTML = var; instead of document.write("<p id=\"someID\">" + var + "</p>");.

How to trigger href event on a jquery slider on a php template

Hello to all jQuery enthusiasts and experts!!
I currently use on a project this jquery slider http://spaceforaname.com/galleryview/.
The slider itself doesnt support on mouseover pause and on href click redirect.
The first part was easy to implement
dom.gv_panelWrap.bind('mouseover.galleryview',function(){
self.stopSlideshow();
}).bind('mouseout.galleryview',function(){
self.startSlideshow();
});
As for the links part i tried to do something like this
dom.gv_panelWrap.bind('click.galleryview',function(){
var href="page.php?lang=<#language#>&action=show&objectid=<#objectid#>";
window.location.href = href;
});
As you may understand this doesnt work since the link has php parametrs in it.
Of course when i change the href variable to page.php?lang=en&action=show&objectid=1 i get the page with the infromation about object n.1.
Any ideas of how i could pass the actual href through jQuery?
Thanks in advance for reading this!!!
dom.gv_panelWrap.bind('click.galleryview',
function(){
var href = 'page.php?lang=' + <?php echo "'" . $language . "'"; ?> + '&action=show&objectid=' + <?php echo "'" . $objectid . "'"; ?>;
window.location.href = href;
});
Change the language and objectid variables if needed
I'm not sure of what is what you truly want.
I don't know where are you going to get the id.
From the image thats being shown?
This is the src of the img that's been displaying.
$(".gv_panel img").attr("src")
I guess you can compare with your list of objects which is this image from.

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