0

Using Jquery AJAX to read a number from a server file, increment the number, and write the number back to the server file.

I can read the file fine, I just can't post to the file.

<script>
var counter = -1;

$.ajax({
    type:    "GET",
    url:     "counter.txt",
    success: function(text) {
    counter = text;
    counter++;
        $("#count").html(counter);
    },
    error:   function() {
        $("#count").html("Error!");
    }
});

$.ajax({
    type:    "POST",
    url:     "counter.txt",
    data:    counter,
    success: function() {
    },
});
</script>
0

2 Answers 2

1

Ajax being a client-side method can't write to a file on the server.

You would need some middleware in PHP, ASP, Python etc to take the amends as posted data and write to the file.

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

Comments

0

Since Ajax is asynchronous, this piece of code

$.ajax({
    type:    "POST",
    url:     "counter.txt",
    data:    counter,
    success: function() {
    },
});

will be executed before you will get first number from server. You need to put this code inside "success" function

$.ajax(
    type:    "GET",
    url:     "counter.txt",
    success: function(text) {
        counter = text;
        counter++;
        $("#count").html(counter);
        $.ajax({
            type:    "POST",
            url:     "counter.txt",
            data:    counter,
            success: function() {
            },
        });
    },
    error:   function() {
        $("#count").html("Error!");
    }
});

Also, you should just call some server side php method through Ajax, since you can't set anything through JavaScript on server. So "post" Ajax URL should looks like url: 'http://www.server.ca/set_vars?var=var_title&value=' + encodeURIcomponent(counter)

1 Comment

Sergey, this is a nice answer... but you need to format you code correctly. Please put 4 spaces before each line with code on it.

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.