1

I have a textarea and this javascript code It should work but dosen't is there something wrong? If so, what is it?

$('#text').load("http://hokuco.com/test/xe7/user.txt");
<form action="formcode.php" method="POST">
<textarea name='field2' placeholder='Code here' rows ="40" cols="40" id ="text"></textarea>
<br />
<input type="submit" name="submit" value="Save">
</form>

here is my php file if curious:

<?php
if(isset($_POST['field1']) && isset($_POST['field2'])) {
    $data = $_POST['field1'] . '-' . $_POST['field2'] . "\n";
    $ret = file_put_contents('code.txt', $data, FILE_APPEND | LOCK_EX);
    if($ret === false) {
        die('There was an error writing this file');
    }
    else {
        echo "$ret bytes written to file";
    }
}
else {
   die('no post data to process');
}
?>
parseguy
  • 129
  • 2
  • 17

4 Answers4

2

Due to browser security restrictions, most Ajax requests are subject to the same origin policy; the request can not successfully retrieve data from a different domain, subdomain, port, or protocol.

I'm assuming the .txt file is not on the same server/domain as the HTML file that is trying to load it? If you are, then you should use a relative URL, i.e.:

$('#text').load("xe7/user.txt");

Please refer to: Loading cross domain endpoint with jQuery AJAX

Community
  • 1
  • 1
Laurens Swart
  • 1,234
  • 9
  • 24
0

Does this work?

jQuery

$(function(){


  $.ajax({
    url : "http://hokuco.com/test/xe7/user.txt",
    dataType: "text",
    success : function (data) {
      $("#text").html(data);
    }
  });


});

HTML

<div id="text"></div>
Timo
  • 727
  • 5
  • 15
  • jQuery's load() function doesn't need a datatype. There is nothing wrong with his code, it's just that he's 'violating' the same origin policy. – Laurens Swart Feb 02 '16 at 15:45
0

As other users have said, you are violating the same origin policy. If you are using PHP you could echo that into your textarea.

Something along the lines of:

<textarea id="text">
    <?php 
        $text = file_get_contents('http://hokuco.com/test/xe7/user.txt');
        echo $text;
    ?>
</textarea>
Duncan Tidd
  • 1,140
  • 10
  • 13
0

If the above code is all there is (as you state in your comment to your question), and you have included jQuery, then mere refreshing of the page won't give you the result. As your HTML code is below this jQuery call, the DOM is not ready yet when the function is called. Therefore you need to call this function when the document is ready, according to the rule that all jQuery calls that relate to DOM elements should be made this way:

$(document).ready(function(){
    $('#text').load("test/xe7/user.txt");
});
n-dru
  • 9,285
  • 2
  • 29
  • 42