Exchange data php javascript - javascript

I have to select a file locally and use it in a python script.
I can't get the filename in order to have it in my ajax script that i use to call a php function.
This is my javascript, called onclick over Ok button:
function myAjax () {
$.ajax( { type : 'POST',
data : {},
url : 'action.php',
success: function ( data ) {
alert( data );
},
error: function (xhr, status, error) {
// executed if something went wrong during call
if (xhr.status > 0) alert('got error: ' + status); // status 0 - when load is interrupted
},
complete: function (data) {
setImg();
}
});
}
This is the php script used to call python script:
<?
function bb(){
$out = shell_exec( 'python heatmap.py');
echo "ok";
$fp = fopen('log.txt', 'w');
fwrite
($fp, $out);
fclose($fp);
}
bb();
?>
I have to take filename from Browse button and send it to ok button, where the python is called.
What is the correct way to exchange data from input="file" html, javascript and php?

I'm making a lot of assumptions here as the question is not entirely clear...
But presumably you're wanting the name of a file that has been selected from the OS. In JS you can do this using the following.
var fileName, oForm = document.getElementById('my-file');
oForm.onchange = function(){
fileName = this.files[0].name;
}
Then in your AJAX call, add the fileName variable to your data property.
data : {"filename":fileName},
And then in your PHP access it via the $_POST variable. So...
echo $_POST['filename'];

Related

Passing a PHP variable to JavaScript For AJAX Request

So my workflow is that onClick of an list element, my JS initiates a PHP AJAX request to build a card object. The $content is a card (similar to KickStarter) of topic data. What I'm trying to do is a pass the 'topic_id' of each topic-instance so that I can then use it in the success function, to then initiate ANOTHER AJAX request (but to Discourse).
With attempt 2), I get a null when viewing its value in the web inspector.
The AJAX requests (the console.log() of the variable I want to get returns a blank line in the web console):
$.post( "/wp-content/mu-plugins/topic-search.php", { topicID: $topicFilter, filterBy: $sortByFilter },
function( data ) {
console.log(topic_id);
data = data.trim();
if ( data !== "" ) {
//get the participants data for avatars
$.getJSON('http://ask.example.com/t/' + topic_id + '.json', function() {
The end of topic-search.php, which echoes out the built up card. Script is supposed to return the topic_id variable for use in the success function.
}
//One attempt: echo $content; //
//Another attempt: echo json_encode(array('data' => $content, 'topic_id' => $row['topicid']));//
}
?>
<script>
var topic_id = "<?php echo $row['topicid'] ?>";
</script>
Try this:
In php
$inputJson = file_get_contents('php://input');
$input = json_decode($inputJson, true); //Convert JSON into array
In javascript
var $url = '/wp-content/mu-plugins/topic-search.php';
var $json = JSON.stringify({topicID: $topicFilter, filterBy: $sortByFilter});
$.ajax({
url: $url,
type: "POST",
data: $json,
dataType: "json",
success: function(data){//you will have the body of the response in data
//do something
},
error: function(data){
//do something else
}
});
EDIT:
This will request $url with the $json data. You will have it available on $input on the server side as an array. You can then on the server prepare a response with a json body that you will have available on the success function as the data variable.

Cannot call external function using ajax [duplicate]

This question already exists:
Deleting a specific node based on dropdown selection in XML [duplicate]
Closed 7 years ago.
Here's my jquery code
<script>
$(function () {
$('#deleteform').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'get',
url: 'delete.php',
success: function () {
alert('Worked');
}
});
});
});
</script>
And my PHP code (I'm just trying to test it out, so I added a simple function)
<?php
header("Location: http://www.google.com/");
?>
And nothing happens when I click the button (when the form submit) except that "Worked" alert box. But whatever I put in that PHP file (delete.php), nothing happens. What am I doing wrong? My "delete.php" file will have a script to delete data in a XML file, just in case it changes something. (for now Im trying with a simple php line)
EDIT
The real PHP code that will go in the PHP file is this :
<?php
$xml = simplexml_load_file("signatures.xml");
$name = $_POST['nom'];
$signs = $xml->xpath('//Signature[Nom = "'.$name.'"]');
$xml -> SignaturesParent -> removeChild($signs);
?>
Nothing happens when I try that.
Try this.
The ajax call now alerts whatever is sent to it from the delete.php
The ajax call does a POST and not a GET so that it matches the fact that you are using $_POST[''] and send some data i.e. smith you are going to have to change that to something that actually exists in your XML file
The delete.php actually returns something
The delete.php saves the changed xml document back to disk to a file with a different name, so you can see if it actually did anything. just while you are tesing.
<script>
$(function () {
$('#deleteform').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: 'delete.php',
data: {nom:"smith"},
success: function (data) {
alert(data);
}
});
});
});
</script>
<?php
$xml = simplexml_load_file("signatures.xml");
$name = $_POST['nom'];
$signs = $xml->xpath('//Signature[Nom = "'.$name.'"]');
$xml -> SignaturesParent -> removeChild($signs);
$result = $xml->asXML("signatures2.xml");
echo $result ? 'File Saved' : 'File Not Saved';
?>

