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.
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
This question already has answers here:
Closed 11 years ago.
I have a javascript function I would like to run on a page, that when executed will send a variable to a PHP script but not open the PHP page just stay on the current page.
What I am trying to do is add this function to pages on a website and for it to return information about the page it was run on, such as URL and user IP.
Everything I have tried so far has not done the job, so any info is appreciated.
Many thanks
Thanks Quentin, but I have tried to javascript forms, but they all open the url the form is being posted to. My most recent example:
var form = new Element('form',
{method: 'post', action: 'http://www.site.com/data.php'});
form.insert(new Element('input',
{name: 'u', value: ""+u, type: 'hidden'}));
$(document.body).insert(form);
form.submit();
I also tried:
document.location.href='http://www.site.com/data.php?u='+u;
but again this open the page :S
For those that have suggested AJAX, thank you but it wont work because that needs a script link in the header and I need to be able to plug this into a page without editing the header. I did try to dynamically insert it via the javascript function, it went in OK but none of the AJAX functions would execute.
What you are looking for is called AJAX (Asynchronous Javascript and XML). These type of calls in Javascript are made trivial with things like jQuery.
This is what jQuery's website says about AJAX: The jQuery library has a full suite of AJAX capabilities. The functions and methods therein allow us to load data from the server without a browser page refresh.
And an example jQuery POST:
$.post('ajax/test.html', function(data) {
$('.result').html(data);
});
Using jQuery
for simplicity do something like this
$.ajax('foo.php',function(d){ alert(d); });
Hi I have web service that is written in php that outputs my data in xml format. I need that data to be send to an html page where I use javascript to display it. I want to know to how call that php service from my html page using javascript?
You can use JSON and PECL for data transfer with php
JSON
http://www.json.org
Scroll down to the page to see some options that you have for PHP.
If you wanted to do something fast and simple, you can use the jquery get or post call to acheive the disired result:
jQuery GET:
http://api.jquery.com/jQuery.get/
The get and the post both have a call-back function which can be used to accept the result of loading your php page and then you can determine how to display it.
You should have a way or create a way to access that by going to a specific URL. So just create some JS that will call that URL. Best to use JQuery to make things easier. Then just manipulate the data all you want.
Try that .ajax function from JQuery. There are some great examples at http://visualjquery.com/. You can also get more details on it from http://api.jquery.com/jQuery.ajax/
Example:
var html = $.ajax({
url: "some.php",
async: false
}).responseText;
You could also use JQuery's load function:
$('#result').load('ajax/test.html');
How about something like this using jQuery's load()?
$('#result').load('http://myWebService/serviceName.php');
<div id="result"/>
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.