having problems passing javascript variable to php file in the url - php

I have this code right now :
$(document).ready(function() {
var ktitle = $('.hiddentwo').text();
$('div#tab2').load('morefour.php?title=ktitle');
});
but the php file doesn't seem to be getting this variable...am I doing something wrong?
I echo something in the php file and I see the text. Also when I echo the $ktitle in the php file I get 'kitle'...that should not be happening :p. This is a stupid question, but I just want to know how to store that variable in the url.

$('div#tab2').load( 'morefour.php?title=' + encodeURIComponent(ktitle) );

try using
$('div#tab2').load("morefour.php", {
title:ktitle
});
or
$('div#tab2').load('morefour.php?title='+ktitle);
UPDATE
In the first case, the data are passed to the script via POST, in the second via GET.

Because you're hardcoding the ?title to "ktitle". If you want to replace this with a variable, you need to concatenate the variable with 'morefour.php?title=' + ktitle.

Related

Access a PHP array element by using a JavaScript variable as index

The code looks like this:
PHP file
<?php
...
$arrayName = ['ArrayValue_0', ..., 'ArrayValue_n'];
...
php?>
JavaScript
$('.elementClass').each(function(index, id) {
$(id).html('<?php echo $arrayName[index - 1]?>');
});
But you can't just insert a JavaScript variable like that into php tags so index is never received.
I know this can be done via AJAX but is there any other way? Thanks in advance.
Additional info:
I've been told to do this in PHP so there's no posibility of switching the array to a JS file.
You can define arrayName variable in JS and initialize it with the value from the server:
var arrayName = <?php echo json_encode($arrayName); ?>;
$(".elementClass").each(function(index, id) {
$(id).html(arrayName[index-1]);
});
What you're trying to do will not work. For example this:
$(id).html('<?php echo $arrayName[index - 1]?>');
The above will never, ever work, because PHP is run on a server, not on your user's browser.
What you need to do is send the variable somehow to the server. You have a plethora of options:
Use a form and read a $_POST variable
Append it to a URL and read a $_GET variable
Use AJAX and asynchronously send that variable to the server
Return the whole array from PHP to your Javascript code
etc. etc.
Remember, PHP runs on the server, which renders the page, which then in turn is read by your browser where you run Javascript. You can't paste PHP code into the page and expect it to be parsed by PHP!
You need to get back to the server if you wish to get info from it (PhP runs on the server), so either you create a javascript variable on-the-fly when loading the page with the complete content of your PhP array , either you use ajax to get back to the server without refreshing the whole page.

assigning javascript variable to php session variable

I'm doing a online exam tool. I want to minimize the number of database requests. So I am requesting all the questions in the test at one go. After this I have to remember all the questions user has attempted and their answers. My plan is to save the answers in a php session variable like this
$('input[type=radio]').click(function()
{
var id = ($(this).parent().attr('id'));
id = id.slice(4);
$('#nav'+id).css('color','red');
<?php $_SESSION['ques['id']']= ?> $(this).val() <?php ;?>
});
In the above code the following lines are to change the color of attempted questions.
var id = ($(this).parent().attr('id'));
id = id.slice(4);
$('#nav'+id).css('color','red');
Here id is the id of the question. Problem is I'm getting the following error
Parse error: syntax error, unexpected ';' in /var/www/sites/onlinetest/test.php on line #x
Also I'm pretty sure the following is wrong
$_SESSION['ques['id']']
since id is the javascript variable here. Please help me. Also I appreciate if any other better solution than 'storing in the session variables' is posted
1) Your problem lies in the last line of click block. I'm not entirely sure what you're trying to do, but you have <?php ; ?> and the semicolon is causing your script to fail to parse. The first part
<?php $_SESSION['ques['id']']= ?>
doesn't do anything either. It looks like you're trying to assign a Javascript value $(this).val() to the PHP SESSION global, which you can't do. You'll need to make an AJAX call back to your server to update your session var.
2) Use double quotes when nesting arrays like so:
$_SESSION["$ques[id]"]
Hope this helps.
Just store the answers in JS, and send them to the server when last question is answered.
Here's a really basic example of storing to an array:
var answers=[];
$('input[type=radio]').click(function()
{
var id = ($(this).parent().attr('id'));
id = id.slice(4);
$('#nav'+id).css('color','red');
answers.push($(this).val());
});
Sending it serverside:
$.ajax({
type: 'POST',
data: {answers : answers},
url: '/path/myfile.php',
success: function(data) {},
error: function() {}
});
Catching it in PHP:
if (isset($_POST['answers'])) {
$answers = $_POST['answers'];
}else{
die('error');
}
This is the way I would do it, just show/hide the questions with javascript.
If you are refreshing the page for every question you could just store the answers in PHP on every new page load, should be pretty straight forward as long as you're not trying to use PHP code inside your JS file.
I think we never get any client side script variable to server side script language
Solution store in some hidden form variable then at the form submit time you can get in GET or POST variable
Thanks
The code seems will not work as you expected even though you clear the errors.So use the ajax in jquery
The problem with PHP is that it gets executed before the javascript so you can't just add php and try to assign a javascript variable into php varivable.
You will have to use ajax to solve your problem.
Do a ajax request and send all values trough GET. After this you can use all variables in your php file where you did the ajax request.
Iterate trough all variables and insert them into the Session