Echo PHP message after AJAX success

I have a modal that will display when the user clicks a delete button. Once they hit the delete button I am using AJAX to subimit the form. Eveything works fine, but it is not display my success message which is set in PHP.
Here is my AJAX code:
function deleteUser(){
var id = <?php echo $userdetails['id'] ?>;
$.ajax({
type: "POST",
url: 'admin_user.php?id=' + id,
data: $('form.adminUser').serialize(),
error: function(e){
alert(e);
},
success: function () {
// This is empty because i don't know what to put here.
}
});
}
Here is the PHP code:
if ($deletion_count = deleteUsers($deletions)) {
$successes[] = lang("ACCOUNT_DELETIONS_SUCCESSFUL", array($deletion_count));
} else {
$errors[] = lang("SQL_ERROR");
}
And then I call it like this:
<div class="col-lg-12" id="resultBlock">
<?php echo resultBlock($errors,$successes); ?>
</div>
When I use AJAX it does not display the message. This works fine on other pages that does not require AJAX to submit the form.
I think you are getting confused with how AJAX works, the PHP script you call will not directly output to the page, consider the below simplified lifecycle of an AJAX request:
Main Page -> Submit Form -> Put form data into array
|
--> Send array to a script to be processed on the server
|
|----> Callback from the server script to modify DOM (or whatever you want to do)
There are many callbacks, but here lets discuss success and error
If your PHP script was not found on the server or there was any other internal error, an error callback is returned, else a success callback is fired, in jQuery you can specify a data array to be received in your callback - this contains any data echoed from your PHP script.
In your case, you should amend your PHP file to echo your arrays, this means that if a successful request is made, the $successes or $errors array is echoed back to the data parameter of your AJAX call
if ($deletion_count = deleteUsers($deletions)) {
$successes[] = lang("ACCOUNT_DELETIONS_SUCCESSFUL", array($deletion_count));
echo $successes;
} else {
$errors[] = lang("SQL_ERROR");
echo $errors;
}
You can then test you received an object by logging it to the console:
success: function(data) {
console.log(data);
}
Well, it's quite not clear what does work and what does not work, but two things are bothering me : the function for success in Ajax is empty and you have a header function making a refresh in case of success. Have you tried removing the header function ?
success: function(data) {
alert(data);
}
In case of success this would alert the data that is echoed on the php page. That's how it works.
I'm using this a lot when I'm using $.post
Your header will not do anything. You'll have to show the data on the Java script side, maybe with alert, and then afterwards redirect the user to where you want in javascript.
you need put some var in success function
success: function(data) {
alert(data);
}
then, when you read var "data" u can do anything with the text
Here is what I changed the PHP to:
if ($deletion_count = deleteUsers($deletions)) {
$successes[] = lang("ACCOUNT_DELETIONS_SUCCESSFUL", array($deletion_count));
echo resultBlock($errors,$successes);
} else {
$errors[] = lang("SQL_ERROR");
echo resultBlock($errors,$successes);
}
And the I changed the AJAX to this:
function deleteUser(){
var id = <?php echo $userdetails['id'] ?>;
$.ajax({
type: "POST",
url: 'admin_user.php?id=' + id,
data: $('form.adminUser').serialize(),
error: function(e){
alert(e);
},
success: function (data) {
result = $(data).find("#success");
$('#resultBlock').html(result);
}
});
}
Because data was loading all html I had to find exactly what I was looking for out of the HTMl so that is why I did .find.

jQuery.ajax + php 5.3 - always executing error function

