Save to server side file from PHP via Javascript - javascript

I am trying to save a json string from a javascript file to a local file on the server using PHP, however, my json file is not being modified at all.
Here is my Javascript:
function saveToFile(data){
jsonString = JSON.stringify(data);
$.ajax({
url: 'php/save.php',
data : jsonString,
type: 'POST'
});
}
Note that jsonString is a valid variable, and i can log it correctly into the console.
Here is my PHP:
<?php
$data = $_POST['jsonString'];
$f = fopen("../website-contents.json", "w") or die("fopen failed");
fwrite($f, $data) or die("fwrite failed");
fclose($f);
?>
Note that even tests trying to save "Hello World" to "test.txt" don't work, or through errors.
Finally, here is my folder structure:

Here is your solution.
Js code
function saveToFile(data){
jsonString = JSON.stringify(data);
$.ajax({
url: 'php/save.php',
data : {'jsonString':jsonString},
type: 'POST'
});
}
php code.
$data = $_POST['jsonString'];
//set mode of file to writable.
chmod("../website-contents.json",0777);
$f = fopen("../website-contents.json", "w+") or die("fopen failed");
fwrite($f, $data);
fclose($f);

I agree with the comments pointing out you must have a permission problem. However, it will not work after you have corrected this problem either. You have
$data = $_POST['jsonString'];
but where do you set a key called jsonString? Use
function saveToFile(data){
var jsonString = JSON.stringify(data);
$.post("php/save.php", {
jsonString: jsonString
})
}
instead.

Related

Try to use the getJSON function but it's not returning anything

This is my getJSON:
$(function () {
var neededData;
$.getJSON('/ajax/connected-devices-data.php', function(jsonData) {
neededData = jsonData;
console.log(neededData);
});
});
And this is my php:
use NET2GRID\Data\CurrentlyConnectedDevices;
require_once __DIR__ . "/../vendor/autoload.php";
header('Content-type: application/json; charset=utf-8');
$cd = new CurrentlyConnectedDevices();
$data = $cd->getConnectedDevicesFromDatabase();
print json_encode($data);
When I look at my site where I run this the console remains empty but according to what I'm used to there should be a json object there.
This is the jsonresponse I get from the php code when I run it individually:
{"SUCCESS":[[1493642582000,912],[1493718591000,909]],"PING_NOT_RECEIVED":[[1493642582000,631],[1493718591000,635]],"TCP_CNX_FAILED":[[1493642582000,7],[1493718591000,7]]}
What am I doing wrong in this code?
Try following AJAX code..
$.ajax({
method: "GET",
url: "/ajax/connected-devices-data.php"
}).done(function( response ) {
alert( "Response received: " + response );
});
--- UPDATE ---
Above code was not the solution of the question asked. It was the error on the web server which has not configured properly with PHP.

Wrong charset from AJAX

When I want to printout the output of jQuery AJAX, which has been recived from server. It doesn't show the right charset. What I want exactly is to get š instead I am getting ? or without using utf8_decode() when sending data from server, I get ĹĄ. All files script.js and server php proceed.php are saved in UTF-8 and set in UTF-8. Database is set to UTF-8 as well. All other request from database give the right charset. I've tried most of the things.
In .js file for AJAX:
$.ajaxSetup({
url: "proceed.php", //file to procces data
ContentType : 'charset=UTF-8', // tried here
global: false,
type: "POST",
dataType: "html" // change to text/html, application/text doesnt work at all
});
In .php file:
mysql_query("SET NAMES utf8");
$output = utf8_decode($sql_result);
All possible combinations.
CODE:
PHP
if(!empty($_POST['select_had'])){
$zem = $_POST['select_had'];
$vysledek = mysql_query("SELECT typ_hadanky, jazyk FROM hlavolam RIGHT JOIN hadanka ON hlavolam.id_hlavolamu=hadanka.id_hlavolamu WHERE zeme_puvodu='$zem'");
$out = "";
while ($zaznam = mysql_fetch_array($vysledek)) {
$zaz = $zaznam['jazyk'];
$out .= "<option>".$zaz."</option>";
}
$vys = utf8_decode($out);
echo $vys;
}
jQuery:
$("#sel_had_zem").change(function(){
var select_had = $("#sel_had_zem option:selected").text();
$.ajax({
data:{'select_had':select_had},
success: function(data){
$("#sel_had_jaz option").nextAll().remove();
$("#sel_had_jaz").append(data);
},
error: function(){
alert('No server response');
}
});
});