Javascript does not allow me to set variable with PHP?

I have done this several times before but am wondering if perhaps there is a conflict with my bitly class.
I use php to generate a bitly url from long ones. This is stored in a variable called
$url
I can echo the $url variable and know it works fine. However, when I try and place the into the following javascript function (which is called onclick event), the entire action fails.
function fbs_click() {
var uf="<?php echo $url; ?>";
var tf=document.title;
window.open('http://www.facebook.com/sharer.php?u='+encodeURIComponent(uf)+'&t='+encodeURIComponent(tf),'sharer','toolbar=0,status=0,width=626,height=436');
return false;
}
if I replace with an actual URL, i have no problems. Even if I replace with the word "blah", it works. Something about the php echo is throwing it for a loop.
The php echo renders this is source:
var uf=""http://bit.ly/rfEcJl\n"";
My guess is that doing this instead will solve your issue:
var uf = <?php echo json_encode($url); ?>;
Is the url is of some file in the file system and wrongly it is giving you '\' instead of '/'? in which case JS might crash... I guess.
It may be that url is not in proper form. So just try to console/alert thr url in "uf" variable, and url in winodw.open(...) statement and then check.

How to combine PHP and Javascript together?

I have a function in my Javascript script that needs to talk with the PHP to get the data in my database. But I'm having a small problem because I start the PHP in the for loop in Javascript, and then inside that for loop I get the data in my database. But the pointer in the for loop inside the PHP code is not working.. I guess the problem is in escaping? Or maybe it's not possible at all.
Here's my code:
(function() {
var data = [];
for(var i = 0; i < 25; i++) {
data[i] = {
data1: "<a href='<?= $latest[?>i<?=]->file; ?>'><?= $latest[?>i<?=]->title; ?></a>", // The problems
data2: ....
};
};
});
I think you are confused, you are trying to use a variable of javascript in php.
You cannot do this:
<?= $latest[?>i<?=]->file; ?>'
Which expands to:
<?php
$latest[
?>
i
<?php
]->file;
?>
how can you possibly know the value of i, if i is a variable generated in the client side?, do not mix the ideas, i is defined in the browser and the php code is on the server.
You may want to consider using PHP to output the JavaScript file, that way the PHP variables will be available wherever you want them.
The following links better explain this.
http://www.givegoodweb.com/post/71/javascript-php
http://www.dynamicdrive.com/forums/showthread.php?t=21617
1.Pass the javascript variable to the URL to another php page.
window.open("<yourPhpScript>.php?jsvariable="+yourJSVariable);
2.Then you can use this variable using $_GET in the php script.
$jsVaribleInPhp=$GET['jsvariable'];
//do some operation
$yourPhpResult;
3.Perform any server side operation in the Php and pass this result.
header("Location:<your starting page>?result=".$yourPhpResult);
4.Redirect back to the page you started from thus passing the result of PHP.
Php and Javascript have different roles in web development.
This task can also be performed if there's a php script and js in the same page. But that I leave for the readers to work it out.
Hope this helps!!

Uploadify: sending data with scriptData

I want to send the session value with uploadify script. I'm tryin following in javascript:
'scriptData': {'name':'<?php echo $_SESSION[name];?>'}
and in the php script im getting the value like:
$name = $_GET['name'];
The script data returns the value <?php echo $_SESSION[name];?>
instead of getting the value stored in session, for example Peter. Can someone please tell me how can i fix it?
Thanks
I think this is what you're looking for.
'scriptData': {'name':<?php echo "'".$_SESSION[name]."'";?>}
I think your are modifying a .js file instead of a .php file. So, a .js file will never execute php code (between tags)

Categories