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.
Related
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.
On my page I have a search result that contains a list with users where each is followed by an "addfriend" button. Each row contains a username and userID. Meanwhile the ID of the user that requested the searchresult is stored in a Session variable.
When the addfriend-botton is clicked the following 2 things should happen:
Store the userID and $_SESSION['userID'] is a MySQL table which describes the relationship.
Do NOT refresh the page (this the core of my problem) but stay focussed and change the state of the button to e.g. "friend request send". I'm thinking of GetElementByID().style method.
I was thinking of this:
<a href="#" onClick="addFriend('<? echo $_SESSION['userID'];?>','<? echo $rij['userID']; ?>')">
which calls the javascript function addfriend
I was hoping to catch the two ID's like this:
<script>
function addfriend(id1, id2)
{
//server side php code where I use value of
//the client-side javascript variables: +id1+ and +id2+ .
}
</script>
Is this at all possible or I'm I thinking the wrong way? Any suggetions on how to accomplish this?
You are in the right way, inside your addFriend() function, you can call one php file (via AJAX) and send the IDS without refresh the page. I think better you work with Jquery in this case, something like this:
<script>
function addfriend(id1, id2)
{
$.ajax({
type: 'POST',
url: 'yourPHPfile.php',
data: { your_id_1:id1, your_id_2:id2 },
success: function(data){
if(data){
alert('Done!');
}
},
dataType: 'text'
});
}
</script>
And in your PHP File you can do this:
<?php
//receive Ids
$id1 = $_POST['your_id_1'];
$id2 = $_POST['your_id_2'];
//do something here
echo "OK!";
<?
to do this work you need download and add the jQuery plugin in your page, rather into head tag
<head>
<script type="text/javascript" src="jquery.js"></script>
</head>
Good work and don't give up! (:
You can do this using AJAX (asynchronous JavaScript and XML), which is really just a fancy term for "sending stuff to a server with JavaScript and getting a response back, without reloading the page". There's nothing special about AJAX; it just involves using plain old JavaScript to send an HTTP request.
Check out jQuery, a JavaScript library that handles most of the technical stuff for you. Specifically, look at its post() function, which allows you to send data to a PHP script using the $_POST system variable. There are lots of clear examples on that page.
Note that you don't need jQuery to use AJAX; jQuery is just a library that makes things easier. If you really want to learn how the JavaScript side of AJAX works, try following one of the many tutorials out there, such as Mozilla's or this one.
AJAX is the answer you're looking for.
It sounds like you already have a basic understanding of this, but to clarify, Javascript executes on the client side, and PHP executes on the server side. So you would have to make a call back to your server in order to interact with PHP/MySQL.
The purpose of AJAX is to do this without requiring a page refresh.
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've looked up briefly about the problems of having a dynamically changing site via javascript or php. However, I'm not interested in url link-backs, getting Google to spider the site, or general url navigation. I will however, tend to those who do not use javascript through my site.
To the question, I am curious that if I were to implement a dynamically changing page using jQuery and Ajax, will that cause vulnerability problems with PHP in the way I am implementing it?
Example jQuery:
<script type="text/javascript">
$(document).ready(function(){
$("div#text").hide();
$("div#text").fadeIn("slow");
$("li#button").click(function(){
var page = $(this).attr("page");
$.ajax({
url: page,
success: function(contents){
$("div#text").empty();
$("div#text").hide();
$("div#text").html(contents);
$("div#text").fadeIn("slow");
}
});
});
});
</script>
Called PHP/HTML:
<h1>Hello</h1>
<?php /* Do mysql/secure things here */ ?>
If there are more efficient/standard ways of doing what I want, I'm open to suggestions. I am not a jQuery programmer by any means.
So long as your PHP script is correctly sanitizing any REQUEST variables before use (and not returning unencrypted sensitive data, of course), this approach should be fine. The input is coming from the page just as any other URL request or form input would.
Using Ajax doesn't make the request any less secure than it would be otherwise.
Is there a way to send data to database when click on a link without page refresh?
I use php/mysql...
I will give you an example using jQuery.
Let's say that we have a link with an attribute id="button_id" (you have to learn the jQuery selectors ).
$("#button_id").click(function(){
var var_data = 5;
$.ajax({
url: "my_script.php",
data: { var_PHP_data: var_data };
success: function(data) {
// do something;
alert(data);
},
});
});
Explanation: you will send the variable var_data with the name var_PHP_data to a my_script.php without page refresh using an ajax call (using GET method).
This is very simple example of what you have to write on your PHP script.
<?php
$var_name = $_GET['var_PHP_data'];
echo 'This is what you have send'.$var_name;
?>
Because the default method to send variables in the ajax function in jQuery is GET.
We have to use the $_GET function in PHP.
This php script will print a message and this message will be handled in the success: function in the Ajax call and just for example we will alert this message returned from PHP.
You'd have to use JavaScript. When a user clicks a link, if you don't use JavaScript, then you need to go user -> server -> user and they get a whole new page.
HTTP is stateless.
It's not possible without a page refresh but this is the classic use-case for AJAX requests. If you're not familiar with AJAX then there are various methods of doing this using all the popular JavaScript frameworks such as Prototype and jQuery
You can't send data directly to a database, but you can use AJAX to send data to a php page that will save them to the database, without reloading the page or following the link in the browser..
Have a look at http://api.jquery.com/jQuery.post/
Not using PHP because it is server side - you need JavaScript / AJAX for this.
Check out frameworks like dojo (http://www.dojotoolkit.org/) , mootools (http://mootools.net/) or jQuery ( http://jquery.com/ ).
Yes, you can use AJAX.
This is a very big topic, but I'd recommend you do some research on AJAX and jquery (javascript).
Here are some tutorials:
http://www.ajaxf1.com/tutorial/ajax-php.html
http://www.talkphp.com/vbarticles.php?do=article&articleid=58&title=simple-ajax-with-jquery
Do a search in google for more info.