Running a PHP script via Ajax, through a link? - php

I'm making a fairly simple rating system, and I've got a small problem. When you +1 rate something, I'm trying to run a PHP script which will connect to the database, download the value from it, +1 to that value, and UPDATE the value in the database again.
I don't think reloading the page for a continious rating system would be a very good idea :S
I'm wondering how I can toggle a PHP script with Ajax, so that when you Click an image of a + sign, it runs the PHP add 1 script, and the + button turns in to a tick. I'm crap at ajax, and I'd go for trying jQuery + $.ajax({}); but I've failed 73 attempts. haha.
Anyone willing to give me a hand writing an Ajax script? :DDD
Thanks! :)

If you want someone to click a link which will access your page, let's assume you have this marup:
<a class = 'plusOne' id = 'someIDForYourSQLTable'>+1</a>
The ID is what you are going to pass to your server script so you can update the appropriate row, generally speaking this should be a primary identifier (i.e. Key) for the record that you want to +1.
Here is the jQuery that will send the ajax request to the file: plusOne.php in the same directory as the current page:
$(function() {
$(".plusOne").bind("click", function() {
$.ajax({
type: "GET",
data: "v="+$(this).attr("id"),
url: "plusOne.php",
success: function(data) {
// Whatever you want to do after the PHP Script returns.
}
});
});
});
The request will send the a URL parameter 'v' which you can access in your PHP script from the $_GET super global array.

html
<img src="plusone.png" rel="some_unique_id" class="rate" />
javscript
$(".rate").click(function() {
var elem = $(this);
$.get('/rate.php?id=' + elem.attr('rel'), function() {
elem.attr('src', 'checked.png').unbind('click');
});
});
and in php
mysql_connect('localhost','db_user','pssword');
mysql_query('UPDATE database_name.table_name SET rating=rating+1 where id=' . mysql_real_escape_string($_GET['id']));

Have a look at xAjax, a library to expose PHP functions/method to client-side JavaScript. xAjax makes things very simple.
For example, you are able to perform several changes in the browser in parallel:
$objResponse = new xajaxResponse();
$objResponse->assign("myInput1","value",$DataFromDatabase);
$objResponse->assign("myInput1","style.color","red");
$objResponse->append("myDiv1","innerHTML",$DataFromDatabase2);
$objResponse->prepend("myDiv2","innerHTML",$DataFromDatabase3);
$objResponse->replace("myDiv3","innerHTML","xajax","<strong>xajax</strong>");
$objResponse->script("var x = prompt("Enter Your Name");");
return $objResponse;

Related

AJAX Updating Javascript Variable from PHP page?

I am not a developer so this is new to me, but I am a long time sys admin so please forgive me if I am asking stupid questions!
Basically, I have a PHP script that parses some XML and echo's a single number formatted to 1 dp.
I am using some Javascript Wijmo widgets, in particular a dial that takes it input from a javascript variable. Lets say "resultvalue".
I want to populate "result value" every 5 seconds with the results of my php script that exists as /xmlparse.php. The wijmo widget apparently responds dynamically to a changing variable so this will produce a dial with a moving needle without having to refresh the whole page.
All I need to achieve is getting this javascript variable to update every 5 secs.
I am already doing something similar with AJAX on a html page by just populating a DIV with the results of /xmlparse.php and it works great using the set interval command.
But how can I get my javascript variable updating every 5 secs with the result of that script?
An example would be a great help!
Code Here
Regards
Tom
window.setInterval(function(){
jQuery.ajax({
url:'/xmlparse.php'
}).done(function(response) {
resultvalue=response;
});
},5000);
You'll probably need to parse the result. Perhaps xmlparse should format it with json_encode so your ajax request could grab it as an object.
Edit:
Looking at your source, I see that the radial gauge doesn't actually monitor the resultvalue variable to detect when it's changed. You'll have to update it yourself. In this case:
window.setInterval(function(){
jQuery.ajax({
url:'/xmlparse.php'
}).done(function(response) {
resultvalue=response;
$("#gauge").wijradialgauge({value:resultvalue});
});
},5000);
You can set a global variable and set it as value returned from xmlparse.php;
var resultValue;
// load at page load first
$(document).ready(function() {
updatevalue();
});
setInterval("updatevalue()", 5000);
function updatevalue(){
$.get("xmlparse.php", function(response) {
resultValue = response;
})
}
This is for test
setInterval("test()", 4000);
function test() {
console.log("Result is: " + resultValue);
}

Refresh PHP functions with JavaScript

