1

I am having a bit of an issue with my code and I just can't pinpoint what it is. I have the following function:

var settings = {
  dataType: 'text',
  "url": "https://example.com/v1/" + <?php echo $_POST["player"]; ?> + "?limit=1",
  "method": "GET",
}

This returns my JSON in a text format that I can run REGEX on. Here I run my regex:

$.ajax(settings).done(function (response) {
  extracted = response.match(/(?=\[\{).*(?:\}\])/);
  itm = <?php echo $_POST["player"]; ?>;
  alert(extracted)

The alert is exactly the data I need and alerts just fine. My problem lies when it comes to saving. Here is my code:

$.ajax({
  type: "post",
  url: 'post.php',
  data: {json: extracted, itemid: itm},
  success: function(){
  window.location.href = "/check/";
  },
});
});

For whatever reason it only saves as a blank json file. But if I remove the regex it save just fine to my server. Am I missing something here? I feel like I have tried many things over the last 2 hours and I am at the last resort. The fact that it is JSON shouldn't matter. Even if I can save 'extracted' as text I would be happy.

If it makes a difference, here is my PHP below that saves the file.

<?php
if(isset($_POST['json']))
{
$data=$_POST['json'];
$itemid=$_POST['itemid'];
$fp = fopen($itemid.'.json', 'w');
fwrite($fp, $data);
fclose($fp);
}
?>
Jason Waltz
  • 435
  • 2
  • 10
  • 1
    I'd be more careful about sanitizing the post data. Consider this `$.post('post.php',{json:'{ "require": { "my_unscrupulous_library": "*" } }', itemid: '../../composer'})` – andrew Aug 30 '19 at 04:02
  • I'm pretty sure your issue is that `fwrite` expects a string as data, but you are passing it an array (the output of `response.match`). You need to convert that to a string using `JSON.stringify` e.g. change your post request to `data: {json: JSON.stringify(extracted), itemid: itm}` – Nick Aug 30 '19 at 04:09
  • This is actually one of the solutions I tried, the problem is now that it is in string form it adds in a bunch of back slashes to my json. Maybe it's a regex error. I am really not sure. I think I may have found some help, https://stackoverflow.com/questions/13916673/issue-with-json-stringify-adding-a-extra-and-to-my-json-object – Jason Waltz Aug 30 '19 at 04:15
  • Try using `json_encode($data)` in PHP instead of `JSON.stringify(extracted)` – Nick Aug 30 '19 at 04:23
  • var x = JSON.parse(extracted) var y= JSON.stringify(x); Was the solution. I had to parse again before stringing. Thanks a ton for pointing me in the right direction. – Jason Waltz Aug 30 '19 at 04:29

1 Answers1

0

Turns out I had to parse, then re-stringify for it to save properly. I am thankful for the push in the right direct from the comments. Thanks.

var x = JSON.parse(extracted) 
var y= JSON.stringify(x); 
Jason Waltz
  • 435
  • 2
  • 10