inserting JQuery function into php - php

I am trying to use some jQuery functions inside of my php page which I am using for a wordpress plugin. I have imported the jquery api using the below code however I'm not sure how to write the function.
<?php
echo "Custom Book Settings Page";
echo '<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js" type="text/javascript"></script>';
this produces syntax error
<?php
$("#form1").submit(function() { $.post("customBook-index.php"); return false; alert ("submit form 1"); });
?>

Like the others have said, you can't use JavaScipt (or any of its libraries) inside PHP. You certainly can, however, use PHP to print out JavaScript which will be run at the appropriate time.
<?php echo "<script type='text/javascript'>
$(document).ready(function(){
$('#form1').submit(function() {
$.post('customBook-index.php');
return false;
alert ('submit form 1');
});
});
</script>";
?>

why wouldnt you just have the syntax without the tags?
$("#form1").submit(function() { $.post("customBook-index.php"); return false; alert ("submit form 1"); });
if you have to have php write the statement, you forgot the echo
<?php
echo '$("#form1").submit(function() { $.post("customBook-index.php"); return false; alert ("submit form 1"); });';
?>

You cannot use jQuery like that within your PHP. JQuery is a JavaScript library. It is essentially code that is pre-written for you and abstracted in such a way that it makes it easy to use. When you call $('#myElementId) you are calling an abstraction of a JavaScript function (or set of functions).
Using jQuery within PHP won't work, because the PHP interpreter has no way to make sense of it. It would be like speaking giving instructions in Chinese to a (monoglot) Anglophone. Furthermore, there is a significant difference between PHP and JavaScript in as much as PHP is executed on a web server, and JavaScript is executed on a client's machine. This is an important concept to understand for any web programmer.
In short, you either need to write your JS function into a <script> tag on the page such that the navigator parses it as JavaScript, or determine the PHP equivalent for what you are trying to do.

// turn off php
?>
$("#form1").submit(function() {
$.post("customBook-index.php");
return false;
alert ("submit form 1");
});
<?php

Related

php variable pass to java script and alert it

index.php
<?php
$loginmessage = "this is message";
?>
$(document).ready(function(){
$("#sb-btn").click(function() {
alert("<?=$loginmessage?>");
return false;
});
});
i have a button i wanted to when the button is clicked , it alert the $loginmessage by java script , but when i clicked it noting happen and no error as well. what i have to do to make the php variable pass to javascript and alert it when user clicked.
Don't forget to call jquery library. then try this-
<?php
$loginmessage = "this is message";
?>
<script>
$(document).ready(function(){
$("#sb-btn").on("click", function() {
var getvalue = '<?php echo $loginmessage; ?>';
alert(getvalue);
});
});
</script>
Depending upon your PHP version and host, the short tags could be disabled. They recently came back into use with PHP7, which is still in Release Candidate state.
What this means is that you might have to replace the short tags with the full <?php echo use. Look in the generated HTML code on the client, to find out if this is the case.
One small thing I'd like to nitpick on, is your terminology. :P
You're not actually passing a variable to JavaScript from PHP, as much as you're using PHP to generate parts of said JS. It might seem trivial, but the difference is a crucial one. Passing the variable implies something being handled in the same program, which isn't the case at all here. The PHP code gets executed on the server side, which generates plain text output to the client. The client (web browsers) in turn parses said content, and figures out what kind of content the different part of this text actually is.
Having this clear mental separation in mind when developing web applications/sites will make it a lot easier for you to understand the details of how things work, and in turn make it easier for you to come up with clean and simple solutions that works as intended. :)
Try to write in console. Maybe your browser blocks alert messages. And-> are you see JavaScript errors in your console?
<script>
$(document).ready(function(){
$("#sb-btn").on("click", function() {
var getvalue = '<?php echo $loginmessage; ?>';
console.log(getvalue);
});
});
</script>
Create a function that is called when a button is clicked. Pass the message that you want to alert to that function. Hope this helps. Checkout the code in snippet.
function alertSomething(test){
alert(test);
}
<button name="samplebtn" onclick="alertSomething('test alert')">Test Alert</button>

Calling PHP from Java Script

