Saving data into a text file sent as JSON with Ajax - javascript

I have currently a problem with my code. I would like to send JSON data with Ajax to a PHP script but it doesn't work. What does work is that the PHP script can be called by the Ajax code but it can't put the code into the .txt file. I have tried several things but I can't get it working. (I am trying to set the users array in the .txt file)
jQuery code:
var users = [];
$.ajax({
type: "POST",
url: hostURL + "sendto.php",
dataType: 'json',
data: { json: JSON.stringify(users) },
success: function (data) {
alert(data);
}
});
PHP Code:
<?php
$json = $_POST['json'];
$data = json_decode($json);
$file = fopen('test.txt','w+');
fwrite($file, $data);
fclose($file);
echo 'Success?';
?>

You must know that in PHP json_decode generates an Array that you can't write into an text file.
So only remove the json_decode command.

Since json_decode() function returns an array, you can use file_put_contents() that will save each array element on its own line
<?php
$json = $_POST['json'];
$data = json_decode($json, true);
file_put_contents('test.txt',implode("\n", $data));
?>

Related

Why can't I import a var from php to js using ajax?

I'm trying to work with ajax, but I'm stuck, because I tried various things to import a var from a php file to js. What am I supposed to write after the success: function() to import $rowcount to js? I know that there are already some questions and answers on the site, but none of those seems to work...
Here's the php code:
<?php
$host = "localhost";
$user = "root";
$pw = "";
$dbName = "mathgame";
$tblName = "fragen";
// mit mysql db verbinden
$con = mysqli_connect($host, $user, $pw, $dbName);
if ($con->connect_error) {
die ("Connection failed: " . $con->connect_error);
}
// Datenanfrage an db
$result = mysqli_query($con, "select id from $tblName where Kategorie='Kategorie1'");
$rowcount = mysqli_num_rows($result);
json_encode($rowcount);
?>
And the js code:
<script id="source" language="javascript" type="text/javascript">
$.ajax({
url: 'Kategorie1.php', //the script to call to get data
data: "", //you can insert url argumnets here to pass to api.php
//for example "id=5&parent=6"
dataType: 'json', //data format
success: function(){
}
})
json_encode() returns a string but your code does nothing with the value. All you need to do is write the return value to stdout. One way to do that is:
echo json_encode($rowcount);
You would need to take in the data that is returned from your PHP script.
Add the data after success: function( for you to manipulate and use the return data.
<script id="source" language="javascript" type="text/javascript">
$.ajax({
url: 'Kategorie1.php', //the script to call to get data
data: "", //you can insert url argumnets here to pass to api.php
//for example "id=5&parent=6"
dataType: 'json', //data format
success: function(data) {
console.log(data); // outputs the json data into your console
}
})
$.getJSON("Kategorie1.php", function (data) {
var nrFragen = JSON.parse(data);
That's the js code, which worked for me, and of course at the end of the php code there should be : echo json_encode($rowcount);

Accessing PHP JSON response using Javascript

Is this valid approach: I want to keep api key from being accessible via source code so I have been trying to keep it hidden with PHP and use Javascript to display data. (I prefer to use js syntax to display data) I've been able to display data successfully but when I look at the source code I can see the JSON response. Can anyone tell me if this is a valid approach and why not good idea to have json shown in source?
<?php
$apikey = "xxxx";
$data = file_get_contents('http://url?apikey=' . $apikey);
$json = json_decode($data,true);
?>
I then access the response like so:
<script type="text/javascript">
var data = <?php echo json_encode($json) ?>;
$('.in-theaters-soon').append('<p>' + data.movies[0].title + '</p>');
</script>
You can directly echo the values from PHP since you already have the response in $json. For example:
<div class="in-theaters-soon">
<p><?php echo $json['movies'][0]['title']; ?></p>
</div>
Always make some validation of the printed data.
<?php
$apikey = "xxxx";
$data = file_get_contents('http://url?apikey=' . $apikey);
if (is_array($data) && ! empty($data)) {
/**
* Do something.
/**/
}
You could do something like this if you have the php in a separate file.
Your php file.
<?php
// create a token check to make sure it is being called.
$apikey = "xxxx";
$data = file_get_contents('http://url?apikey=' . $apikey);
echo json_encode($data);
?>
Then query your php file something like this sending a token or something similar.
$.ajax({
url: url,
type: 'POST',
data: {token:token},
success: function(data){
var response = $.parseJSON(data);
for(var x = 0; x < response.length; x++){
$('.in-theaters-soon').append('<p>' + response[x].title + '</p>');
}
},
cache: false,
contentType: false,
processData: false
});
Hope this helps.

PHP gets JSON String as array

I have a form with 17 checkboxes. When one of these changes, JavaScript should submit the values to the server (running PHP).
I want to use JSON, because the checkboxes give two arrays which have to be seperated in PHP
In JS, I create an JSON-String, which I want to submit via POST and read and decode in PHP.
The String looks like this atm: [["2015-06-26","2015-06-27"],["2","3","4","5","6","7","8","9","10","11","12","13","14"]] - This is what I want it to be.
This is, what my AJAX-function looks like:
var fullArray = [dateArray, trackArray];
var jsonFullString = JSON.stringify(fullArray);
//jsonFullString == [["a","b","c"],["d","e","f","g"]]
$.ajax({
type:'POST',
url:'shownitems.php',
data: jsonFullString,
success: function(data){
//More script. This comment is reached, because
alert(data);
// works.
}
});
When I get it to PHP, and search for $_POST[0] the success function in JS doesn't show anything. When I search for $_POST, I get "Array.." back.
This is, what my PHP looks like (This is my test snippet):
<?php
echo $_POST;
echo ".";
echo $_POST[0];
echo ".";
echo $_POST[0][0];
$array = array();
?>
I am also using jQuery.
In your JS:
/* dateArray and trackArray must be variables with values */
$.ajax({
method: "POST",
url: "shownitems.php",
data: { date: dateArray, track: trackArray }
}).done(function(response) {
alert(response);
});
In your PHP:
<?php
var_dump('Date: '.$_POST['date']);
var_dump('Track: '.$_POST['track']);
?>
You should get your request content instead the $_POST variables.
Something like this would
$json = file_get_contents('php://input');
$obj = json_decode($json); //Will contain your array of two arrays
In case you wanted to get your post variables like you are doing, you could change your AJAX request and use:
$.ajax({
type:'POST',
url:'shownitems.php',
data: {
data: jsonFullString
},
success: function(data){
//More script. This comment is reached, because
alert(data);
// works.
}
});
And your PHP would be:
$json = $_POST["data"];
$obj = json_decode($json); //Will contain your array of two arrays

How to read data from in Javascript

I'm trying to use Javascript to read stock data from yahoo finance at "http://table.finance.yahoo.com/table.csv?s=000001.sz", which returns a csv file and convert the data into json format as in http://www.highcharts.com/samples/data/jsonp.php?filename=aapl-ohlcv.json&callback=? to be used in highcharts.
I tried using $.ajax get and jquery.get but neither worked. Can somebody tell me how to read the data from the url and convert it into json? Thanks a lot.
This can be easily done with PHP.
<?php
file_put_contents("data.csv", fopen("http://table.finance.yahoo.com/table.csv?s=000001.sz", 'r'));
//reads the CSV file and save value into an associative array
function csv_to_array($filename = '', $delimiter = ',')
{
if (!file_exists($filename) || !is_readable($filename))
return FALSE;
$header = NULL;
$data = array();
if (($handle = fopen($filename, 'r')) !== FALSE) {
while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE) {
if (!$header)
$header = $row;
else
$data[] = array_combine($header, $row);
}
fclose($handle);
}
return $data;
}
$arr = csv_to_array('data.csv');
//<pre></pre> tags appear only to prevent white-space collapsing
//prints the associative array
echo "<pre>";
print_r($arr);
echo "</pre>";
//displays the the JSON
echo "<pre>";
echo json_encode($arr, JSON_PRETTY_PRINT);
echo "</pre>";
?>
Now depending on the format of JSON that it acceptable to Highcharts API, you are required to tweak how the array is encoded into JSON.
Also avoid using JSON_PRETTY_PRINT if the size of the incoming data is large.
I guess you are facing Cross Domain issue. Use jsonp calls for Cross Domain requests. Use something like this
$.ajax({
url : "http://xx.xx.xx.xx/xxx/xxx",
type: "GET",
dataType: "jsonp",
jsonp : "callback",
success: function(data) {alert("Success");},
error: function(data) { alert("Error"); }
});
});

How to send multiple data from PHP to JavaScript

I don't know how to make a script for sending multiple variables from external php to javascript (jQuery)
For exemple:
<?php
$test = "tets"; -->this, I want something this, no echo
$dock = "dock"; --
echo $test; -->no, I don't want echo in PHP script
echo $dock; -->no, I don't want echo in PHP script
?>
and JS
<script>
function(){
$.post("url", {Some_Thing: "Some_Thing"}, function (data) {
alert(data); --> no, I don't want echo in PHP script
alert($test); --> this, I want something this, no echo
alert($dock);
}
}
</script>
Use a data structure, e.g:
<?php
$data = array('test', 'dock');
echo json_encode($data);
Then in your JS
$.post('url', {...}, function (data) {
alert(data[0]);
}, 'json');
^^^^^^^^--- tell jquery you're expecting back some json
you can just output your data in JSON format and then load the data to JavaScript using ajax like so:
<?
$arrayWithData = array('data1' => 123, 'data2' => 555);
echo json_encode($arrayWithData);
then call load the data using ajax:
$.ajax({
'url' : 'php-data-script.php',
'method' : 'get',
'dataType' : 'json'
}).done(function(data) {
// do whatever you want with the data
console.log(data);
});

Categories

Resources