Php variable to JavaScript - php

How to add the value of php variabele to jquery variable and adds them,i have a form that will take a value and post to second page where second page contains a div panel where the form checkboxes values are adding and subtracting,basically i want to add the submitted value from page1 to page2.Here is the code.I have 3 form values which will be redirected one by one.Whenever user submits the respective button
if($_POST['submit'])
{
$beg=$_POST['basic'];
}
function refreshPrices() {
var currentTotalValue = 0;
var beg=?????
$("#results div").each(function() {
if (!isNaN(parseInt($(this).find("span").text().substring(1)))) {
currentTotalValue += parseInt($(this).find("span").text().substring(1));
}
});
$("#totalValue").text("$" + currentTotalValue)
}

var beg=<?php echo $beg; ?>

Try this:
var beg = '<?php echo $beg ;?>';
if you want to add to the total value you can do this:
currentTotalValue = currentTotalValue + parseInt(beg);

its better to do it this way :
var js_var = '<?=json_encode($php_var);?>';
This way you will be able to transfer any type of data to js (arrays, objects, strings, etc.) and access it easily like this:
js_var['element']

var beg = '<?php echo $beg ;?>';
But this can be only one once during the load of the page. After that we cant assign a server side script to js.

Retrieve value by input class or id like dat
var beg = $("#basic").val();

Related

Conflicting jquery functions

I have built two functions which work separately (when the other is deleted) but do not work together. The overall aim is that when a person selects the number of results they want to see per page, this then reloads the page, and the value is put in the url and then retrieved using get in php; and then on the new page the selected value in the drop down menu to is the value what triggered the reload.
Jquery
$(document).ready(function(){
//the first section takes the value from the php script and then selects the option if it's not null - this works fine on it's own
var data = "<?php echo $rp;?>";
if (data){
$("#bo2 option[value="+data+"]").attr('selected', 'selected');
}
//this too works fine on it's own but not with the above
$('#bo2').change(function(){
var opt = $(this).val();
var url = "sales.php?results=";
var newurl = url + opt;
window.location.replace(newurl);
});
});
Together, the first works fine, in that it re-selects the right value if, say, I put ?results=50 after sales.php but then the jQuery to trigger the reload doesn't work. What am I doing wrong?
Just to clarify. The first page is called "sales.php" and the drop down menu has the currently selected value of "10", with 25 and 50 being other options. When I click on another number the jquery doesn't work. However should I type into the url the ending "?result=50", for example, it does work; and the drop down menu now shows 50; when i click on ten, the url updates, and the drop down shows ten also; the problem then is they seem to conflict only at the start, as it were.
It would seem the problem may concern how jquery deals with php. Take for example the following first example which works, and then the second which doesn't:
1)
$(document).ready(function(){
$('#bo2').change(function(){
var opt = $(this).val();
var url = "sales.php?results=";
var newurl = url + opt;
window.location.replace(newurl);
});
});
2) This change function however will not trigger a reload of the page because of the inclusion of the php defined jquery variable.
$(document).ready(function(){
var data = "<?php echo $rp;?>";
$('#bo2').change(function(){
var opt = $(this).val();
var url = "sales.php?results=";
var newurl = url + opt;
window.location.replace(newurl);
});
});
This achieves what I want (I don't know if the php posed a problem or not). The function is from here - Get url parameter jquery Or How to Get Query String Values In js.
Also, I'm surprised nobody more experienced than me didn't point out what also seems to have made a difference; the "first" function in the original post needs to in fact be second.
So the below will reload a new page, when a user clicks on an option in a select menu with pre-defined options for how many results they want to see per page; this value will then show in the url, and, importantly, the current select value of the select menu will now be this value also; this is important so that if the user goes back to the original number of views, the change() function works still.
$(document).ready(function(){
var getUrlParameter = function getUrlParameter(sParam) {
var sPageURL = decodeURIComponent(window.location.search.substring(1)),
sURLVariables = sPageURL.split('&'),
sParameterName,
i;
for (i = 0; i < sURLVariables.length; i++) {
sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] === sParam) {
return sParameterName[1] === undefined ? true : sParameterName[1];
}
}
};
var data = getUrlParameter('results');
$('#bo2').change(function(){
var opt = $(this).val();
var url = "sales.php?results=";
var newurl = url + opt;
window.location.replace(newurl);
});
if (data)
{
$("#bo2 option[value="+data+"]").attr('selected', 'selected');
}
});