How do I get two arrays in Ajax call?

JS CODE:
$.ajax({
url: 'assignavailtrainers.php',
data: {action:'test'},
type: 'post',
success: function(data) {
}
});
PHP CODE:
<?php
$username = "trainerapp";
$password = "password";
$hostname = "localhost";
$link = #mysql_connect($hostname, $username, $password);
if(#mysql_select_db("trainer_registration"))
{
$select_query_num = #mysql_query("select program_id,facilitator_id,availability_status from program_facilitator where availability_status in (1,2)");
$select_query_name = #mysql_query("select facilitator_id,firstname,lastname,email_id from facilitator_details");
$num_rows = #mysql_num_rows($select_query_num);
$trainerdetails = [];
$traineravaildetails = [];
$i = 0;
$j = 0;
while($row = #mysql_fetch_assoc($select_query_num))
{
$trainerdetails[$i]['pgidi'] = $row['program_id'];
$trainerdetails[$i]['facilitatorid'] = $row['facilitator_id'];
$trainerdetails[$i]['avail_status'] = $row['availability_status'];
$trainerdetails[$i]['idi'] = $row['facilitator_id'];
$i++;
}
while($row1 =#mysql_fetch_assoc($select_query_name))
{
$traineravaildetails[$j]['facilitatorid'] = $row1['facilitator_id'];
$traineravaildetails[$j]['firstname'] = $row1['firstname'];
$traineravaildetails[$j]['lastname'] = $row1['lastname'];
$traineravaildetails[$j]['emailidvalue'] = $row1['email_id'];
$j++;
}
echo json_encode(array('result1'=>$trainerdetails,'result2'=>$traineravaildetails));
}
?>
Please help me with the code in the ajax success function area. I've tried using initChart2 but I get an error which says initChart2 is not defined. I don't seem to understand of how to get two arrays from PHP in ajax since I'm a newbie ajax. If someone can help me with the code along with explanation, it'd be great. And I also need to know how to differentiate outputs in ajax which are sent from PHP.
You have two choices:
First one is to simply parse received (text) data to JSON:
var jsonData = JSON.parse(data);
// or simply data = JSON.parse(data);
But the best one in my oppinion is to specify json dataType to the $.ajax() request:
$.ajax(
data: {action:'test'},
type: 'post',
dataType: 'json',
success: function(data) {
...
}
});
This way, $.ajax() will also check for the validity of the received JSON data and error callback will be called instead of success one in case of wrong JSON data received.
...also is important to note you missed to send the json content-type header in your php with:
header("Content-Type: application/json");
Sending this header the dataType: 'json' parameter is no longer (strictly) necessary because $.ajax() guesses it by default attending to the received content-type. But, personally, I prefer to do both.
See $.ajax() documentation.
You forgot:
header("Content-Type: application/json");
… in your PHP.
While you are outputting JSON, you are telling the browser that it is HTML (which is the default for PHP) so jQuery isn't converting it to a useful data structure.
Add that and then you should be able to access data.result1 and data.result2.
To get ajax data:
$.ajax({
url: 'assignavailtrainers.php',
data: {action:'test'},
type: 'post',
success: function(data) {
data.result1;
data.result2;
}
});
You can use console.log(data); to view data structure

Send json from javascript to php

I have a page where users do some stuff and on selecting next, I want to redirect them to a php file, called "Step2.php" along with some JSON information.
I built my json string and it looks like this:
[{"name":"IMG_20130726_182336.jpg","size":2280709,"type":"image/jpeg","width":null,"height":null,"lastModified":1374852216000,"fileExtension":"jpg","orientation":1,"displayed":true,"attributes":[{"title":"Name: ","value":"IMG_20130726_182336.jpg"},{"title":"Date: ","value":"no date"}]}]
Now, I sent it trough jquery POST like this:
jsonData = JSON.stringify(serializableAttributes);
console.log(jsonData);
$.ajax({
type: 'POST',
url: 'Step2.php',
data: {"jsonData" : jsonData},
success: function(msg) {
console.log("Json Sent! " +msg);
window.location("")
},
error: function(request,msg){
console.log("Error : " + msg);
}
});
Question: Why I can`t receive anything in my Step2.php file? Am I wrongly redirect user to that page?
Code in the Step2.php files looks like this:
if(isset($_POST["jsonData"])) {
$json = $_POST["jsonData"];
var_dump(json_decode($json, true));
} else {
echo "NO";
}
It always shows NO.
Ok so I think you misunderstand how AJAX works. You ajax request sends the json to you php and should then respond to it with the appropriate return, in your case a var_dump.
This won't hold the json in the php at all and if you go and request the php file without the POST request you won't get anything else but the output "NO" as there is no POST data you are sending.
If you do want to send a json to you php you do what you are doing now and listen to the request responds which you can see in your inspector. I am not clear on what you ultimately want to do with the data so I don't know if this is the right way.
You can't do it like this. That's not how AJAX and POST work.
If you're simply going to Step2.php, try sending it to the page as part of the URL.
Instead of your AJAX function, simply do:
var jsonData = [YOUR DATA];
window.location.href="Step2.php?json="+jsonData
Or if PHP created the JSON string, you could store it as a SESSION variable.
EDIT: To venture a bit further on the SESSION variable route...
Have your AJAX script as it is now, but make a new PHP file. In this example we'll call it foo.php. Have your foo.php file setup like so:
session_start();
if($_POST){
if(isset($_POST['jsonData'])){
$json = $_POST['jsonData'];
$_SESSION['jsonData'] = $json;
//CREATE A JSON RESPONSE INIDCATING SUCCESS
echo '{ "success" : 1 }';
}
}
Your SUCCESS function of the AJAX call could analyze the response for the success code. If it's "1" redirect to the Step2.php page.
Just make sure that you're calling session_start() at the top of each page.
You can post JSON to PHP
jsonData = JSON.stringify(serializableAttributes);
console.log(jsonData);
$.post("Step2.php", { json: jsonData }, function(msg) {
console.log("image name = " + msg);
});
PHP, you simply parse:
if(isset($_POST['json'])){
$json = $_POST['json'];
$data = json_decode($json);
$image = $data[0];
echo $image->name;
$atributes = $image->attributes;
foreach($atributes as $atrribute){
//echo 'title '.$atribute->title;
}
}
Try this code in my work:
<?php
if(isset($_POST["jsonData"])) {
$json = $_POST["jsonData"];
$json = str_replace('\\', '', $json);
var_dump(json_decode($json, true));
print_r($json);
} else {
echo "NO";
}
?>

Rewriting into JSON file using JavaScript/jQuery

I used jQuery to read from a json file, but when I try to write it to the same file, it won't work.
Here's the code:
$.getJSON(src,function(data){
var about= data.abouttext;
var mail= data.mail;
var phone = data.phone;
$("#about_ta").val(about);
$("#mail_ta").val(e);
$("#phone_ta").val(mp);
$("#wizard_tabs_edit").show();
$("#mask_edit").show();
$("#edit_save").on("click",function() {
data.abouttext = $("#about_ta").val();
data.mail = $("#mail_ta").val();
data.phone = $("#phone_ta").val();
$.ajax({
url: src,
type: "POST",
data: data,
contentType: "application/json",
success: function(response){
alert("aaa");
}
});
$("#wizard_tabs_edit").hide();
$("#mask_edit").hide();
});
});
src is the path to the file (working at the $.getJSON), and it's giving me the alert "aaa" when AJAX succeeds.
But still, the JSON file remains the same.
The only way is to use php or any other backend coding language that can handle the file manipulation for you. Below is an example if you use php5 so you can have a clue:
<?php
// Specify filename
$filename = 'myJsonFile.json';
// Read data transforming them to an array
$data = json_decode(file_get_contents($filename), true);
// Push to the array a new pair
array_push($data, ['key' => 'value']);
// Open file for writing
$file = fopen($filename, 'w');
// Write data as json
fwrite($file, json_encode($data));
// Close file
fclose($file);
?>

Categories