I'm building an extension that extracts DOMs from a website(not mine) and automates a button click with filling some inputs.
I made a local database which the extension will be extracting values from to fill the inputs, I could successfuly done that with xmlhttprequest that reads my php file from my content-script js file.
Now I want to send my php file that the button was clicked so it updates the database with new values. I tried $.post() but I can't get it with $_POST[];
content-script.js
setTimeout(
function(){
var finsih_div_found = $(dialog_div_found).find("div").get(12);
var finish_button_found = $(finsih_div_found).find("button").get(2);
finish_button_found.dispatchEvent(new Event('click', {bubbles: true}))
$.post('http://localhost:8012/extension-Oasis/php/getIntervenant.php', {button: 'Clicked'}, function(e){
console.log("posted");
});
},2000);
php file
$status = $_POST["button"]; //Gives an error of 'Undefined index: button'.
Please note that the website is not mine I don't have nor the back end nor the front end nor its API's. I just want to automate a button click that's done regularly.
Have you called your PHP file directly? Then it is a HTTP GET request and therefore $_POST['button'] throws and 'Undefined index: button' error. In other words, you can only access the button value via $_POST[] if you use your jQuery $.post to do so.
$.post('http://localhost:8012/extension-Oasis/php/getIntervenant.php', {button: 'Clicked'}, function(e){
console.log(e); // log everything that is echoed in PHP file to browser's console
});
In your PHP file, add a echo $status; in the last line.
Related
I have a html page which contains a form element with some text and file input elements.
This from is submitted with an ajax call to the server using a method suggested here: How can I upload files asynchronously?
As you may see in the referenced page from the above link, the FormData() object is used as a container for inputed data and I have done the job successfully.
But now we want to create a new page that have these html elements, save the text and file inputs on client side (Cookie or Local Strorage or . . .) and do the ajax submit later on another page.
I wasn`t able to save new FormData() in either cookie or local storage; what got saved is a small string:"[object FormData]" instead of entered file and strings.
I also tried using JSON.stringify() with no success; it just returned an empty JSON("{}").
(the code is using jQuery selector)
var postData = new FormData($(form)[0]);
// var sPostedData = JSON.stringify(postData); // returns: "{}"
var myStorage = window.localStorage; // returns: "[object FormData]"
myStorage.setItem("contentOrder", postData);
Please help, how should I save this object on my client-side?
To get the file from form data use formData.get('file') where file is the name of an input. The returned object will be of type Blob (see how to get its content).
The complete example can be found in this fiddle: https://jsfiddle.net/skm5m467/1/
I have a site where I want a user to be able to download some data as a text file, without permanently saving the file on my server. The approach I'm trying is to use JavaScript to send a POST, using PHP to generate and save a text file. On success, JavaScript will open that file in a separate window. After a few seconds delay, it will then send a POST with the file to delete.
I have most of it working, but for some reason, when I try to delete the file, I keep getting an error - No such file or directory. I don't know why, especially since using a test file to delete in the same directory works fine. Here's what I'm using on the javascript side:
////CREATE FILE
function exportGroup() {
$.post("../Modules/Export_Mod/export_mod.php",
{ submit:'export',
groupIndex: groupSelect.value,
userRole: 'admin',
serial: <?php echo $serial;?>
},
function(data,status){
//open created file in new window
window.open("../Modules/Export_Mod/"+data);
removeExport(data);
});
};
//////REMOVE FILE
function removeExport(filename) {
///After 1 second, send post to delete file
setTimeout(function() {
$.post("../Modules/Export_Mod/export_mod.php",
{ submit:'removeExport',
file: filename
},
function(data,status){
data;
});
}, 1000);
}
and my PHP:
//I'm creating the file successfully with this
...
$filename = $groupName."_group_export.txt";
$content = $header.$dataStr;
$strlength = strlen($content);
$create = fopen($filename, "w");
$write = fwrite($create, $content, $strlength);
$close = fclose($create);
But when I try to delete a second (or more) later using this:
if (($_POST)&&($_POST['submit']=='removeExport')){
$file = $_POST['file'];
unlink($file); ///works when using an already-existing file in the same directory ... unlink('test.txt');
}
I get the error. The first thing am wondering is if I'm approaching this the right way. If not, is there a better way to do it? And then the second thing I'm wondering is why I'm getting this error and what I need to change to make it work.
I would check the server permissions to see if the php script that is running is able to delete the files that are created. If you are on a unix based script I would run the
ls -l /usr/var/
command on the directory that you are storing the files in, to see what permissions have been assigned to them.
I've done similar sorts of things where a file is created and then deleted some time later, in my case 24hrs. But what I did was to set up a cron job to find the files that are older than a period of time and then delete them. That way I don't have to depend on the browser to post back a delete request.
Another option is to set up a custom session handler that deletes files associated with the session upon close of the session. Though that may leave things lying about if the user doesn't officially log out.
Or you could keep the file data in CLOBs on MySQL and then set up a query that kills them after a period.
Or if you feel like using Cassandra, you can set a TTL on a row and it will magically disappear.
Don't get locked in to operating system files. You control what data is provided by your pages, so if you want to send back data and call it a "file" the user will never know that it is actually a database entry.
Here's the break down: My problem is two fold, i want to use a button to call to my php script, which in turn calls to my nodejs script running on my little internal test server (this is all done local for now).
Here is my html + script pull:
<input type="submit" value="Save Sketch" id= "run_system">
</body>
<script>
$('#run_system').on('click', function(){
$.ajax({
url : 'exec.php',
type : "GET"
}).done(function(data){
console.log(data);
});
});
</script>
and here is my php script:
<?php exec('node screenshot.js //place holder url that gets dumped into js file// "); ?>
so my problem is that the previous call to this php is not executing this. Everything i've googled says that this exec("") should run my nodejs script. What am i missing?
I am guessing the type : GET is incorrect, tried not having that line, putting POST in there, nothing seems to work though
Oh one more addition, so when i run the above all it does is print what was in the php file to the console, doesn't actually run the script
One of the issues is that the exec is executing the command, but you're not capturing / returning the output of that command. You can probably add an echo or print before exec to return the output to the AJAX request.
You might also want to bind to the submit event to handle form submissions as well as submit button clicks, but that would be bound to the form itself.
Ultimately though, I would recommend that you contemplate handling this exec by adding a simple HTTP server to your screenshots.js node script (or something that wraps it) and handle the AJAX request with that. Will likely need to add a Access-Control-Allow-Origin exemption.
I've been trying this for 3 days but couldn't find a solution yet. I need to load a php page with javascript. I'm using the code bellow however changing the page while the function is still working slows the page down.
$.post("connect.php?refresh_steamdata=true",{
},
function(data)
{
alert("loaded!");
});
load() is a simplified version of Post that replaces the contents of an element with the response from the server.
".load() sets the HTML contents of the matched element to the returned data."
$.post() will get you the result you are looking for but it does so Asynchronously. This means that if you plan to do something with the response you get back from the server you need to do it inside of the success function
$.post("<? echo $js_url."?refresh_steamdata=true"; ?>",{},function(data){
alert("loaded!");
// do something with data HERE
});
// not here since this will run before the data is returned
I have a link that when clicked needs to call a controller action with certain data which must be retrieved via JavaScript. The action will be returning a FileStreamResult.
I looked at #Url.Action but I couldn't figure out how (or even if) I could pass value dictionary stuff which had to be retrieved via JS.
So then I went with a $.post from a click handler. The problem I'm having is that I'm not sure what to do in my success: function() to return the file stream result to the user. Or even if I can.
So any help on how you would do something like this would be great..
So then I went with a $.post from a click handler. The problem I'm having is that I'm not sure what to do in my success: function() to return the file stream result to the user. Or even if I can.
Exactly. You can't do much with a received byte in javascritpt: obviously you cannot save it on the client computer nor pass it to some external program on the client. So don't call actions that are supposed to return files using AJAX. For those actions you should use normal links:
#Html.ActionLink("download file", "download", new { id = 123 })
and let the user decide what to do with the file. You could play with the Content-Disposition header and set it to either inline or attachment depending on whether you want the file to be opened with the default associated program inside the browser or prompt the user with a Save File dialog.
UPDATE:
It seems that I have misunderstood the question. If you want to append parameters to an existing link you could subscribe for the click event in javascript and modify the href by appending the necessary parameters to the query string:
$(function() {
$('#mylink').click(function() {
var someValue = 'value of parameter';
$(this).attr('href', this.href + '?paramName=' + encodeURIComponent(someValue));
return true;
});
});
Instead of going with a post, I'd go with associate a JQuery on click handler of the link which would call the controller action. This is assuming that the action method returns a FileStreamResult and sets the correct content type so that the browser interprets the result and renders it accordingly.
With your approach you'd have to interpret in the onSuccessHandler of the post on how to render the generated stream.