If I want to do some PHP on an event(e.g. onchange) should I use jQuery ajax like:
$("#elm").on("change", function(){
//ajax code
}
, should I use the PHP in the HTML attribute like:
<element onchange="<?php //stuff to do ?>"></element>
You seem to be conflating two different issues.
JS bound events vs intrinsic event attributes.
Bind your event handlers with JS.
Follow the principles of Progressive Enhancement and Unobtrusive JavaScript.
Ajax vs Putting PHP in a JS function
If you put PHP in a JS function then it will run when the PHP outputs the JS function to the browser, not when the JS function is called.
If you want to run PHP in response to an event, then you have to make an HTTP request to the server to run the PHP.
If you want to insert content from the load of page and leave it static, you should use only PHP.
If you want to insert content dynamically (changing with users interactions) you should use AJAX.
I can't found out what are you trying to achieve with your example, so not very sure what you should do there.
taking your code it would give this :
$("#elm").on("change", function(){
//ajax code
$.get('url', {data:'tosend'}, function(data){
// here you have the response of the php script in the data object
// it can be json for exemple
});
}
You must realise two things, your php code will be render when the page is loaded in the
browser so the second code you gave us
means that your "onchange" event is already present in your page.
If you want to request something (data, html, etc) to server from a loaded page, then do an ajax.
In that case below code is correct.
$("#elm").on("change", function(){
//ajax code
}
You cannot execute a piece of php code from client side. But you can assign values from php to javascript and then do operations on client side.
Related
I have a PHP Function that I would like to integrate into my (existing) web page. Further, I would like it to execute when the user clicks a link on the page. The function needs to accept the text of the link as an input argument.
Everything I've researched for sending data to a PHP script seems to involve using forms to obtain user input. The page needs to accept no user input, just send the link-text to the function and execute that function.
So I guess the question is two-part. First, how to execute a PHP script on link click. And second, how to pass page information to this function without the use of forms. I am open to the use of other technologies such as AJAX or JavaScript if necessary.
EDIT:: Specifically what I am trying to do. I have an HTML output representing documentation of some source code. On this output is a series of links (referring to code constructs in the source code) that, upon being clicked, will call some python function installed on the web server (which leads me to think it needs called via PHP). The python function, however, needs the name present on the link as an input argument.
Is there some sort of interaction I could achieve by having JavaScript gather the input and call the PHP function?
Sorry for the vagueness, I am INCREDIBLY new to web development. If anything is unclear let me know.
You'll need to have a JS function which is triggered by an onclick event which then sends an AJAX request and returns false (so it won't be redirected to a new page in the browser). You can do the following in jQuery:
jQuery:
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript">
function doSomething() {
$.get("myfile.php");
return false;
}
</script>
And in your page body:
Click Me!
In myfile.php:
You can add whatever function you want to execute when the visitor clicks the link. Example:
<?php
echo "Hey, this is some text!";
?>
That's a basic example. I hope this helps.
You will need to use AJAX to accomplish this without leaving the page. Here is an example using jQuery and AJAX (this assumes you have already included the jQuery library):
First File:
<script language="javascript">
$(function(){
$('#mylink').click(function(){
$.get('/ajax/someurl', {linkText: $(this).text()}, function(resp){
// handle response here
}, 'json');
});
});
</script>
This text will be passed along
PHP File:
$text = $_REQUEST['linkText'];
// do something with $text here
If you are familiar with jQuery, you could do the following, if you don't want the site to redirect but execute your function:
in your html head:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
the link:
Execute function
in ajax.php you put in your function to be executed.
Maybe something like this:
....
<script>
function sendText(e)
{
$.ajax({
url: '/your/url/',
data: {text: $(e).html()},
type: 'POST'
});
}
</script>
You can use query strings for this. For example if you link to this page:
example.php?text=hello
(Instead of putting a direct link, you can also send a ajax GET request to that URL)
Inside example.php, you can get the value 'hello' like this:
<?php
$text = $_GET['hello'];
Then call your function:
myfunction($text);
Please make sure you sanitize and validate the value before passing it to the function. Depending on what you're doing inside that function, the outcome could be fatal!
This links might help:
http://net.tutsplus.com/tutorials/php/sanitize-and-validate-data-with-php-filters/
http://phpmaster.com/input-validation-using-filter-functions/
Here's an overly simplistic example of what you're trying to do..
Your link:
Some Action
Your PHP file:
<?php
if (isset($_GET['action']))
{
// make sure to validate your input here!
some_function($_GET['action']);
}
PHP is a server side language i.e. it doesn't run in the web browser.
If you want a function in the browser to operate on clicking a link you are probably talking about doing some Javascript.
You can use the Javascript to find the text value contained in the link node and send that to the server, then have your PHP script process it.
I have some ajax that loads php script output into a div. I would like the user then to be able to click on links in the output and rewrite the div without reloading the whole page. Is this possible in principle? Imagine code would look like:
html
<div id="displayhere"></div>
php1 output
echo 'ChangeToNew';
JS
function reLoad(par1,par2,par3) {
...
document.getElementById("displayhere").innerHTML=xmlhttp.responseText;
xmlhttp.open("GET","php2.php?par1="+par1 etc.,true);
xmlhttp.send();
php2
$par1 = $_get['par1'];
change database
echo ''.$par1.'';
Could this in principle work or is the approach flawed?
Thanks.
What you describe is standard, everyday AJAX. The PHP is irrelevant to the equation; the JS will simply receive whatever the server sends it. It just happens that, in your case, the server response is being handled by PHP. The JS and PHP do not - cannot - have a direct relationship, however.
So the principle is fine. What you actually do with it, though, will of course impact on how well it works.
Things to consider:
what will the PHP be doing? This may affect the load times
what about caching responses, if this is applicable, so the PHP doesn't have to compute something it's previously generated?
the UI - will the user be made aware that content is being fetched?
Etc.
I'm used to using jQuery so will give examples using it.
If you create your links as
Click Me
You could then write your code as
<script>
$("#do_this").live('click', function(){
var link_url = $(this).attr('href');
$.ajax({
url: link_url,
success: function(data) {
$('#displayhere').html(data);
}
return false;
};
</script>
If you use jQuery, make sure you use the .live('click', function(){}) method versus the .click(function(){}) method, otherwise it won't recognize dynamically created elements. Also make sure you do a return false.
I would like to be able to execute a php script on a onclick state, but each page could hace multiple buttons each with a different action to send. I want the script to be executed, but i don't want the page tobe changed.
This is to execute a UDP client to change setting in a remote box.each button send a different action to different board, in fact i need to send 2 arguments to the script.
something like this i need to send: set_states.php?ip=xxx.xx.xxx.xx&cmd=CR1
Thanx for the help!
It doesn't really matter what the URL is. The important things is what HTML verb you are using (get, post, delete, put) and your returned content type. The URL can be anything. I'd just use some js library like jquery. Check out their $.get, $.post, $.ajax functions.
If you don't use a js library then you need to account for all the differences in various browsers. Typically though it goes something like this: http://www.w3schools.com/ajax/tryit.asp?filename=tryajax_first
In your case, I would use jquery (since it'll get you started extremely quickly). Since your variables are in the url and you aren't sending any other data you would use get. Typically for mutators you should use post. I don't think it matters in your case. Drop the following script on to your webpage (make changes as needed):
<script src="http://code.jquery.com/jquery-1.6.4.min.js"></script>
<script>
$(function(){
$('#the-id-of-your-button').live('click',function(){
$.get('set_states.php?ip=xxx.xx.xxx.xx&cmd=CR1',function(return){
alert('success');
});
});
});
</script>
The first part: $('#the-id-of-your-button').live('click' watches the browser in a sense to see if any elements that match appear and binds a click event to them. Live actively awaits for dom changes in a sense. Click is the handler, and $('#the-id-of-your-button') is the selector. The next part:
function(){
$.get('set_states.php?ip=xxx.xx.xxx.xx&cmd=CR1',function(return){
alert('success');
});
});
is what happens when the click event occurs. We call this an anonymous function. It can be rewritten as:
function onButtonClick(){
$.get('set_states.php?ip=xxx.xx.xxx.xx&cmd=CR1',function(return){
alert('success');
});
});
$('#the-id-of-your-button').live('click',onButtonClick());
or something like that, but thats just just to help you understand what is going on.
The next part:
$.get('set_states.php?ip=xxx.xx.xxx.xx&cmd=CR1',function(return){
alert('success');
});
is the ajax request and the function to execute if it successfully returns. In this case it will simply just alert us.
Oh also: $(function(){}); that wraps everything up, tells us to run the script when the page is ready. Soooo once the page is ready we will turn on the live command to watch for buttons. You may not need it (I know there are some cases, where it isn't important, but I put it there just in case).
You may need to tweak it a bit :).
For example, I have a php function:
function DeleteItem($item_id)
{
db_query("DELETE FROM {items} WHERE id=$item_id");
}
Then, I have something like the following:
<html>
<head>
<script type="text/javascript">
function DeleteItem($item_id)
{
alert("You have deleted item #"+$item_id);
}
</script>
</head>
<body>
<form>
Item 1
<input type="button" value="Delete" onclick="DeleteItem(1)" />
</form>
</body>
</html>
I want to be able to call the PHP function DeleteItem() from the javascript function DeleteItem() so that I can use Drupal's db_query() function, so I don't have to try to establish a connection to the database from javascript.
Does anyone have any suggestions on how this might be done? P.S. I understand that PHP processes on the server-side and javascript processes on the client-side, so please no responses saying that. There has got to be some kind of trick one can do in order to have this work out. Or maybe there is a better way of doing what I am trying to accomplish.
Since you are aware that PHP processes on the server-side and javascript processes on the client-side, you must also realize you can't call a PHP "function" from javascript. Your client side code can redirect to a PHP page, or invoke a PHP program using AJAX. That page or program must be on the server and it should do a lot more than just the one line you have in your function. It should also check for authentication, authorization, etc. You don't want just any client side script anywhere to call your PHP.
You need to write a PHP script which will execute the function. To call it, either:
use XMLHttpRequest (aka Ajax) to send the request
change the page's location.href and return HTTP status code 204 No Content from PHP
You will want to use ajax for that.
Also, database connection from within javascript is something you should not even consider as an option - terribly insecure.
A very simple example:
//in javascript
function DeleteItem($item_id) {
$.post("delete.php", { id: $item_id}, function(data) {
alert("You have deleted item #"+$item_id);
});
}
//in php file
db_query("DELETE FROM {items} WHERE id=" . $_REQUEST["id"]);
you can't actually call PHP functions within JavaScript per se. As #Christoph writes you need to call a PHP script via a normal HTTP request from within JavaScript using the magic that is known as AJAX (silly acronym, basically means JS can load external HTTP requests on the fly).
Take a look at jQuery's AJAX functionality on how to reliably make a HTTP request via JS, see http://docs.jquery.com/Ajax
All the normal security rules apply, i.e. make sure you filter incoming data and ensure it's what you're expecting (the $item_id in your example). Bear in mind there's nothing to stop someone manually accessing the URL requested by your JS.
First, use jQuery.
Then, your code will have to be something like:
<input ... id="item_id_1" />
<script>
$(document).ready(function() {
$('input').click(function(){
var item_id = $(this).attr('id');
item_id = item_id.split('_id_');
item_id = item_id[1];
$.get('/your_delete_url/' + item_id);
});
});
</script>
I'm building a page which loads the contents of our MySQL db for editing. Each row of the table is in a seperate, editable textarea on the page. I need the user to be able to update each row (ie send it's contents to the db) without reloading the whole page, with a click of a button that's responsible for that specific textarea.
I understand that such procedure would involve some JavaScript, but sadly I know none - I did all I could with php, so I need a pointing in that direction. Basically my question (I think) is how do I grab a text from an edited textarea and send it to MySQL without reloading the page. If I'm heading in the wrong direction I'd be more than willing to hear other suggestions.
Yes this will require javascript. Namely an async call to a PHP page you have. This is often called AJAX.
I hate to be the "use jquery" answer here but the hump of learning jQuery to use AJAX based calls is very low to the value you gain from calls like this.
The documentation has great examples and most of them are quite simple.
That's precisely what AJAX does: Asynchronous JavaScript and XML. It lets you send requests to the server without reloading the page.
I'd recommend starting with jQuery which you'll notice has a lot of support in the StackOverflow community, as well as elsewhere, and which makes cross-browser AJAX requests very easy.
With the jQuery script on your page, you can do something like this:
$("#id-of-the-button-the-user-will-click").click(function() {
$.post('/path/to/your/script.php', { field1: value1, field2: value2 }, function(data) {
// This function is called when the request is completed, so it's a good place
// to update your page accordingly.
});
});
Understanding the details will still require a thorough understanding of JavaScript, so really the best thing to do is dive in and start writing (and thus learning) a lot of JavaScript. AJAX is a fine place to start.
There is a good introduction to JavaScript at Opera. Jibbering covers the use of the XHR object, which is the usual way to send data to the server without leaving the page. Libraries such as YUI or jQuery can do some of the heavy lifting for you.
What you're looking for is AJAX. jQuery makes a lot of that easier; try starting here.
You can add JavaScript event to textarea:
onblur="sendUpdate(this.value)"
This event will happen when user has finished editing the text and leaves the input.
In example, "this" references current textarea component.
And then use Ajax, as previously mentioned. An example would be:
function sendUpdate (text) {
$.post('script.php', {textarea_value:text},function(){});
}
You need to make asynchronous calls to server from your script (javascript).Use ajax to achieve this.You need to have a look at using XMLhttp objects to communicate with the server /database from your client side script (javascript) . You need not submit the entire page using a button click,instead you can invoke the javscript code in a button click event or a onBlur event or a onTextChange event etc...
jQuery is a javascript framework library which helps you to reduce the number of lines of code to implement this. But its not necessary that you need to use jquery .You can do ajax calls without using jquery.Usage of jQuery will reduce the number of lines.
Check this
http://docs.jquery.com/Ajax/jQuery.ajax
You will definitely require JavaScript, and some method of sending a HTTP request to your PHP server without reloading the page. Generally, this is called AJAX.
It is probably best to use a JavaScript library, as AJAX is a bit complicated for beginning JavaScript developers. A good choice is JQuery, or MooTools
AJAX libraries usually use XMLHttpRequest or JSONP to implement the HTTP requests. Understanding those should make it a bit easier.
JQuery AJAX: http://docs.jquery.com/Ajax
MooTools AJAX: http://mootools.net/docs/core/Request/Request
Selecting the textarea element, updating it, would require use of the DOM (http://www.w3.org/DOM/). Most JavaScript frameworks now use an implementation of CSS or XSLT selectors to query the DOM.
JQuery Selectors: http://docs.jquery.com/Selectors
MooTools Selectors: http://mootools.net/docs/core/Utilities/Selectors
You can do this fine without JavaScript. Just have each textarea+button in its own <form>, then submit the form to a script that updates the database from the textarea value, and returns a:
204 No Content
status instead of 200 OK and a new page. The old page will stay put.
You can start by adding a jquery function to pick up any changes made ie:
$('#inputelement').on('input propertychange', function(){
alert("Alert to test jquery working");
});
You should then use AJAX to create a php script with the data (as php is how you update to the server) and send using either a GET or POST variable. Then use that script file to upload the changes to your server. e.g.
$('#yourElement').on('input propertychange', function(){
$.ajax({
method: "POST",
url: "updatedatabase.php",
data: {content: $("#yourElement").val()}
})
.done(function( msg ) {
alert( "Data Saved: " + msg );
});
});
Script upload:
session_start();
if(array_key_exists("content", $_POST)){
include("connection.php");//link to your server
$query = "UPDATE `users` SET `updateColumn`= '".mysqli_real_escape_string($link, $_POST['content'])."' WHERE id= ".mysqli_real_escape_string($link, $_SESSION['id'])." LIMIT 1";
if(mysqli_query($link, $query)){
echo "success";
}else {
echo "failed";
}
}
Try to read more about Ajax. There are a lot of libraries for it.