0

I would like to declare in javascript two object stored in a file.txt and use it in a code.

For example I wrote this in my index.php:

 var counter = Number(localStorage.getItem('rans')) || 0;
 var counter1 = Number(localStorage.getItem('bans')) || 0;

$('.redanswer').one('click', function(){
     localStorage.setItem('rans', ++counter);
     $( '.rtotal' ).text( counter + " concordano" );
     $( '.btotal' ).text( counter1+ " non concordano");
     $('.rgraphic').css("height", counter * 100 / (counter1+counter));
     $('.bgraphic').css("height", counter1 * 100 / (counter1+counter) );
});

$('.blueanswer').one('click', function(){
      localStorage.setItem('bans', ++counter1);
      $( '.btotal' ).text( counter1 + " concordano" );
      $( '.rtotal' ).text( counter + " non concordano");
      $('.rgraphic').css("height", counter * 100 / (counter1+counter));
      $('.bgraphic').css("height", counter1 * 100 / (counter1+counter) );
});

As you can see, in this example, the items bans and rans are stored in the localStorage and I used those items for the counters. I would like to write exactly the same code but with the new bans and rans stored in my file.txt. I think this had to be done with AJAX but I don't know.

I think the file.txt has to be wrote like this:

bans: 1; //casual number
rans: 5;  //casual number

I hope you understand, Thank you very much.

3
  • 1
    It can be done with AJAX, which I think means you need to read a book or find some tutorials Commented Feb 5, 2016 at 15:48
  • I can't found nothing on youtube, and I can't understand how to insert the code I need in my code. Commented Feb 5, 2016 at 15:50
  • YouTube is not the only resource out there, but GOOGLE will find almost anything if you try it Commented Feb 5, 2016 at 15:56

3 Answers 3

1

It could be done with ajax but it can also be done without

index.php

<?php
    // read your file.txt
    // strip off the comments
    // get the value part of bans: 1 into a variable $bans
    // get the value part of rans: 5 into a variable $rans

// for testing
$bans = 1;
$rans = 5;

echo '<script>';
echo "var master_bans = $bans;";
echo "var master_rans = $rans;";
?>

var counter = Number(localStorage.getItem('rans')) || master_bans ;
var counter1 = Number(localStorage.getItem('bans')) || master_rans;

$('.redanswer').one('click', function(){
     localStorage.setItem('rans', ++counter);
     $( '.rtotal' ).text( counter + " concordano" );
     $( '.btotal' ).text( counter1+ " non concordano");
     $('.rgraphic').css("height", counter * 100 / (counter1+counter));
     $('.bgraphic').css("height", counter1 * 100 / (counter1+counter) );
});

$('.blueanswer').one('click', function(){
      localStorage.setItem('bans', ++counter1);
      $( '.btotal' ).text( counter1 + " concordano" );
      $( '.rtotal' ).text( counter + " non concordano");
      $('.rgraphic').css("height", counter * 100 / (counter1+counter));
      $('.bgraphic').css("height", counter1 * 100 / (counter1+counter) );
});
</script>
Sign up to request clarification or add additional context in comments.

1 Comment

@NiccolòGuidi - This is a good answer. Just remove the localStorage calls if you don't want them and it will still work, e.g., var counter = master_bans;
1

RiggsFolly's solution, which does the work on the server side, seems the best approach. (up voted)

However, another alternative is to simply load the file using a script tag as shown below.

The content of file.txt is:

var config={"rans":10,"bans":20};

Page:

<html>
<head>
    <script type="text/javascript" src="file.txt"></script>
</head>
<body>
<script type="text/javascript">

     var counter =  config.rans;
     var counter1 = config.bans;
     alert( 'counter: ' + counter + ', counter1: ' + counter1 );

     // the rest of your code here

</script>
</body>
</html>  

The values in file.txt could be modified using an editor, PHP function, or some javascript like so:

  // write file.txt
  var xhr = new XMLHttpRequest();
  xhr.open('PUT','file.txt', true);
  xhr.setRequestHeader('Content-Type','text/javascript; charset=utf-8');
  xhr.send( 'var config={"rans":' + counter + ',"bans":' + counter1 + '};' );

2 Comments

How can I edit permanently the file.txt? I want to replace the text in file.txt with 'var config={"rans":' + ++counter + ',"bans":' + ++counter1 + '};'
@NiccolòGuidi - From your example, it appears you want to increment and store the new values to the file. Correct? Then what event and conditions should cause the update? If you can provide more information then I will provide a suggestion and example.
0

You are correct, you will need to use AJAX to get that data out.

$.ajax({
  type: 'GET',
  url: 'file.txt',
  dataType: 'json',
  success: function(data) {
    if (data.result === 'error') {
      //show an error message
    return false;
    } else {
     console.log(data);
     bans = data.bans;
     rans = data.rans;
    }
  }
});

This is typical AJAX code I use. If you can store whatever data is in file.txt as an array in PHP it might be easier to work with. So for example your file.php that you're calling to from AJAX could looks like this:

<?php
$bans = array(); //your bans data here
$rans = array(); //your rans data here

try {
  echo json_encode(array('result' => 'success', data => array('bans' => $bans, 'rans' => $rans)));
} catch (Exception $e) {
    echo json_encode(array('result' => 'error', 'message' => $e->getMessage()));
    exit();
}

This may not be the best for your set-up, but I hope the information helps you.

2 Comments

Is it still considered Ajax when async = false ?
@Roberto: Good question. That snippet was from an older piece of code I had sitting around. Setting async to false is a deprecated method. @NiccolòGuidi: Put that $.ajax section under something like $('.blueanswer, .redanswer').on('click, function() { //ajax here })

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.