php inside javascript checkbox value - php

I have a list list of checkbox with name of files that came froma DB. Then I have button for delete the files. I have the following code for the button:
<input type='button' id='submit_btn' onclick='eraseFile()' value='DELETE FILES' />
and the eraseFile function
...
<script type="text/javascript" language="javascript">
function eraseFile(){
var checekedFiles = [];
$('input:checked').each(function() {
checekedFiles.push($(this).val());
});
alert(checekedFiles); // it gives me all the checked values..good
<?php
echo "HElllo World";
?>
}
</script>
It gives an error "missing ; before statement" and "eraseFile is not defined"
Is it possible to write php inside javascript right??

Is it possible to write php inside javascript right??
Unless the PHP code is generating valid JavaScript, then no.
The reason eraseFile is being called undefined is that your echo statement is causing a syntax error since it is printing the string literal Hellllo World at the end of the JavaScript function which violates JavaScript syntax rules.

Yes, it is possible.
PHP is parsed on the server, so you will literally be printing "HElllo World" inside your javascript function, which would probably cause an error.
You might be looking do do the following:
<?php echo 'document.write("Hello World!");'; ?>

Your PHP output gets appended to your JS function making your javaascript look like this:
<script type="text/javascript" language="javascript">
function eraseFile(){
var checekedFiles = [];
$('input:checked').each(function() {
checekedFiles.push($(this).val());
});
alert(checekedFiles); // it gives me all the checked values..good
HElllo World //syntax error here
}
</script>
You can do this:
<script type="text/javascript" language="javascript">
function eraseFile(){
var checekedFiles = [];
$('input:checked').each(function() {
checekedFiles.push($(this).val());
});
alert(checekedFiles); // it gives me all the checked values..good
alert("<?php echo "HElllo World"; ?>");
}
</script>
This will give a pop-up saying 'Hello World'
To pass a value from your Javascript function to your PHP script, you can do this:
var yourJsVar = {assign value here};
url = "yourPHPScript.php?value=" + yourJsVar;
if (window.XMLHttpRequest)
{ // Non-IE browsers
req = new XMLHttpRequest();
req.onreadystatechange = someFunction;
//someFunction will get called when the PHP script is done executing
try
{
req.open("GET", url, true);
}
catch (e)
{
alert(e);
}
req.send(null);
}
else if (window.ActiveXObject)
{ // IE
req = new ActiveXObject("Microsoft.XMLHTTP");
if (req)
{
req.onreadystatechange = someFunction;
req.open("GET", url, true);
req.send();
}
}
In your PHP script:
$yourPhpVar = $_GET['value'];
I mentioned someFunction above that gets called after the PHP script completes execution. This is how it should look. (Note that this is on your Javascript)
function someFunction()
{
if(req.readyState == 4 && req.status == 200)
{
//this will only execute after your AJAX call has completed.
//any output sent by your PHP script can be accessed here like this:
alert(req.responseText);
}
}

Try to echo a meaningful javascript code, "Hello World" it's not a valid JS statement.
Try something like
<?php
echo "alert('HElllo World');";
?>

Where is your eraseFile function defined?
if it is not defined until after the place it is called, you will get that error.
Side note:
You can have php echo inside of the javascript, except what you have there will not do much...

Yes, you can use PHP code in you script files, but your code generate invalid script code here.
<?php
echo "HElllo World"; // becomes: HElllo World (text!) in JS
?>

It is possible to write PHP in Javascript, but it is not the best pratice. The way we normaly do this is through AJAX read the documentation : http://api.jquery.com/category/ajax/

Yes, it is possible to include PHP inside JavaScript, since the PHP will be executed on the server before the page contents are sent to the client. However, in your case, what is sent is the following:
<script type="text/javascript" language="javascript">
function eraseFile(){
var checekedFiles = [];
$('input:checked').each(function() {
checekedFiles.push($(this).val());
});
alert(checekedFiles); // it gives me all the checked values..good
HElllo World
}
</script>
This doesn't validate as JavaScript, since the "Helllo World" is not a valid JavaScript command. This is why the function isn't being defined properly. You need to replace the "Helllo World" string with an actual JavaScript command.

Related

script is not getting variable from GET