Targeting text value from link for multiple links in one output

I can't find/think of a way to solve this problem.
I have a list of links outputted by a php script and I need to get the text value from the item (link) that's been clicked.
Here is the php part that outputs data:
$query = mysql_query("SELECT NAME FROM ccm WHERE NAME LIKE '$value%'");
while( $run = mysql_fetch_array($query)){
$name = $run['NAME'];
echo '<a id="rez_link" onClick="klik();">'.$name.'</a>';
}
And here are some of my attempts to fetch the .text() from the link that's been clicked:
var value = $('a#rez_link').text(); //this one targets every text if there are multiple search result from the query
var value = jQuery(this).find("a").text(); //this one returns nothing
So how do I do it?
Maybe I should modify the php script so that it outputs new links with id=""+i and then target them like that in jQuery or something like that.
Is there a simple way to do this?
You can't have more anchor tags with same id
echo '<a id="rez_link" onClick="klik();">'.$name.'</a>';
it's better to use class instead
echo '<a class="rez_link">'.$name.'</a>';
$(function() {
$(".rez_link").on("click",function()
{
var text = $(this).text();
alert(text);
}
});
$(function() {
$('.rez_link').bind('click', function(e) {
e.preventDefault();
var linkText = $(this).text();
$('#show').text(linkText);
});
});
It's this what you try to do ?

Keep value of input which is generated by Javascript after submitting

I have this code to append the input panel #yearPanel after the select box #before changed.
$("#before").change(function() {
var selected = $('#before option:selected').text();
if(selected == bankShowYear) {
$(yearPanel).insertAfter("#yearAnchor");
var value = $("#yearHiden").val();
$("#year").val(value);
} else {
$("#yearPanel").remove();
}
});
I want to keep the input value of #year in #yearPanel after submitting by PHP. I tried to store the value in #yearHidden and assign it to #year after all the input are rendered but it doesn't work.
How to keep the input value?
Try this:
$("#before").change(function() {
var selected = $('#before option:selected').text();
if(selected == bankShowYear) {
$(yearPanel).insertAfter("#yearAnchor");
var value = $("#yearHiden").val();
$("#year").val(value).attr('name', 'year');
} else {
$("#yearPanel").remove();
}
});
Then, on your next page:
$("#year").value(<?php echo $_REQUEST['year']?>);
OR
<input id="year" value="<?php echo $_REQUEST['year']?>" />
your input needs a name attribute in order for it to be passed along to your serverside php script
You need to pass the value to PHP via a hidden field and PHP will have to render it on the next page. In other words the value needs to go from the client-side to the server-side and back to the client-side.

How to send Javascript/jQuery array over URL paramter to PHP?

Here's my script, this works fine... send_array_to_other_page.html
$(function(){
//DECLARE ARRAY
var arr = new Array();
var i = 0;
$('#form').submit(function(e){
e.preventDefault();
var value = $('#box').val();
var index = arr.length;
var list = '';
//ADD VALUE TO ARRAY
arr[index] = value;
//OUTPUT VALUES IN ARRAY
for (var index in arr){
list+=index+': '+arr[index]+'<br/>';
$('#arrLength').html(arr.length);
}
//DISPLAY ARRAY
$('#display').html(list);
$('#form').get(0).reset(); //RESET FORM
});
$('#submit').click(function(){
window.location = 'send_array_to_other_page_2.php?list='+arr;
});
});
This doesn't. It outputs Array content lost. Id also like to point out the the url of this page is send_array_to_other_page_2.php. Its missing the ?list=
<?php
$arr = $_GET['list'];
echo 'The contents of the array are still... <br/>';
if(isset($arr)){
print_r($arr);
} else {
echo 'Array content lost';
}
?>
$(function(){
//DECLARE ARRAY
arr = new Array();
var i = 0;
$('#form').submit(function(e){
e.preventDefault();
var value = $('#box').val();
var index = arr.length;
var list = '';
//ADD VALUE TO ARRAY
arr[index] = value;
//OUTPUT VALUES IN ARRAY
for (var index in arr){
list+=index+': '+arr[index]+'<br/>';
$('#arrLength').html(arr.length);
}
//DISPLAY ARRAY
$('#display').html(list);
$('#form').get(0).reset(); //RESET FORM
});
$('#submit').click(function(){
window.location = 'send_array_to_other_page_2.php?list='+arr;
});
});
Try without the var arr to make it global, I don't believe the sub functions are parsing it.
Don't sent 'long' data over a URL. Most browsers have a length limit and it's very easy to exceed that and end up with corrupted data. For 'big' data, use a POST, which is not limited.
To send the array itself, just do an AJAX request and let jquery encode the array into JSON. You then handle it in PHP with json_decode() and you'll end up with a native PHP array.
Edit: Updated the JavaScript on jsfiddle based on your comment. On "submit", the array is saved at the "#form" element using the .data() method. On "click" of the "#submit" button, that data is retrieved and the url is build up.
The click event does fire before the submit event (at least in my Firefox 7), so your array is empty when concatenated to the URL string.
I put together some JavaScript on jsfiddle that might help. You do not really need to bind to the click event of the submit-button, just do the "redirect" in the submit handler function. You are building your string list there anyways. So there would no confusion what fires first, the click or the form submit event.
As for the serialization of your array, I used jQuery's .each() function but there is nothing wrong doing it by hand (if done correctly).
I could also imagine that the form is actually posted and this is why you do not see the "?list" search part of the URL.
If you don't need a complete redirect, why don't you send the data using jQuery.get()?

jQuery get values from selected checkboxes

First problem is that I do not know how to get the values of SPECIFC checkboxes when they are checked.
I need a function that will get the value of the selected checkboxes by checkbox ID or Name.
This is the code I have so far:
$("#doStatus").click(function(){
var Tuitting = $('textarea#tuitting').val();
var F = $('input#Fb').val(); //checkboxes with ID Fb
var T = $('input#Tw').val(); //checkboxes with ID Tw
$.get("<?echo $site['url'];?>modules/yobilab/tuitting_core/classes/doStatusBox.php", { tuitting: Tuitting, f: F, t: T });
window.setTimeout('location.reload()', 1000);
return false;
});
Now the second problem is that both var F and var T may contain MORE than one values in an array..
Obviously when I use the ajax get functions the multiple values for both var F and var T are not
passed at all. What is the problem..?
How do I pass multiple values in an array that will be then runed by the foreach on the doStatusBox.php page?
Please help me.
$("#doStatus").click(function() {
var Tuitting = $('textarea#tuitting').val();
var F = $('input[name="fb"] :selected').val();
//You can give the name of checkbox and get the values of selected checkbox
return false;
});
I'm answering based on an assumption: you need checked checkboxes to pass them via GET method to your doStatusBox.php script.
However, why would you go trough the trouble of finding which checkbox is checked if you can simply use the serialize() method and let jQuery do the job for you?
$("#doStatus").click(function()
{
var serialized = $("#someFormHere").serialize()
// or, if you have your form elements within a div or another element
var serialized = $("#elementID :input").serialize();
$.get("<?echo $site['url'];?>modules/yobilab/tuitting_core/classes/doStatusBox.php", serialized);
window.setTimeout('location.reload()', 1000);
return false;
});
However, is "#doStatus" a submit button submitting the form or something else? If it submits the form, bind the submit event to the form, not click event to the button submitting it.

Categories