i need a a script that will refresh the functions:
$ping, $ms
every 30 seconds, with a timer shown,
i basicly got this script:
window.onload=function(){
var timer = {
interval: null,
seconds: 30,
start: function () {
var self = this,
el = document.getElementById('time-to-update');
el.innerText = this.seconds;
this.interval = setInterval(function () {
self.seconds--;
if (self.seconds == 0)
window.location.reload();
el.innerText = self.seconds;
}, 1000);
},
stop: function () {
window.clearInterval(this.interval)
}
}
timer.start();
}
but it refreshes the whole page, not the functions i want it to refresh, so, any help will be appriciated, thanks!
EDIT:
I forgot to mention that the script has to loop infinatly
This here reloads the whole page:
window.location.reload();
Now what you seem to want to do is reload portions of the page, those portions having been generated by php functions. Unfortunately php is server side so that means you cant get the client browser to run php. Your server runs the php to generate stuff that browsers can understand. In a web browser open a page you made using php and choose to view source and you'll see what I mean.
Here's what you'll need to do:
Make your two functions ping and ms accessable via ajax
Instead of window.location.reload() do a call to jQuery.ajax. on success write to your page
Here's what I think would be the ideal way of dealing with this... I haven't seen the php side of your problem but anyway:
make a file called ping.php and put all your ping function code in there. ditto for ms
in your original php file that called those functions, make a div at each point where you wanted a function call. Give them appropriate ids. Eg: "ping_contents" and "ms_contents"
You can populate these with some initial data if you want.
In your js put in something like this:
jQuery.ajax(
{
url : url_of_ping_function,
data : {anything you need},
type : 'POST', //or 'GET'
dataType: 'html',
success : function(data)
{
document.getElementById("ping_contents").innerHTML = data;
}
});
do another one for the other function
What you want is AJAX, Asynchronous JavaScript and XML
You can use jQuery for that.
I can put an example here, but there is a lot of information to be found on the internet. In the past I wrote my own AJAX code, but since I started using jQuery, it's all a lot easier. Look at the jQuery link I provided. There is some usefull information. This example code might be the easiest to explain.
$.ajax({
url: "test.php"
}).done(function() {
alert("done");
});
A some moment, for example on a click on a button, the file test.php is executed. When it's done, a alert box with the text "done" is shown. That's the basic.

Dynamic jquery pages

I didn't really know what to call this so I couldn't find anything by searching. Pretty much I have the following:
$(document).on('click', 'a[data-ajax]', function(e) {
var box = $('#ajaxdata');
e.preventDefault();
var r = $(this).attr('href');
$.ajax({
type: 'post',
url: '/betasite/' + r,
success: function(data) {
box.html(data);
}
});
});
Pretty much it loads the contents of a file (being some html) into a div so the page doesn't need to reload data as often. The problem is having is that I want to have some php inside that loaded file so I can access server side MySQL data and display it. Whenever I try to do this however, it comments the php out like <--php (stuff) -->. Does anyone know how I can work around that (like having the php generate the page before its loaded)?
Your php code will be rendered by server(WAMP/MAMP) automatically if you are on a local environment. If you are not running a server(WAMP/MAMP) you will have to select one depending on the O/S you use.
a good practice is to test the operation of the service in this case "php", before trying the operation in the front-end (jquery). If you have an Apache server up should see the result of their service by accessing the service route.

Image wont change