I have code in /user.php:
<?php
$thisuser = $_GET['user'];
echo $thisuser;
?>
And i write in browser: /user.php?user=Maria
And the website do not echo anything. What is wrong about it?
I actually have a ajax script that should send there a variable by get but it do not work at all.
EDIT here is the whole thing:
echo '<div class="thisphotobox"><div class="photouser">' . 'Dodał: '.$numphotos["user"].'</div>';
<script>
function prof(profuser){
var xmlhttp=new window.XMLHttpRequest();
xmlhttp.open("GET", "user.php?user=" + profuser, true);
xmlhttp.send();
}
</script>
This seems to be related to the <a> tag's default behavior preventing your function to execute on click.
Since you are setting the URL inside the prof() function, you don't need he href value inside the <a> tag, so you could do something like this:
echo '<div class="thisphotobox"><div class="photouser">' . 'Dodał: '.$numphotos["user"].'</div>';
Note that I just set the href value to javascript:void(0);. So now onClick should take effect and the prof() function should be invoked.
** Visually verify if it's working: **
Use this javascript code:
<script>
function prof(profuser)
{
var xmlhttp=new window.XMLHttpRequest();
xmlhttp.onreadystatechange = function()
{
if ( (xmlhttp.readyState == 4) && (xmlhttp.status==200) )
{
document.getElementById('result').innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "user.php?user=" + profuser, true);
xmlhttp.send();
}
</script>
Then you will also have to add, in the same file where the javascript code is, the following:
<div id="result"></div>
Finally, please make sure you are properly closing the PHP tags <?php ?> and make sure that only PHP code is inside that block. HTML and Javascript must be outside that block.
The AJAX script will send the data by POST not by GET.
GET is to 'get' the value, POST is to pass the value.
You also only use the send() value for POST, so change the GET to POST in the AJAX.
Also, you need to declare your script BEFORE you call it in the HTML.

Simple Javascript error

I got a syntax error on the following code. Once I took out the first line of code, the alert pops. My brain is almost dead and I can't find out why. Please help. Thanks a lot.
JS
var rss = <?php echo json_encode($test); ?>;
alert("Hello World");
Updated
html
<?php
$test=get_array();
//the $test is a multi-dimention array.
?>
<script type="text/javascript" src="js/slideshow.js"></script>
json_encode will return FALSE on failure, so if it fails, echo false will output nothing.
so your code became below, which give you a syntax error.
var rss = ;
alert("Hello World");
Edit:
From your updated edit, the reason is:
You can not write php code in a js file.
If you need that variable in the js file, assign it to a global variable first.
<script type="text/javascript">
var rss = <?php echo json_encode($test); ?>;
</script>
<script type="text/javascript" src="js/slideshow.js"></script>
To avoid error, your code should be:
var rss = <?php echo json_encode($test) ? json_encode($test) : "''"; ?>;
alert("Hello World");
Even if json_encode returns false, your code would be:
var rss = '';
alert("Hello World");
This is because JavaScript throws fatal error and stops current script execution because of:
var rss = <?php echo json_encode($test); ?>;
The problem is that this may return non-Valid JSON string and it throws new exception,
What you can do:
First of all you should determine if the string you got from PHP is actually valid.
As JSON methods usually do throw errors, you can simply put this var into try/catch block
try {
var rss = <?php echo json_encode($your_array); ?>;
} catch(e){
alert('Invalid JSON string');
}
In PHP, please also check if it's valid to prevent sending invalid JSON string back to javaScipt
In a .js file, PHP doesn't work. It will work only in files with extension .php .
Put your JS code in the PHP page; then it works.

How to get the content of a jquery variable to use it in a sql query in php?

I'd like to know how can I use a jquery variable in a sql query?
Here is my jquery that is in my php file:
?>
<script type="text/javascript">
jQuery.noConflict();
jQuery(function(){
jQuery('#event_form_field-<?php echo $event_id; ?>').click(function() {
var bradio = jQuery("input[type=radio]:checked").val();
alert(bradio);
}) });</script> <?php
I want to use the bradio variable in a sql query (on the Having clause, for example Having answer='$bradio'.
But i don't know how to passe the jquery variable in php.
Can you please explain me how can I do this?
Thanks.
You can use AJAX to pass the variable to a PHP script. That PHP script can also return data to the JavaScript AJAX call, for instance you can output error or success in your PHP file so the JavaScript code can alert the user as to what happened (in my example this response is saved in the serverResponse variable):
jQuery(function ($) {
$('#event_form_field-<?php echo $event_id; ?>').click(function() {
$.get('path/to/server-side.php', { 'bradio' : $("input[type=radio]:checked").val()}, function (serverResponse) {
//the server request has been made and has come back successfully
});
});
});
Some documentation:
$.get(): http://api.jquery.com/jquery.get

Why doesn't browser parse the JS code in the file loaded by AJAX?

I have 2 files, the first file has some HTML and a portion of JS. The second file is the main file, and it loads the first file thru' XmlHttpRequest.
The first file is like this:
<div>
My HTML contents
</div>
<script id="my_js_block">
function my_function() {
alert(9);
}
</script>
The second file is like this:
<div id="div_ajax_content">
</div>
<script>
function load_ajax_content() {
//synchronously with XmlHttpRequest(...,...,false);
//...load and throw the first file into 'div_ajax_content'
}
load_ajax_content();
my_function(); <-- fails here
</script>
How to solve this matter?
Ajax is asynchronous. Your code attempts to call my_function() before the XMLHttpRequest has completed. Do this instead:
<script>
function load_ajax_content() {
//...load and throw the first file into 'div_ajax_content'
// then,
my_function();
}
load_ajax_content();
</script>
Okay, so now your ajax call is synchronous. You can parse the returned HTML for <script> tags, and handle them separately, but it's not pretty:
function load_ajax_content() {
//...load and throw the first file into 'div_ajax_content'
// then grab the script nodes one-by-one
var scriptElts = document.getElementById('div_ajax_content').getElementsByTagName('script'),
scriptElt,
propName; // http://www.quirksmode.org/dom/w3c_html.html#t07
if (scriptElts.length) {
propName = scriptElts[0].textContent ? 'textContent' : 'innerText';
}
for (var i=0; i<scriptElts.length; i++) {
scriptElt = document.createElement('script');
scriptElt[propName] = scriptElts[i][propName];
document.body.appendChild(scriptElt);
}
// finally,
my_function();
}
...or you could just use a library like jQuery, which automagically handles this exact problem (and many others!) for you.
Adding a script via innerHTML does NOT run the script. Therefore your function is not being defined, hence the failure.
Instead, I suggest loading HTML and JS separately, and either appending the JS using DOM methods to put the <script> tag on the page, or eval() to execute the returned file contents.
Following Kolink I found a pretty funny method but it works!
load_ajax_contents();
eval(document.getElementById("my_js_block").innerHTML);
my_function();
However, in order to make those functions evaluated by 'eval()' global, all the functions in the first file must be declared as variables, like this:
//this works!
my_function = function() {
alert(9);
}
and not:
//this makes the function nested in the context where eval() is called
function my_function() {
alert(9);
}
and also not:
//this makes the variable local to the context where eval() is called
var my_function = function() {
alert(9);
}

How can I access a multidimentional php array in javascript?

The code is like this:
<SCRIPT LANGUAGE="JavaScript">
function showReview(){
//javascript stuff
<?php
$http="obj.href ='http://localhost/PROJECT1/thispage.php'";
if (array_key_exists(0, $arr)){
$http .= "+'&PQID={$arr[0]['ID']}'+
'&PQNo={$arr[0]['QNo']}'+
'&PNextSWF={$arr[0]['NextSWF']}';";
}
echo $http;
?>
}
</SCRIPT>
But I can't access $arr array. I tried to declare it global or use the $GLOBALS variable.
Show Review is called during onclick.
$arr is set in the main php code.
I tried just accessing the array in the main php code and passing the resulting string to the javascript which is the '?&PQID=ar&PQno=1...' part of the URL but it doesn't pass successfully. I tried passing the array itself to the javascript but js but I couldn't access the contents.
PHP runs on the server, Javascript on the client - they can't see each other's variables at all really. Think of it this way - the PHP code just generates text. It might be Javascript, but as far as the PHP concerned, it's just text.
Basically, you need to use PHP to generate text which is valid Javascript for creating the same data structure on the client.
Add this to the JS-function:
var arr=<?php echo json_encode($arr); ?>;
The PHP-Array "$arr" should now be accessible to JS via "arr" inside the JS-function.
I guess you are trying something like this:
<?php
//example array
$arr=array(
array('ID'=>'0','QNo'=>'q0','NextSWF'=>1),
array('ID'=>'1','QNo'=>'q1','NextSWF'=>2),
array('ID'=>'2','QNo'=>'q2','NextSWF'=>3),
);
?>
<script type="text/javascript">
function showReview(nr)
{
//make the array accessible to JS
<?php echo 'var arr='.json_encode($arr);?>
//some obj, don't no what it is in your case
var obj={};
var href='http://localhost/PROJECT1/thispage.php';
if(typeof arr[nr]!='undefined')
{
href+='?PQID='+arr[nr]['ID']+
'&PQNo='+arr[nr]['QNo']+
'&PNextSWF='+arr[nr]['NextSWF'];
}
else
{
alert('key['+nr+'] does not exist');
}
//check it
alert(href);
//assign it
obj.href=href;
}
</script>
<b onclick="showReview(0)">0</b>-
<b onclick="showReview(1)">1</b>-
<b onclick="showReview(2)">2</b>-
<b onclick="showReview(3)">3</b>
Try this
<SCRIPT LANGUAGE="JavaScript">
function showReview(){
//javascript stuff
var http =
<?php
$http="obj.href ='http://localhost/PROJECT1/thispage.php'";
if (array_key_exists(0, $arr)){
$http .= "+'&PQID={$arr[0]['ID']}'+
'&PQNo={$arr[0]['QNo']}'+
'&PNextSWF={$arr[0]['NextSWF']}';";
}
echo $http;
?>
}
</SCRIPT>

Categories