(Newb here) I have a PHP function that gets 2 csv files from the server and create a new one with the difference between values contained in those files. This PHP function is inside a separate file test.php and looks like this:
<?php
require_once('libs/parsecsv-for-php-master/parsecsv.lib.php');
$csv1name = $_POST['csv1'];
$csv2name = $_POST['csv2'];
$data1 = 'data/'.$csv1name.'.csv';
$data2 = 'data/'.$csv2name.'.csv';
$csv1 = new parseCSV($data1);
$csv2 = new parseCSV($data2);
$csv = new parseCSV();
$csv->data[0] = array('label','difference');
$j = 1;
for ($i = 0; $i < count($csv1->data); $i++) {
$csv->data[$i+1] = array($j.'d',$csv1->data[$i][$csv1name] - $csv2->data[$i][$csv2name]);
if($i == 0) {$j += 20;}
else {$j += 21;}
}
$csv->save('test.csv');
?>
This function works correctly and produces the expected csv file.
I have a JavaScript function that sits on another page (namely update.html) and calls the aforementioned php function via ajax:
function callPHP() {
$.ajax({
type:"POST",
url:"test.php",
dataType:"json",
data:{csv1: '02-01-2015', csv2: '02-12-2014'},
error: function(requestObject, error, errorThrown) {
alert(error);
alert(errorThrown);
},
});
}
PROBLEM: The error function is always executed, that is, whenever I run callPHP() I get two alerts.
QUESTION: Why is it error always being called?
(Extra: Is it possible to work with the response variable? How can I debug it without having to upload my files to a server every time? Is it guaranteed that when the complete function is called, the $csv->data function was already resolved?)
Thanks for helping!!! :D
UPDATE 1: I changed the code above by removing the complete function from ajax and I added some extra parameters to the error function.
complete is always called no matter its success or error. So you are running into error condition and complete gets called anyway after error is executed. You can add additional params (jqXHR jqXHR, String textStatus, String errorThrown) in error function to figure out what the error is.
Try using success instead of complete, and add a JSON answer to your PHP script for example echo json_encode((object) array('success'=>true)); because your AJAX call has dataType:"json" parameter for a JSON response, so your AJAX call will try to parse a JSON.
PHP code:
header('Content-Type: application/json');
echo json_encode((object) array('success'=>true));
AJAX:
function callPHP() {
$.ajax({
type:"POST",
url:"test.php",
dataType:"json",
data:{csv1: '02-01-2015', csv2: '02-12-2014'},
success: function(response) {
alert(response);
},
error: function(response) {
alert(response);
},
});
}

Converting JavaScript function argument to php variable

I have a js function, which is passed a fileid to delete by a php script.
I don't know how to convert the javascript parameter from JavaScript to PHP variable.
Here is what I have done so far:
<script>
function deleteFile(file)
{
var r = confirm("Are you sure you want to delete this file?");
if (r === true)
{
<?php
$idfile = file; // How to convert it??
unlink(mysql_result(
mysql_query("SELECT filepath FROM
file where idfile='$idfile'"), 0, 0))
or die("Could not delete file");
mysql_query("DELETE FROM file WHERE fileid=$idfile")
or die("Cannot delete file");
echo "File has been deleted successfully.";
?>
}
}
</script>
I have a button also:
echo "<button onclick=\"deleteFile($fileid)\">Delete</button>";
UPDATE
function deleteFile(file)
{
var r = confirm("Are you sure you want to delete this file?");
if (r === true)
{ // doesn't go to deletefile.php
$.ajax({
url: "/deletefile.php",
method: 'POST',
data: {
id: file
}
});
}
}
That won't work. JavaScript and PHP are totally separate entities that execute at different times.
PHP is a server-side language. The PHP code executes on your server and returns a response to the web browser.
JavaScript is a client-side language. It executes when the user is interacting with the page in their browser, after the PHP code has executed.
You'll need to write a separate PHP script that takes the ID of the file to delete, then use AJAX to send the request to delete it with the specified file ID.
You can’t put a Javascript variable in PHP, but you can make an AJAX to send $id_file:
$.ajax({
url: "/action.php",
method: 'POST',
data: {
id: file,
}
});
Then in the PHP action you can use the $_POST['id'] and make the query.
It would be better to use AJAX for example with jQuery. Code you created can't work, that way. Try this.
Generating button with id
<?php
echo '<button class="delete_button" data-id="'.$id.'">delete me!</button>';
?>
Download jQuery from here, save it into your project folder.
Sending post request using jQuery
<script type="text/javascript" src="/path/to/jquery.min.js">
<script type="text/javascript">
$(".delete_button").click(function() {
var id = $(this).data("id");
$.post( "handler.php",{del: id}, function( data ) {
if(data)
{
alert("deleted successfully!");
window.location = "/your/desired/url"; // redirect after success
}
}
}); </script>
deleting in handler.php
if(array_key_exists("del", $_POST))
{
// delete in mysql
}
function deleteFile(file)
{
var r = confirm("Are you sure you want to delete this file?");
if (r === true)
{ // doesn't go to deletefile.php
$.ajax({
url: "/deletefile.php",
method: 'POST',
data: {
id: file
}
})
.done(function( data ) {
console.log(data);
});
}
}
Php
<?php
$idfile = $_POST['id']; // How to convert it??
unlink(mysql_result(
mysql_query("SELECT filepath FROM
file where idfile='$idfile'"), 0, 0))
or die("Could not delete file");
mysql_query("DELETE FROM file WHERE fileid=$idfile")
or die("Cannot delete file");
?>
doesn't go to deletefile.php ? maybe the url is not the correct

Categories