Kim
Kim

Reputation: 1156

Jquery AJAX Save to file

Everthing here works fine except that in the saved file it doesn't give me the whole string. Just one of the IDs (There are multiple on the page).

Not sure how get "all of the IDs and Content" in the $.ajax()

What am I doing wrong?

Have got this jquery:

$('a#exportPage').on('click',function(){
var contentMap = {};
$('[id^="appendHeading"]').each(function(){
    contentMap[this.id] = $(this).text();
});
for(id in contentMap)
    $("#PrintIds").append("ObjectID:" + id + "Content:" + contentMap[id]);

$.ajax({
  url: "post.php",
  type: "post",
  data: { 
      objectID: id,
      content: contentMap[id]
      },
      success: function(){
      alert("success");
  },
  error:function(){
      alert("failure");
  }   
 }); 
});

And this PHP:

<?php
if ($_POST['objectID'] || $_POST['content']) {
$myFile = "test.css";
$stringData = $_POST['objectID'] || $_POST['content'];
file_put_contents($myFile,$stringData);
}
?>

Upvotes: 1

Views: 3347

Answers (1)

vher2
vher2

Reputation: 990

You forgot to enclosed the for loop into { and }.

$('a#exportPage').on('click',function(){
var contentMap = {};
$('[id^="appendHeading"]').each(function(){
    contentMap[this.id] = $(this).text();
});
for(id in contentMap) {
    $("#PrintIds").append("ObjectID:" + id + "Content:" + contentMap[id]);

    $.ajax({
        url: "post.php",
        type: "post",
        data: { 
            objectID: id,
            content: contentMap[id]
        },
        success: function(){
            alert("success");
        },
        error:function(){
            alert("failure");
        }   
    }); 
}
});

The content should be appended to the end of the file:

<?php
if ($_POST['objectID'] || $_POST['content']) {
    $myFile = "test.css";
    $stringData = $_POST['objectID'] . ':' . $_POST['content'] . "\n";
    file_put_contents($myFile,$stringData,FILE_APPEND | LOCK_EX);
}
?>

Upvotes: 1

Related Questions