I would like to have a php script that creates a file from the content of an ajax post. File to be called report.txt
I have this php script located at /var/www/copypaste.test/public_html/index.php
<?php
header('Access-Control-Allow-Origin: *');
$report = $_POST['report'];
echo $report;
$report_file = fopen("report.txt", "w");
fwrite($report_file, $report);
?>
and the i have a simple ajax post for now with some test text
var text = 'test string';
var formData = new FormData();
formData.append('report', text);
var ajax = jQuery.ajax({
type: "POST",
url: 'http://copypaste.test',
data: formData,
dataType: 'text',
processData: false,
contentType: false,
success: function(){
console.log('success');
},
error: function() {
console.log('error');
}
});
}
The ajax post is successful as i get test string in the response and this in my console
readyState 4
responseText "\ntest string"
status 200
statusText "OK"
when i then go to http://copypaste.test I don’t see the text or the creation of a file when going into the directory?
Could anyone point me in the right direction please
Thanks
I noticed that you never call fclose("report.txt") to close the file after writing. This can cause problems.
You can you use this function call to handle the opening, writing, and closing of a file.
file_put_contents("report.txt",$report);
You might try replacing the "report.txt" in the function call above just in case the file is still open in memory and you are not able to access it.
Related
I have had this error for multiple days now, I have tried searching this error up but whenever I search this error up it gives a different reason for the error and when I try to add what other sites say it doesn't work which is why I am asking here as I don't see what else I can do.
I am trying to pass a variable from JavaScript to PHP but it is not working and I have no idea why.
Here is my JavaScript code:
<head>
<script type="text/javascript" src="jquery.js"> </script>
</head>
<script>
var variable = "hello";
console.log(variable);
$.ajax
({
url: "ajax.php",
type: "POST",
data:{pass : variable},
success: function() {
alert("Success");
}
});
</script>
Here is my PHP code:
$variable = $_POST['pass'];
echo($variable);
Everything seems to work perfectly. It writes the variable to the console, it comes up with the alert saying success. However I get an error message saying: 'Undefined array key "pass"'
What is causing this? Thank you?
Edit: People have told me to use isset, I have added that it removed the error however it still does not echo the PHP variable, meaning it is still not been passed to PHP, I am still trying to find how to fix this.
Your front end code looks OK, but I don't know your target PHP environement, but maybe your environnement doesn't accept formData.
By default, jQuery send ajax POST data as formData.
Try to send data as JSON
$.ajax({
url: "ajax.php",
type: "POST",
data: JSON.stringify({pass : variable}),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function(data){alert(data);},
});
And then you will probably have to adapt your php code:
$json = file_get_contents('php://input');
// Converts it into a PHP array
$data = json_decode($json, true);
$variable = $data['pass'];
echo($variable);
Can you please use the developer tools in chrome browser that will help you to find if data is properly sent to php file.
Also you can try $_REQUEST instead of post just to check what data is coming in REQUEST as it works for GET & POST both. If it still does not help you.
Also can you please use
data: {'pass':variable}
instead of
data: {pass:variable}
let me know if it works for you.
If you get this error in your ajax.php file which you Post the data to it, I say it's normal because when you open that file (ajax.php) it's like that there is no $_POST['pass'] because you just opened that file without running JS to send data.
If you want to receive data that you send you can do this:
Your JS code I call this file index:
var variable = "hello";
$.ajax
({
url: "ajax.php",
type: "POST",
data:{pass : variable},
success: function(res) {
alert(res);
}
});
The PHP file:
$variable = $_POST['pass'];
echo($variable);
Then if You open up that index file, after running the JS code it'll send that post data to your PHP file and your PHP file will echo that, then the value will store in that res variable which when every thing went fine, you can see the alert of that res in the page (index file).
Notice that as I said you can't open up the PHP file lonely because it doesn't receive a post data on its own, it is normal for undefined to return.
Re: #puckloe your code is working, php echo wouldn't be printed with ajax(correction echo is working but wouldn't show on page if you don't print it with JS too), you have to catch the response in ajax success function ( like success: function(response) ) and print or alert the response --> success: function(response) { alert("hi look this is echo from php"+response) }
you ajax code should look like
$.ajax
({
url: "ajax.php",
type: "POST",
data:{pass : variable},
success: function(response) {
alert("hi look this is echo from php" + response);
}
});
I'm trying to send an array from a JS file to a PHP file in the server but when I try to use the array in php, I got nothing.
This is my function in JS:
var sortOrder = [];
var request = function() {
var jsonString = JSON.stringify(sortOrder);
$.ajax({
type: "POST",
url: '<?php echo get_template_directory_uri(); ?>/MYPAGE.php',
data: { sort_order : jsonString },
cache: false,
success: function() {
alert('data sent');
}
})
};
and this is my php file MYPAGE.php:
<?php
$arrayJobs = json_decode(stripslashes($_POST['sort_order']));
echo($arrayJobs);?>
This is the first time that I use ajax and honestly I'm also confused about the url because I'm working on a template in wordpress.
Even if I don't use json it doesn't work!
These are the examples that I'm looking at:
Send array with Ajax to PHP script
Passing JavaScript array to PHP through jQuery $.ajax
First, where is that javascript code? It needs to be in a .php file for the php code (wordpress function) to execute.
Second, how do you know that there is no data received on the back-end. You are sending an AJAX request, and not receiving the result here. If you read the documentation on $.ajax you'll see that the response from the server is passed to the success callback.
$.ajax({
type: "POST",
url: '<?php echo get_template_directory_uri(); ?>/MYPAGE.php',
data: { sort_order : jsonString },
cache: false,
success: function(responseData) {
// consider using console.log for these kind of things.
alert("Data recived: " + responseData);
}
})
You'll see whatever you echo from the PHP code in this alert. Only then you can say if you received nothing.
Also, json_decode will return a JSON object (or an array if you tell it to). You can not echo it out like you have done here. You should instead use print_r for this.
$request = json_decode($_POST['sort_order']);
print_r($request);
And I believe sort_order in the javascript code is empty just for this example and you are actually sending something in your actual code, right?
the problem is in your url, javascript cannot interprate the php tags, what I suggest to you is to pass the "get_template_directory_uri()" as a variable from the main page like that :
<script>
var get_template_directory_uri = "<?php get_template_directory_uri() ?>";
</script>
and after, use this variable in the url property.
Good luck.
I hope it helps
I can't get the php $_SESSION variable to work the way I want it to. I've got two files. The first one setting the variable:
<?php
session_start();
header("Access-Control-Allow-Origin: *");
$_SESSION['authenticated'] = "yes";
echo json_encode('Authenticated successfully.');
?>
and a second one trying to retrieve it:
<?php
session_start();
header("Access-Control-Allow-Origin: *");
print '<pre>';
var_dump($_SESSION['authenticated']);
print '</pre>';
?>
But the second file always prints NULL when it should print "Yes" and a new error is recorded in the server's log:
[Thu Sep 22 12:52:47.763114 2016] [:error] [pid 26644] [client <ip_here>] PHP Notice: Undefined index: authenticated in <Second_file> on line 5, referer: <client_url_here>
Both files are accessed by AJAX calls from JavaScript.
The AJAX code for file 1 works as following:
$.ajax({
url: corrDomain + '/auth.php', //Path and name of file #1. It's correct and working.
type: 'POST',
data: {
//This part is excluded in the above php code for simplification. It's guaranteed to work.
username: username,
password: password,
action: 'init'
},
dataType: 'json',
success: function(data){
//Check if data contains the right information, then call function for file #2.
},
error: function(){
//Something went wrong
}
});
When that code gets thumbs up from the php, that the user is authorized the following code will be run for file #2:
$.ajax({
url: path + '/getProducts.php', //Also correct and working.
type: 'POST',
dataType: 'json',
success: function(data){
products.push(data);
orderProductIds();
//Update col 1 + 2;
updateOrders('reload');
//Set interval of updating col 1.
setInterval(function(){
updateOrders('update');
}, 10000);
},
error: function(){
alert('Something went wrong.');
}
});
UPDATE: I added session_name(); as the first row in all my php files. The session now works if I open each file in the browser but not if I access them via AJAX. So the problem still persists, but maybe this can help you help me.
UPDATE #2: In Chrome's web inspector I can see that both files are returning Session Cookie ids, but they have different values. See screenshots.
UPDATE #3: I've researched and found that php sessions isn't possible when using PhoneGap, even though I'm requesting the php file via jQuery AJAX. Can someone confirm this?
Make sure you also start the session session_start(); on the page which makes the AJAX calls
EDIT
A not preferable but maybe usefull method is to send the session_id with each ajax request to use more like a token.
The first PHP-script:
session_start();
echo json_encode([
'message' => 'Session started',
'session_id' => session_id()
]);
exit();
Store the received id in a javascript-variable:
var session_id;
$.ajax({
...
success: function(data) {
session_id = data.session_id;
}
...
}
After that send the session_id along with each AJAX-request:
var data = {session_id: session_id, ... };
$.ajax({
type: "POST",
url: "server.php",
data: data,
success: function(data) {
}
});
Instead of the session_id you can generate a random token instead to send along with each request.
I am trying to to extract a Json response in jquery sent from a php file.
This is the .js code:
$.ajax({
url: 'index.php?page=register', //This is the current doc
type: 'POST',
datatype: 'json',
data: {'userCheck': username},
success: function(data){
// Check if username is available or not
},
error: function(){
alert('Much wrong, such sad');
}
});
This is the response from the php file:
if($sth->fetchColumn()!=0){
//$response = array("taken");
$response = array("username"=>"taken");
echo json_encode($response);
//echo '{"username':'taken"}';
}else{
//$response = array("available");
$response = array("username"=>"available");
echo json_encode($response);
//echo '{"username":"available"}';
}
I have tried all combinations I can think of in both files, but nothing seems to work. It is a simple check for a username in the database. If I console log the data I get from the response, I get this:
{"username":"available"}<!DOCTYPE html>
// The rest of the page html
So the info is there, but how do I access it? I have tried several syntaxes found around the internet, but no luck so far. I seem to recall that a json response only can contain valid json, so is the problem the html? I don't think I can avoid this due to the structure of my application, so hopefully it is possible to access the json with my present structure.
in you Ajax
EDIT:
change
datatype:"json",
the case of parameter name was not respected, the t must be T
dataType:"json",
now retry please
$.ajax
({
url: 'index.php?page=register', //This is the current doc
type: 'POST',
dataType: 'json',
data: {'userCheck': username},
success: function(data)
{
// Check if username is available or not
switch(data.username)
{
case "available":
// do you want
break;
case "taken":
// do you want
break;
}
},
error: function()
{
alert('Much wrong, such sad');
}
});
in PHP
simply that, and don't forget to exit; to avoid include html page in your json response !
This is the code coming after the }".... who break your json output
and make it unreadable by javascript (worste, it simply break your javascript !)
echo json_encode(["username"=> ($sth->fetchColumn()!=0) ? "taken":"available"]);
exit;
When you're responding to an AJAX call, you should just return the JSON response, not the HTML of the page. Add:
exit();
after this code so you don't display the HTML after the JSON.
In the JS code, use if (data.username == 'available') to tell whether the username is available.
The other problem in your code is that you have a typo here:
datatype: 'json',
It should be dataType, with an uppercase T.
You can also put:
header("Content-type: application/json");
before echoing the JSON in the script, and jQuery will automatically parse the response.
Also you can set request headers in your jQuery ajax call beforeSend function like follows
beforeSend: function (xhr) {
xhr.setRequestHeader('Content-Type', 'application/json;charset=utf-8');
xhr.setRequestHeader('Accept', 'application/json');
}
So you're strictly declaring the data type to be json
This is my first time posting on this site. I have looked over several of the previous postings related to this topic, but did not find anything that works for me. I am trying to use javascript and jquery $.ajax to call a php script on the server and return the contents of the file. Thus far I am not getting any data back. I am able to update the .txt file on the server using the $.ajax, but could use some help in finding out what I am doing wrong to retrieve it. I do not see any errors being generated from the php script and the events.txt file is not blank. vb.net and c# are my native languages so this is a bit foreign to me.
My js is:
function readText() {
var url = "readdata.php";
var result = "";
$.ajax({
url: url,
type: 'get',
dataType: 'text',
success: function (data) {
result = data;
alert(result);
},
async: false
});
}
and my readdata.php script is:
<?
$file=fopen("events.txt","r");
$read=fread($file,filesize("events.txt"));
fclose($file);
echo $read;
?>
Any advise is welcome. Thanks!
The type in $.ajax should be in capitals
type: 'GET'
function readText() {
var url = "readdata.php";
var result = "";
$.ajax({
url: url,
type: 'GET',
dataType: 'text',
success: function (data) {
result = data;
console.info(result);
},
async: false
});
}
After adding the error: function(){} to the ajax call, I was able to work through this issue.
It turned out that part of the issue was permissions on the server (not able to read from file in the file permissions on the server).
Also I was trying to run locally and I did not have php installed on my local machine.