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.
Related
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'm currently working on a website and I would like to be able to do the following:
when clicking one of the links from the sideMenu the only thing I would like to change would be the content of my contentMain div and nothing else(page layout/design/etc)
Could anybody give me some general pointers on how I could achieve this in php?
Thank You in advance :D
This is a client-side change that cannot be accomplished using PHP. PHP is evaluated on the server-side, so once the page is loaded for the user, it has no control over what the user sees (unless you use client-side code to call PHP).
To accomplish this, you will need to use Javascript and/or jQuery.
Reference: https://developer.mozilla.org/en/JavaScript/
jQuery: http://jquery.org/
iFrame, frameset or AJAX all work for your case depending on what you are actually trying to achieve.
For AJAX calls (the most modern way out of the three that relies on Javascript) you can use a library such as jQuery.
http://api.jquery.com/category/ajax/
You can use ajax for this one. Using jQuery to detect the click on the link or use normal JavaScript onClick function. Then do the things like you want.
<a href="" id="my_link">My link<a>
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery('#my_link').click(function(){
jQuery.ajax({
url: 'ajax page need to be called',
success: function(data) {
//do your operations on success
}
});
});
});
</script>
You can get more details on :
jQuery
jQuery Ajax
Hope this helps you
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 have a form - textarea (named su) and submit button.
When the form is submitted, I need to
run a PHP script without refreshing/leaving page
"echo" or somehow print a return on the screen
I'm pretty sure this works via some kind of ajax request thing. but I have no idea how.
Like I said I'm uneducated with ajax or java. A quick example would be wonderful.
Simple , that is what is called AJAX. The solution is more of Javascript, than PHP.
Using Jquery, you can do it with a simple function call:
<script src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#ID_Of_Your_Button').change(function(){
$.ajax({
type: "GET",
url: "send.php",
data: "query="+document.form.textarea.value,
success: function(msg){
document.getElementById("Div_Where_you_want_the_response").innerHTML = msg }
})
});
});
</script>
Does the trick.
If your just now getting into ajax, PHP, and JQuery I would highly suggest using firefox and installing Firebug. Learn to use it and it will tell you all sorts of great things. There is not enough space to tell you everything it does, but it is ,at this point, one of my best debugging tools. Learn it, Love it and good luck.
It is usually best to use a Javascript library for doing AJAX.
See jQuery.get() for one way to send a request to a PHP web page using the jQuery library. You can have your PHP page output Javascript to be executed, or output plain text or data.
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.