I'm new at dealing with web programming and not used to dealing with the flow of data through a site.
I was looking for a way to call PHP from Java Script or from HTML and came across the following code with many other answers from this site. One thing that I got from Stack Overflow was that Ajax was the only good way to do this and JQuery would be the best way to go about that.
Is the code below safe? Are there holes in it that I don't know about at this point of learning?
<?PHP
$a="hello";
?>
<script>
function echoHello(){
alert("<?PHP hello(); ?>");
}
</script>
<?PHP
FUNCTION hello(){
GLOBAL $a;
ECHO $a;
}
?>
<button onclick="echoHello()">Say Hello</button>
This is not AJAX, but server-side code that only loads at first request.
A mockup of your functionality using AJAX is:
functions.php file:
<?php
$clientSideMethodRequested = $_POST['method'];
if ($clientSideMethodRequested == "sayhello"){
tellHimHello();
}
function tellHimHello(){
echo 'Hello!';
}
?>
client-side AJAX call:
$(document).ready(function(){
$.ajax({
type: "POST",
url: "mydomain.com/functions.php?method=sayhello",
success: function(returnedString){
alert(returnedString);
}
});
});
It will not work. PHP is executed on server, JS is executed in your browser. When you are opening page, the server will at first interpret your code. The result of your code, after this will be like that:
<script>
function echoHello(){
alert("hello");
}
</script>
<button onclick="echoHello()">Say Hello</button>
As you see, everything what was between <?php and ?> was "removed" from the origin file. By "removed" I mean executed.
Sometimes, when your server is not configured to interpret PHP, you will see PHP code in page source in browser. But it still won't work, because no browser supports PHP.
PHP is a server side language, so the code that your browser will "receive" will contain nothing related to PHP. What will happen is that this PHP file will be parsed and executed still in the server, and your browser will get only the following code:
<script>
function echoHello(){
alert("hello");
}
</script>
<button onclick="echoHello()">Say Hello</button>
which is the result of your server's PHP execution. This might be just what you expected in this particular case, but what if we wanted to pass parameters to echoHello function?
<script>
function echoHello(speech){
alert("<?PHP hello(speech); ?>");
}
</script>
<?PHP
FUNCTION hello($speech){
return $speech;
}
?>
<button onclick="echoHello('hello')">Say Hello</button>
<button onclick="echoHello('bye')">Say Bye</button>
One could expect this to alert 'hello' when the user clicks the first button, or 'bye' for the second one. This is not true, as the server starts executing this code before the buttons even exist (as they will only exist when the browser downloads the processed document to render the elements), and thus won't even be able to execute echoHello since speech isn't a valid variable. For this case and many others, AJAX is indeed the most appropriate way to go.
This tutorial should be good for a start.

PHP code in JavaScript to get variable

When I press on any of the ‘region’ names in the list ('href' links), the matching list of 'cities' is showing underneath.
<?php while(has_list_regions()) { ?>
<?php } ?>
<script type="text/javascript">
function show_region(chosen_region_id)
{
;
$(this).slideDown(200);
;
<?PHP $clicked_tag = 'chosen_region_id'; ?>
}
</script>
Is it possible to include PHP code within a section of JavaScript? Because I need to get the ID of the selected ‘href’ that I clicked. I am trying to include the PHP code in the above JavaScript function but it doesn’t work.
PHP runs on the server, generates the content/HTML and serves it to the client possibly along with JavaScript, Stylesheets etc. There is no concept of running some JS and then some PHP and so on.
You can however use PHP to generate the required JS along with your content.
The way you've written it won't work.
For sending the value of clicked_tag to your server, you can do something like (using jQuery for demoing the logic)
function show_region(chosen_region_id) {
...
$.post('yourserver.com/getclickedtag.php',
{clicked_tag: chosen_region_id},
function(data) { ... });
...
}
In your script the variable chosen_region_id is already in the function so you don't really need to declare it again with PHP.

Trying to toggle divs with JS after calling a PHP script

