0

I was wondering if it is possible to update the value of a PHP variable on click on an HTML element. I would listen for the click with jQuery's .click() and transmit some PHP with jQuery's .ajax() or one of the jQuery ajax functions and that request would increase the variable by 10 (+=10) ?

How can I do that?

Increase the variable's value for all users when any user clicks. Kind of like a Google +1 or Facebook like button. Except a user can click more than once. and even clicks don't undo.

Is there a way to do this without a database?

6
  • why are you not using a database? Commented Jun 7, 2013 at 21:32
  • @PeeyushKushwaha because I haven't used a database thus far in developing this web app. And it would be nice not to use any databases. But it sounds like a database is the best and most secure solution. Can you show me how to do it with a database or a text file? Commented Jun 7, 2013 at 21:41
  • if this is a small application, you can do it with files. But on a large scale, databases are recomended Commented Jun 7, 2013 at 21:54
  • @PeeyushKushwaha Fine, you all convinced me to use a database. Can you show me how to do this with a database? Commented Jun 7, 2013 at 22:13
  • here's a secret for making db based apps (don't tell anyone!) : Learn MySQL language ;) Commented Jun 8, 2013 at 5:49

6 Answers 6

7

You will need to store the data somewhere. You COULD write to a text file. This is terrible in practice. The best thing to do here is use a database.

Sign up to request clarification or add additional context in comments.

Comments

2

Once the PHP renders the page, it's done, no more changes there. To update the page in real-time, you need to use JavaScript (you can use the success function of your ajax call to do it). However, to make this work for all the users, you need to keep the value of that variable somewhere - a database, or even a textfile. Database is strongly recommended. After all, that's what they are meant for.

Your ajax call needs to call a PHP function that will increase that value for you and probably echo something to denote whether it was successful. Upon that returned result, you update the existing page by using the success function, like I mentioned above.

2 Comments

Ah, okay. Could you please include some sample code on how to do this? I know of these methods and even more so now, but not how to do them. An example of how to do this with file storage would be best if you could do that.
People at Stack Overflow don't write codes/homework for others. We help by giving solutions and fixing the existing code (though you haven't provide any). There are tons of resources online - api.jquery.com/jQuery.ajax and homeandlearn.co.uk/php/php.html#MySQL, for example...
2

You can do this without a database — you could store the value in memory (memcache, redis) or a flat file.

However, an in-memory store isn't going to persist across crashes or reboots, and a file-based solution could result in hangs or delays, as only one client can have write access to the file at a time.

Why don't you want to use a database? If you don't have MySQL access, you could try sqlite.

2 Comments

I don't want to use MySQL simply because the web app I am building hasn't needed to use MySQL thus far and it would be nice if it didn't need to at all. It's part of the #NoSQL movement. I know if may sound stupid.
Well, if you have a NoSQL store (Mongo?), that's a database, too. Store the value there.
1

You can temporarily store the data in $_SESSION (http://php.net/manual/en/features.sessions.php) or in a cookie (http://php.net/manual/en/features.cookies.php). You cannot store this data permanently without a database.

1 Comment

Sessions are user specific though.
1

There are threetwo ways to do this without database.

file storage

store the value of variable in a file using file_put_contents and retrieve it using file_get_contents, increase by ten and save it again in the same file.

serialize or export

using functions var_export() or serialize() , you can store variables and arrays in files. Serialization and unserialization is more resource intensive but in terms of storage space, its more effective than exporting.

Example:

<?php
include 'data.php';
$data[$_POST['itemid']]  += 10;
$towrite = var_export($data, true); 
file_put_contents('data.php',$towrite);
?>

and here is what data.php should look like before executing the above code:

<?php
 $data = array( 'myitemid' => 0);
?>

just replace myitemid with the unique identifier the like button is on.

#sessions# you can save data in a session, but beaware , this data is short lived.

5 Comments

session would not be very useful here, as he wants the stored value to be the same for all users, while a session is user specific...
@PeterVR Yes, I don't see a session working well. As this is supposed to be for all users.
Can you show me how I could go about doing this with either, file storage, serialize, or export. In other words, could you add a sample implmentation with one of your methods to your answer?
how do I do that with the jQuery ajax function though?
How, can you show me how to a POST request with $.post() in jQuery or $.ajax() ?
1

Some options:

Option: You can use input field to store the value temporary, its faster than filesystem manipulation and do not have size limit.

Another Option: other option is using innerHTML of a div or another html element, i prefer input field because is easy to serialize and use in another ajax event and than its easy to persists. For example using json is fast and easy to save in MongoDB.

Example using input:

javascript example:

$('.classname a').click(function(e){
        $.ajax({
            url : '/foo',
            type: "POST",
            data: $("form.bar").serialize(),
            error: function(){
            },
            success : function(data){
                $('.input_class_name').val(
parseInt($('.input_class_name').val())+parteInt($('.another_input_class_name').val())
);
            }
        });
    });

html example( with 2 forms, using like this you can submit in diferent moments or put in the same form):

<form class="foo1">
<input type="hidden" class="another_input_class_name" value="10" />
</form>

<form class="bar">
<input type="hidden" class="input_class_name" value="10" />
</form>

2 Comments

If I can store it in an input field, then can't I store it in the innerHTML of any element? If so, can you update your answer so that it is stored in the innerHTML of a div.
Yes, i'll update the answer. The advantage of input field is easy to serialize and use in another ajax event

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.