Alberto Rossi
Alberto Rossi

Reputation: 1800

Save text file with PHP using Javascript code

This is the code of a simply button.

<input value="Download" type="button" onclick=" inccount();" /> 

And here this is what inccount(); does:

function inccount() {
 var a = parseInt(document.getElementById("num").value);
 document.getElementById("num").value = a + 1;
}

As you can see, this function increments by 1 the number I have on the input field num. I'd like to save this number on my server, but if I call a php script with the <form> tag, the page changes.

I want save the content of count on my server without leaving the current page. Who could I do it?

I wrote this simply PHP script for save the content of the input field (that is called num):

<?php
$file = '/dat/count.txt';
$current = $_GET["num"];
file_put_contents($file, $current);
?>

Upvotes: 0

Views: 192

Answers (2)

Gokul E
Gokul E

Reputation: 1386

You are Posting the Page to the Server. So, the Page will have changes..

You need to use AJAX request from javascript to the Server.

simply with JQuery

$.ajax(
{
    url:'/?num=' + $('#num').val(),
    type: 'GET',
    success: function(response){
        alert('Success');
    },
    error: function(e1,e2,e3){
        alert('Error occured, Could not able to make request.');
    }

});

Upvotes: 0

Andy G
Andy G

Reputation: 19367

To update a page without leaving it you need to investigate Ajax. From the linked page:

in the AJAX model, web applications are able to make quick, incremental updates to the user interface without reloading the entire browser page.

The Ajax call can be to a PHP script that writes to a text file.

Upvotes: 1

Related Questions