I am wondering whether this is possible:
I have a page. The user clicks a link and that calls a PHP script. The PHP script returns true or false.
Depending on the true or false, I was hoping to be able to toggle a div.
I am wondering whether I need to do it the AJAX way? How do people usually accomplish this?
Seems pretty common.
I am using this YUI library already:
<link rel="stylesheet" type="text/css" href="http://yui.yahooapis.com/combo?2.8.2r1/build/reset-fonts-grids/reset-fonts-grids.css&2.8.2r1/build/base/base-min.css">
jQuery:
$.post('/path/to/url', {data: 'some data'}, function(data) {
if (data) $('#some-div').show();
else $('#some-div').hide();
}, 'json');
PHP:
echo json_encode(true);
For more information see:
http://api.jquery.com/category/ajax/
http://php.net/manual/en/function.json-encode.php
Yes, you should use AJAX to create a good flow in your site. Instead of implementing your own AJAX handling functions, you could use one of the big JavaScript frameworks, I recommend http://jquery.com/. There, you can read about (and see examples of) jQuery.ajax - http://api.jquery.com/category/ajax/.
This should get you started, but the main idea is to bind that link to an AJAX function, that will call your PHP script, and based on the contents of the returned data, toggle your DIVs on/off.
Good luck!
Set the php script to add a hidden field ... such as...
<input type="hidden" id="passed-value" value="passed-val-is-true" />
Then in your Javascript when you fire the toggle event .. check that element ...
In jQuery would be something like this ...
$foo.click(( if (passed-value.value === "passed-val-is-true") { foo.toggle(); }
Sorry for syntax .. but you should get the general idea.
Also, if you need it to do without page reload, i would def recommend Ajax (pref via jQuery)
Yes, very easy, no need for Ajax. Here's two ways:
Using straight PHP:
<?php
if($test) {
echo "<div>Content...</div>";
}
?>
Or, using inline Javascript (in the PHP script), assuming you have a <div id='targetDiv'> in your HTML, and a $testVar in your PHP:
<script type='text/javascript'>
function toggle(testVar) {
if(testVar) { document.getElementById('targetDiv').style.display = ""; }
else { document.getElementById('targetDiv').style.display = "none"; }
}
window.onload = function() { toggle(<?php echo $testVar; ?>); }
</script>
The second method can be easily altered to degrade gracefully.

Calling JavaScript within Php block and vice-versa

echo "<a href=#> Delete </a>";
Whenever a user hits Delete, a javascript function should be called for confirmation. Somewhere in the Javascript function, php code should be used for delete operation. How do I do that? Use something like "some php code goes here" and "some javascript function();" for me to know where to put what. Thanks.
This assumes that you are using jQuery...
<a href='javascript:delete();'>Delete</a>
<script type="text/javascript">
function delete()
{
$.post("/your_script.php", {}, function(result) {
});
}
</script>
JavaScript functions execute on the client (in the browser) and PHP executes on a server. So, the JavaScript must send a message - via HTTP - to the server to be handled by PHP. The PHP would perform the delete. Make sense?
The message sent to the server might be sent via AJAX.
Maybe you should use Ajax: http://en.wikipedia.org/wiki/Ajax_%28programming%29
PHP is a server-side technology, while JS is a client-side. They cannot interact with each other - in other words: they're completely independent.
PHP can only output code that is a JS code:
echo 'document.getElementById("test").appendChild(document.createTextNode("' . $myVar . '");';
It's all PHP can do. JavaScript cannot direct interact with PHP as well. You'll have to use AJAX to send a new HTTP request and process returned data.
PHP is a server-side language, thus you can not output PHP script to the browser and expect that it will parse it with the PHP engine.
What you're looking for is probably AJAX, or simply redirecting the user to another page (with different URL parameters) or submitting a form.
AJAX doesn't require from the browser to reload the page, while the two other methods does.
Anyway, you can execute a JS script with the "onclick" method, that's executed when the user clicks on the element: Delete
But the following approach looks better and considered as an ideal one:
Delete
<script type="text/javascript">
document.getElementById("myId").onclick = myFunc;
</script>
Since this involves Ajax, let's assume you can use jQuery to handle the XHR an so on.
<script>
$('#del').click(function(ev){
ev.preventDefault();
var del_conf=confirm('Are you sure you want to delete this item?');
if(del_conf){ $.post('delete.php',{'del':1,'id':123123},function(data){
alert(data.result);},'json');
}
});
</script>
<a id='del'>Delete</a>
Okay, so that's some JS and HTML. Now, you need a separate PHP script to handle the post. To go with the example, this would be saved in the same directory, named 'delete.php'.
<?php
$del=(int)$_POST['del'];
$id=(int)$_POST['id']
if($del<1 || $id<1){ exit; }
else{
//do your DB stuff
}
if($db_success){
echo json_encode(array('result'=>'success'));
}
else{
echo json_encode(array('result'=>'error'));
}
here is another example using jQuery:
<div id="message"></div>
<a class="action" type="delete" rel="1234567">delete</a>
<script type="text/javascript">
$('a.action').click(function(){
var $this = $(this);
var processResponse = function(data){
//optionaly we can display server response
$('#message').html(data);
return;
};
var postPparams = {
module:'my_module_name',
action:$this.attr('type'),
record_id: $this.attr('rel')
};
$.post('/server.php',postPparams, processResponse);
});
</script>

Categories