running javascript from php? - php

I don't know if this is possible as i know php is server side and javascript is client side.
But i am trying to run this javascript code from an if isset inside a php page.
I am using this code:
<?php
if( isset($_POST['submit2'])){
echo "
<script type=\"text/javascript\">
$(document).ready(function(){
setTimeout(function () {
doWork();
window.location.reload();
}, 2000);
function doWork() {
$('#submit').trigger('click');
}
});
</script>";
}
?>
this javascript should click on the button named (submit) and it works fine if its not inside the PHP echo.. and I also checked to see if the if if( isset($_POST['submit2'])) actually returns a value and it does and it works as it should.
So, I don't know what the issue is here>
can some one please help me out with this?

I have always found it best to keep my main javascript/jquery code within the head tag and use php to check and set variables that allow my scripts to run; echoing a javascript boolean into my JS block using php. This way you know that the javascript is doing what it should natively and not worry about elements not being treated properly in the DOM.
So I would do this (I don't know the order in which you want things to happen so this might seem out of order but the principle should still be the same):
<?php
if( isset($_POST['submit2'])){
$varSet = "var set2 = 1;";
} else {
$varSet = "var set2 = 0;";
}
?>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type=\"text/javascript\">
$(document).ready(function(){
<?php echo $varSet; ?>
if(set2 == 1){
setTimeout(function () {
doWork();
window.location.reload();
}, 2000);
function doWork() {
$('#submit').trigger('click');
}
}
});
</script>
</head>

Related

Use jQuery in external php file

I have a php file that I load into another php file with jQuery. This works, but the moment I start using jQuery in the 'external file', I get ERROR 500.
The reason I used this approach is because this is handy to refresh the data after an AJAX function.
This I have:
test.php:
<script type="text/javascript" src="js/modernizr.custom.29473.js"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.1.js"></script>
<script type="text/javascript" src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<script>
$(function () {
$(document).tooltip({
items: ".plupic , .ingr",
content: function() {
var element = $( this );
if ( element.is( ".plupic " ) ) {
var src = element.attr('src');
return "<img src='" + src + "' style='max-height: 300px; max-width: 300px;'>";
}
if ( element.is( ".ingr" ) ) {
var txt = element.text();
return txt;
}
}
});
$('#kasticket').load('cart.php');
});
</script>
</head>
<body>
<div class="container">
<div id="kasticket"></div><!-- Load data with jQuery-->
cart.php:
I just do a select from the database and write some data to a table with echo();
This works perfectly, but the moment I want to use jQuery, I goes all wrong...(I know this for sure because the jQUery works in a local html file and putting this line in comment makes my php working again)
echo("
<script>
jQuery(document).ready(function() {
if($('#L$MyAant').width() < 70) {
$('.TR1$MyAant').show();
$('.TR2$MyAant').hide();
}else{
$('.TR2$MyAant').show();
$('.TR1$MyAant').hide();
}
});
</script>
");
I have no idea what I'm doing wrong.
If its any help: http://www.itreflex.be/TestAcc/test.php (with currently the jQuery line in comment).
And this is cart.php, exported to txt, it was to long to paste here.
hard to tell without the full source code but I have got a couple of ideas:
First Error 500 should be the HTTP code for internal server error, which basically means that the error lies on the server, then on the PHP side.
Could it be possible that you are mixing up PHP and jQuery on some of your other statements not posted here?
Second, you missed a single quote on your line
$('#kasticket').load(cart.php');
In your cart.php remove the brackets after echo ... For example
echo "<script>
jQuery(document).ready(function() {
if($('#L$MyAant').width() < 70) {
$('.TR1$MyAant').show();
$('.TR2$MyAant').hide();
}else{
$('.TR2$MyAant').show();
$('.TR1$MyAant').hide();
}
});
</script>";
Try this above line in your cart.php and see if that works.

New to jQuery - why isn't this simple function working?

I'm building a web application inside CodeIgniter and I've decided to have a fiddle with jQuery and Javascript - something I've never really used before.
I have included jQuery in my header using Google Libraries:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
And now I'm fiddling with the SIMPLEST of jQuery but it's not working.
<p><?php if ($post->love) { echo $post->love; } else { echo 0; } ?></p>
<script type="text/javascript">
$("#lovecounter").click(function() {
alert("Click");
});
</script>
I am clicking on the lovecounter link but there is no alert. If I add simple javascript to the actual anchor tag it works though.
<p><?php if ($post->love) { echo $post->love; } else { echo 0; } ?></p>
Any ideas? What am I doing wrong?
Wrap your code in ready handler:
$(document).ready(function(){
$("#lovecounter").click(function() {
alert("Click");
});
});
Working Example
This works perfectly fine for me:
<p>asdf</p>
<script type="text/javascript">
$(document).ready(function() {
$("#lovecounter").click(function() {
alert("Click");
});
});
</script>
You should include a $(document).ready(function() {}); just like Sarfraz said. Otherwise, it would not find anything with an id of lovecounter because nothing on the page has loaded yet. If you wait for it to load, then it will find the element. Here is some documentation: http://www.w3schools.com/jquery/event_ready.asp. Here is a full jQuery lesson: http://www.codecademy.com/tracks/jquery.

php inside javascript checkbox value

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.

Jquery .each method

learning Jquery and integrating with PHP - getting there, but have one last challenge in some code I'm working on.
I have HTML in a string, trying to pull html in tags, might be multiple elements in the HTML string, so trying to use each. My function worked fine without each, below is my each integration (returns nothing currently):
<?php
$info = '<li><strong>I want this text</strong></li><li><strong>I want this text too</strong></li>';
$info = json_encode($info);
?>
<script type="text/javascript">
$(document).ready(function () {
$("a", $( < ? php echo $info; ? > )).each(
function () {
alert($(this).html());
});
};
This code below does work, but only returns the first element in the HTML:
<?php
$info = '<li><strong>I want this text</strong></li>';
$info = json_encode($info);
?>
<script type="text/javascript">
$(document).ready(function () {
var output = $("a", $( < ? php echo $info; ? > )).html();
var link = $("a", $( < ? php echo $info; ? > )).attr("href");
alert(output);
alert(link);
});
</script>
This is a description and a working example of How to use .each() LINK
You can try this one as a example
$("a").each(function(index){alert($(this).html()});
Your code is not working because there are a few syntax issues.
First, change
< ? php echo $info; ? >
to
<?php echo $info; ?>
PHP doesn't like spaces and the opening and closing tags must appear without spaces.
Second, close the ready function and the script tag properly. Instead of
};
use,
});
</script>
Why are you encoding a piece of XML with JSON? That makes like no sense at all. Both are ways to encode data. HTML is XML too, btw. You can directly reference the $info variable since PHP will process everything first on the server.
<?php
$info = '<li><strong>I want this text</strong></li>';
?>
<script type="text/javascript">
$(document).ready(function() {
$("a", $("<?php echo $info; ?>")).each(
function () {
alert($(this).html());
}
);
});
Or just remove the temporary variable altogether. Makes it combersome to read, but that's essentially what PHP is doing.
$("a", $("<?php echo '<li><strong>I want this text</strong></li>'; ?>")).each(
Or to make it even simpler, since you already have the HTML, simply include it as part of the page and maybe give it an ID to make referencing it easier with jQuery.
<li id="myList">
<strong>I want this text</strong>
</li>
<script type="text/javascript">
$(document).ready(function() {
$("a", "#myList").each(function() {
alert($(this).html());
});
});
</script>
This last example gets rid of PHP completely, but you weren't really using it anyways.

Trouble with javascript if statement

Ok, I'm making a login and registration panel with jquery and php. In short, if there are errors with the registration it sets a few form errors, redirects back to the registration page, the javascript detects there are errors with the use of a php variable and forces the slider to show itself.
The working code: Above the doc type $errors = $form->num_errors; and the whole $errors routine works fine.
My problem is that I also have a verification that the form was submitted successfully. It uses
if(isset($_SESSION['regsuccess'])){
$success = 1;
} else {
$success = 0;
}
to set the $success variable. The crazy thing here is that this doesn't work using the same routine as the $error variable. I know the $success conditional is working correctly as I have an it echoed out further down the page.
jQuery slide script:
$(document).ready(function() {
var num_errors = "<?php $errors; ?>";
var form_success = "<?php $success; ?>";
// Expand Panel
$("#open").click(function(){
$("div#panel").slideDown("slow");
});
// Collapse Panel
$("#close").click(function(){
$("div#panel").slideUp("slow");
});
// Switch buttons from "Log In | Register" to "Close Panel" on click
$("#toggle a").click(function () {
$("#toggle a").toggle();
});
//this part works
if(errors>0){
$("div#panel").slideDown();
$("#toggle a").toggle();
}
//this part doesn't
if(form_success>0){
$("div#panel").slideDown();
$("#toggle a").toggle();
}
});
The demo page is here http://demo.ivannovak.com/danlogin/index.php
Suggestions would be appreciated, thanks!
In your page, you have an errors variable defined, that's why that portion works:
<script type="text/javascript" language="javascript">
<!--
errors = 0; // -->
</script>
Your javascript file isn't processed by php, it's served directly by the web server so your variables in what you listed above:
var num_errors = "<?php $errors; ?>";
var form_success = "<?php $success; ?>";
Those come out exactly that way to the client, they aren't replaced with their values. You need to move those 2 lines into your page where you have errors now, and remove them from quotes as well. Take them out of your js and use this in your page:
<script type="text/javascript" language="javascript">
var num_errors = <?php $errors; ?>;
var form_success = <?php $success; ?>;
</script>

Categories