JS $.post > dump PHP $_POST data to file - javascript

I've been trying this for hours and finally give up.
As you can tell I've a huge noob and have little to no idea what I'm doing...
I have some JS being called from a button onclick= which POSTs to a PHP file. I'd like to take this POST data and just write it to a file, nothing fancy, just dumping it raw.
I've tried various methods, but none seem to work - either not writing the data at all, or writing "()", "[]" (if trying to encode the POST data as JSON), or just the word "array" and so on.
Methods I've tried;
file_put_contents('test.txt', file_get_contents('php://input')); //this I thought *should* definitely work...
var_dump / var_export / print_r
I've tried storing the above as $data and writing that as well. Just nothing I do seems to work at all.
I'm mostly trying to use fopen/write/close to do the deed (because that's all I really "know"). File is writable.
(part of the) JS I'm using to POST:
(from button onclick="send('breakfast'))
function send(food){
if(food == 'breakfast'){
$.post("recorder.php?Aeggs=" + $("textarea[name=eggs]").val());
I'm not looking to extract(?) values from the POST data, just write it "as-is" to a file, and I'm not bothered on the formatting etc.
Would someone please assist in putting me out of my misery?

You could use fopen() and fwrite() to write text to a new file. print_r() could be used to get the structure of the data or you could write the post var itself to the file. But since your client side code is not sending any POST data, use $_GET on the php side instead of $_POST. Here's an example:
$f = fopen("post_log.txt", 'w'); // use 'w' to create the file if not exists or truncate anew if it does exist. See php.net for fopen() on other flags.
fwrite($f, print_r($_GET, true)); // the true on print_r() tells it to return a string
// to write just the Aeggs value to the file, use this code instead of the above fwrite:
fwrite($f, $_GET["Aeggs"]);
fclose($f);
NOTE: The 2nd param to $.post() would contain the "post" data. Since you dont have that in your code, the $_POST on the PHP side will be an empty array.

Related

Using "A little vanilla framework" to build an upload feature

Looking at this document; I am trying to make a file upload using XMLHttpRequest.
Here is how I start: I take the code in the A little vanilla framework section of the document. Then I first make it work on my own site. Then to implement the upload functionality I want to modify the end of the register.php file. Indeed a file transfer to the server is already happening there. To call it an upload I only have to save the file on the server.
I do that after these lines:
echo "\n\n:: Files received ::\n\n";
print_r($_FILES);
There, I want to write the contents of $_FILES[0] on the server. For that I use this code:
$myfile = fopen("MyData.jpg", "w");
fwrite($myfile, $_FILES[0]);
// The three lines below that I have tried instead of the one above do not work either.
//fwrite($myfile, json_encode($_FILES['photos']);
//fwrite($myfile, json_encode($_FILES[photos[0]]);
//fwrite($myfile, json_encode($_FILES['photos'][0]);
fclose($myfile);
As a result, there is a file named MyData.jpg written on the server as expected, but its length is zero.
I think there is a mistake in the three lines above but, what did I do wrong?
Right method is to use
move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], "MyData.jpg");
where "fileToUpload" is the field name you gave for the file button
I think you'll get data here: $_FILES['photos']['tmp_name'][0].
Try it please.
Or
You could rewrite your code like below:
foreach($_FILES['photos']['tmp_name'] as $i=>$file){
if($_FILES['photos']['error'][$i] == 0){
move_uploaded_file($file, "MyData_".$i.".jpg");
}
}

How to pass javascript variables to php variables with yii

First: I KNOW this is a duplicate. I am creating this because none of the answers to all the other questions satisfy me. I have a very particular situation where I'm using yii and tryi I can't send it through ajax because the php and javascript are on the same page on the same page.
Basically what I'm asking is if you have a page that uses yii and chart js, and you need to render a page that requires two arguments from the clicked bar, which is represented by activeBars[0]:
<script>
canvas.onclick = function(event) {
var activeBars = getBarsAtEvent(event);
<?php $controller->functionThatRendersView($arg1 /**(activeBars[0].value*/,$arg2 /**(activeBars[0].label*/); ?>
}
I don't care if it will render automatically, that is another problem. I just need to get those arguments to the php.
Thanks.
Also, if it helps, I am passing those two values to javascript through php for loops:
labels: [<?php for ($i=1;$i<=$numberIssues;$i++) {
echo $i . ",";
}?>],
The problem with grabbing $i and putting it into the label argument is that I don't know which bar label is the clicked one, I need javascript to pass the clicked bar values back to php.
Explain to us again why you can't use ajax. You say "because the php and javascript are on the same page". That's not what ajax is - you need a different URL for the ajax request, and a separate PHP file or something to handle it.
Without ajax it's impossible for javascript to send information to PHP, because the PHP runs on the server before the javascript runs on the client. Unless of course you want to do a complete page refresh, which is slower and generally worse from the user perspective.
I found an answer to my question! I'm just doing this for anyone else who is stumbling:
To pass javasctipt variable var jsInteger = 5; to php you type (in javascript):
window.location.href = "yourPhpFile.php?phpInteger="+jsInteger;
You access the variable in php like so:
$phpInteger = $_GET['phpInteger'];
This will require a page refresh, and will redirect you to the php file.

passing php variable to separate javascript file

I have been reading how to pass variables from a php webpage to a separate javascript file, but am not having any luck.
Please don't mark this as duplicate, as I know there are a ton of things out there telling the ways to do this. I recognize those posts and am more just checking my syntax or seeing if there is anything unique about my specific situation that is causing those methods not to work.
So I have a PHP webpage where I POSTed some variables to:
DOCTYPE HTML
...
<?php
$id = $_POST["id"];
$name = $_POST["name"];
?>
...
HTML code with some usage of PHP variables
javascriptFunction()
end page
Then in a separate javascript file I have:
var markerlocation = '<?php echo $point; ?>';
function javascriptFunction () {
alert("markerlocation");
});
This seems really straight forward, but for whatever reason I can't get it. I also have tried with json encode.
I can delete this when done.
Sincere thanks for any help.
My way:
Declare a Array to store variable for passing variable to JavaScript
Encode the Array to JSON in php
Decode the JSON String from php and store as a JavaScript variable
PHP
<?php
//You may declare array for javascript
$jsVal = array(
'user_name' => 'Peter',
'email' => 'peter#gmail.com',
'marker_location' => '102,300'
);
?>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>var phpConfig = jQuery.parseJSON(<?=json_encode($jsVal)?>);</script>
Separated javascript file
alert(phpConfig.marker_location);
You can try it
You can point the script tag source to a .php file instead of a .js file, I think that's what you want. Works with image tags too ;)
Edit: some browsers may require the text/javascript mime header in order for it to work properly, but it's not hard with PHP I'll assume you already know how to do that.
On a side note: This option should probably only be used if you're planning on allowing the client to cache the javascript output. If you don't want the client to cache it, you need to set additional headers.

