Use AJAX call to update a php session variable - php

I have a PHP script that reads PDF files in a specified folder. I have each file split by page. I have stored these file names in an array and have created an index variable called $count. There are left (page down) and right (page up) arrows. I need $count to increment on page down and decrement on page up. I know I need to use AJAX to do this, but the only data I have to send is the onclick event.

Perform an ajax request sending your action as a parameter :
JQuery.ajax({
url: 'my_script.php?action=increment'
});
Then in my_script.php, update your session variable according to the parameter action.
I used jQuery for my example but any other library will do just fine.

jQuery's $.ajax() function is used to perform an asynchronous HTTP request.
here is a demo code to interact with php file
$.ajax({
type:'POST',
url:'contact_form.php',
data:'details='+Message,
success:function(msg){
$('#show-msg').html('<span >'+msg+'</span>');
}
});

The onclick event should be enough to send.
Technicly you just need to send to your server what button has been pressed and from there your variable in your session will go down or up according to whats the php logic receiving the ajax call.
So just make a simple php page that does something like this
if(isset($_REQUEST['Down']))
$count --;
if(isset($_REQUEST['Up']))
$count ++;
And on your page were you actually click the buttons
Just have a regular ajax call like so,
$("#UpButton").click(function(){
$.post('linkToYourPage.php',{Up:true});
});
$("#DownButton").click(function(){
$.post('linkToYourPage.php',{Down:true});
});

Related

should jquery ajax go to the same page or another php file?

My Current Setup
my sites home page (rankings.php) shows a list of users with a search form at the top to filter users by their gender or city.
I want to use jquery ajax to update the results without reloading the page.
My Question:
with either method (load,post,get) you need to enter the url to send the request to but I'm not sure if the url should be the rankings.php page itself or another php file that holds the mysql query to get new results from the database. Which is best? should ajax requests go to another php and then the results sent back to the main php file where the content will be reloaded or should the ajax request go to the same php file it came from and then jquery to replace the content with the returned html data?
shorter version of question: should ajax url point to the page the ajax request comes from or point to another php file and then the data returned back?
It should point to the URL of the script that performs whatever function you need the AJAX request to do. It can be the same or a different URL from the page that contains the caller. If it's the same page, you'll need to put conditionals in the script that detects whether it's being used to process an AJAX request or to display the regular page, usually by checking the parameters.
For instance, you might send the AJAX request with:
$.ajax({
url: '<?php echo $_SERVER['PHP_SELF']; ?>',
type: 'post',
data: { action: 'dosomething', ... },
...
});
Then in the PHP script, you would do:
if (isset($_POST['action']) {
// code to process AJAX request
} else {
// code to display the page HTML
}
I generally find it simpler to put the AJAX code in a separate script, so I don't have to do that.

jQuery AJAX vs PHP in HTML attribute

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.

Passing values from ajax page to calling page javascript function

One part of my page is being loaded via ajax using jquery. For example this initial page has a name first.php. It has a div with it's innerHTML generated from ajax called script (for example ajax is calling second.php). Is it possible to pass some values from ajax executed script (second.php) to original site. I need to access this value from original site (the one calling second script via ajax) javascript function, and I don't want to use hidden fields.
For example, my site has some captcha that is being displayed and processed through ajax. I don't want to write captcha result to some hidden field and access it with original site javascript function because of possible javascript injection attack...
Since you call your secound.php script via ajax, you surely could read the result.
$.ajax({
url: 'secound.php',
success: function(data) {
// now data contains the code returned by secound.php
}
});
Now the most common way to return data from your secound.php script is returning it in JSon format. Then you could do someting like:
var obj = jQuery.parseJSON(data);
alert(obj.name);
For this example your secound.php needs to return
{"name":"John"}

Send data to database when click on a link without page refresh

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.

How can I add a simple counter function in javascript jquery?

I'm using Shadowbox a jquery overlay and I wanted to count how many people are actually using the overlay. Thus, I would need a function that would write a counter to a file or sending a query through a php api...
has to be a a php url api because I cant use php on the server where the overlay is.
So I need help with executing a javascript function on the overlay click, tips on how to make a counter query through GET method.
Thanks
<script type="text/javascript">
Shadowbox.init({
handleOversize: "resize",
overlayOpacity: 0.9
});
When you bind your click handler to open the shadownbox, add a binding for an ajax call, such as this:
$.ajax({
type: "GET",
url: "stats.js",
data: "name=urlOrNameOfItem"
});
Replace urlOrNameOfItem with something meaningful so you can track what has been clicked. I assume you know in php how to handle a query string.
See JQuery docs: http://api.jquery.com/jQuery.ajax/
Before you display your Shadowbox throw an Ajax query to a php script which would save the current request in a db (including $_SERVER info for better analysis).
This PHP script can fetch the current count of views for that image from the Db and update it accordingly.
I'm guessing the shadowbox function is called as a onclick event on your image so just add the Ajax call something like this:
$.ajax({
url: 'path-to-counter-script.php?i='+image-identifier,
success: function() {
//display shadowbox
}
});

Categories