I am trying to get the image links from 9gag (what also works) and when I click on a button the image changes to the next one. The basic problem is that it works only once. I can then switch between the 1st and the 2nd image, though. This should be pretty simple, but I ´ve got no clue where the error is, so thanks in advance to anyone bothering to look at this.
<?php
$index = 0
$html = file_get_contents("http://www.9gag.com");
preg_match_all( '|http://d24w6bsrhbeh9d\.cloudfront\.net/photo/.+?\.jpg|', $html, $gags);
?>
<script>
function nextImg(){
<?php $index++;?>
pic.src='<?php echo $gags[0][$index];?>';
}
function prevImg(){
<?php $index--;?>
pic.src='<?php echo $gags[0][$index];?>';
}
</script>
You can't increment your PHP variables after the page has loaded. You are trying to increment them client-side with JavaScript. You are going to need to call that PHP using AJAX if you want to do this without refreshing the page, and even then you'll want to increment a javascript variable to keep track of where you are.
EDIT: I went a little nuts creating an ajax routine using PHP and JavaScript, specifically the jQuery library, which you will need to link to for this to work. You may also need to modify parts of the script to work with what you're trying to accomplish, but this certainly is a guide for running your ajax app as you're hoping to.
Start by making a PHP file with this script:
<?php
// Set content header to json
header('Content-Type: application/json');
// Get the index from the AJAX
$index = $_GET['index'];
// Grab file contents & parse
$html = file_get_contents("http://www.9gag.com");
preg_match_all( '|http://d24w6bsrhbeh9d\.cloudfront\.net/photo/.+?\.jpg|', $html, $gags);
// Send filename back to AJAX script as JSON
echo json_encode(array($gags[0][$index]));
?>
Then, in your HTML, include this jQuery to complete AJAX calls to your PHP script, and update the DOM with the data from the PHP script.
<script>
$(function() {
'use strict';
// Initiate index variable
var index = 0;
// Load initial image
loadImage(index);
// Add click event to a button with class of next-btn
$('.next-btn').click(function(e) {
e.preventDefault();
// Increment index to get next image
index++;
// Run AJAX function to retrieve image
loadImage(index);
});
// Add click event to a button with class prev-btn
$('.prev-btn').click(function(e) {
e.preventDefault();
// Decrement the index if it isn't 0
if (index > 0) {
index--;
}
// Run AJAX function to retrieve image
loadImage(index);
});
});
function loadImage(index) {
'use strict';
$.ajax({
type: 'GET',
url: 'your-php-script.php', // Filepath to your PHP script
data: 'index='+index, // Index is passed through GET request
dataType: 'json', // Return JSON
success: function (data) { // If the php script succeeds
// Change img with class of pic's src
// to the filename retrieved from php
$('.pic').attr('src', data[0]);
}
});
}
</script>
Configuring this for your needs will require some serious PHP and jQuery/JavaScript knowledge, as some debugging will likely be needed. Good luck!
EDIT 2:
I uploaded the working (tested, it works) source files to my website if you want to download. Please accept answer and let me know you grabbed the files...
http://www.wedgewebdesign.com/files/ajax-image-loader.zip
#Eric basically has it right but didn't really go into detail if you aren't familiar with the model...
PHP is a server side language in that it does all its processing on the web host server and once it is complete sends a static result back to the user. This means, whatever you see after the page is loaded within PHP is there to stay, unless you do one of two things:
1) Send a new request -- You provide different parameters, the page re-executes its logic and returns a new result to the user
2) Execute some form of clientside Javascript. Javascript is different from PHP in that it executes on the client (not the server) so you don't necessarily have to send responses back to the server unless you need more information. Javascript and PHP can be combined to create AJAX calls which allow the client to make asynchronous calls to the webserver for more data without reloading the entire page. The Javascript handles re-drawing the new information or updating the page which can appear seamless to the user.
What you therefore need is one of those two options. Either you provide 'next'/'previous' links to the user and the page is loaded differently each time or you create an AJAX call that fetches the url of the next image and then loads it.
Try assigning a variable to $gags[0][$index]. Something like
$imgsrc = $gags[0][$index];
and then
pic.src='<?php echo $imgsrc; ?>';

Determining which key is pressed and saving to database

I have a code which is helping for determining which key is pressed. But I confused, I do not know how can I save this key -(button) is pressed-. Is this possible? Can I use php codes in javascript to create a new line in my mysql database?
<script type="text/javascript">
function textsizer(e) {
var evtobj = window.event ? event : e;
var unicode = evtobj.charCode? evtobj.charCode : evtobj.keyCode;
var actualkey = String.fromCharCode(unicode);
if (actualkey == "a") {
//database code needed
}
}
document.onkeypress = textsizer;
</script>
Your main problem is that JavaScript is a client-side language (it runs in the browser running on the user's computer) and PHP is a server-side language (it runs on your web server). You can't mix the two together because they run at different times.
What you could do is use is AJAX to send requests from your JavaScript code to your web server, without navigating away from the page, whenever a key is pressed. You'd simply send a key code (or the character that key code represents) as a parameter of the request, then your web server would handle saving that information to your database.
Here is some code that might help you get the ball rolling. I'm opting to use jquery, it will make this much more straight forward.
window.bind('keydown', function(event){
$.ajax(
{
url: 'http://asite.com/script_to_save_codes_to_db.php',
data: event.keyCode,
type: 'POST',
success: function (data){
//have the server respond with a boolean indicating that the keycode was saved to the db or not and decide what to do next
}
}
);
});
How this works on the server side is a whole 'nother can of worms as it will depend on your server-side language and database choices.
For an entirely client-side solution you could save the keyCodes as a json string to localStorage or a cookie and do what you want with it later... But those can be wiped at any time and I would not call them databases.

Categories