trying to write to txt file with php and ajax post

I am trying to save a string that is created dynamically based on the user's interaction with the web app that I'm creating. just a string. nothing special. I am using ajax to send the string up to the server, and it seems that it is getting as far as the file_put_contents function I am using, but it seems to go haywire. It makes the txt file, but it does not put anything in it, and it does not send back q, the variable that I have it echo back.
Another weird thing is that when I try to write to said file with this
file_put_contents($putStringHere, $q);
I also tried this one:
file_put_contents($putStringHere, "$q");
The file always says that this happened:
modified: Today, Now (last time I ran the function)
Last Opened: Today, 5 minutes ago... last time I opened the file by hand
This would make sense, except for the fact that the function above contains fopen, fmodify, fclose, or whatever they're called. And the modified set to the last time I ran the function... I am super confused on this one. anyone who can help, I will greatly appreciate it.
ajax that sends string (yes, i made sure it was a string)
//ajax for saving changes
function stylesheetBackup(str){
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST","stylesheetBackupFile.php",true);
console.log("q="+str);
xmlhttp.send("q="+str);
}
also tried ajax with
xmlhttp.open("POST","stylesheetBackupFile.php",true);
xmlhttp.send();
php that I call with ajax
<?php
//get the q parameter from URL
$q = $_POST["q"];
$putStringHere = "savedStyleSheet.txt";
//output the response
echo $q;
//save to a backup file
file_put_contents($putStringHere, $q);
?>
You have a mis-match:
xmlhttp.open("GET"...
and
$q = $_POST["q"];
Here's two things that might help fix your problem:
In the AJAX request, you specify that it's a GET request. However, in your PHP file, you're trying to get the q value of $_POST. Try $_GET['q'] instead.
I'm not sure you're able to send your GET data using xmlhttp.send. Try adding it to your URL, as in xmlhttp.open("GET", "stylesheetBackupFile.php?q=" + str, true).

jQuery Fails To Read JSON Response From PHP Script

In my form, I want to do something with two fields:
"website_domain" and "website_ip_address"
I'm trying to use jQuery/JSON to call a PHP script, pass the website_domain to it, and receive JSON including the IP address of that website.
Problem/Symptoms Description:
It's partially working: On blur, it GETs the url of the PHP script. I can see that much in firebug. I get a 200 OK. Output from the PHP script is valid JSON according to JSONLint:
{"field":"website_ip_address","value":"74.125.225.70"}
But in Firebug, I don't have a JSON tab. I only have Params and Headers tabs. Not even a Response tab.
Needless to say, the website_ip_address field is also not being populated with the data I should be getting from the PHP script's JSON output.
My PHP Script:
It may be important to note that for now, this PHP script on a different domain from my application. Maybe my whole problem is cross-domain?
<?php
$domain = $_GET["domain_name"];
$ip = gethostbyname($domain);
// echo $ip;
$json = array(
'field' => 'website_ip_address',
'value' => $ip,
);
header('Content-Type: text/plain');
echo json_encode($json );
?>
My jQuery/JSON script:
Note this is written inside a Ruby On Rails application view.
:javascript
$("#website_domain").bind("blur", function(e){
$.getJSON("http://exampledomain.com/temp_getIP.php?domain_name=" +$("#website_domain").val(),
function(data){
$('#website_ip_address').val(data);
});
});
I really hope this isn't just a syntax error on my part. I've been writing/rewriting this for 2 days, based on answers I've found on StackOverflow, to no avail. I'm just missing something here.
You are currently attempting to output the JS object (that is formed from the parsed JSON response) to the field. You need to output a value from within it. So not:
$('#website_ip_address').val(data); //data is an object, not a string
but
$('#website_ip_address').val(data.someValue); //output a property of the object
With your code as it is, I would expect the field to be populated with the string representation of an object, which is [object Object]. You don't mention this, so I wonder whether a) your success function is even firing (check this - stick a console.log in it); b) your jQ selector is sound.
The problem can be with different domain. I had it like this before. Try in php to add header("Access-Control-Allow-Origin: *")
Put your jQuery code inside document ready, example: $(function(){ });
:javascript
$(function() {
$("#website_domain").bind("blur", function(e){
$.getJSON("http://exampledomain.com/temp_getIP.php?domain_name="+$("#website_domain").val(),
function(data){
$('#website_ip_address').val(data);
});
});
});
});
And you have a missing end })

Categories