Send/receive data via jQuery to/from PHP - php

I am using this code to make the user input a name to create a folder. I have modified the code to try and send the form data via jQuery and receive the success/failure message from PHP through jQuery.
However, when I enter the name of the folder, nothing happens. No folder is created nor any error displayed. Firebug does not show any error either.
This is the code I have till now:
create.php:
<html>
<head><title>Make Directory</title></head>
<body>
<div id="albumform">
<form id="album_form" method="post" action="createAlbum.php" enctype="multipart/form-data">
<p id="message" style="display:none;">
<?php echo (isset($success)?"<h3>$success</h3>":""); ?>
<?php echo (isset($error)?'<span style="color:red;">' . $error . '</span>':''); ?>
</p>
<input type="text" id="create_album" name="create_album" value="" />
<input type="button" onclick="return checkForm('album_form');" id="btn_album" name="btn_album" value="Create" />
</form>
</div>
</body>
</html>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script type="text/javascript">
/* $("#btn_album").click(function() { */
function checkForm(form) {
//create post data
var postData = {
"create_album" : $("#create_album").val()
};
//make the call
$.ajax({
type: "POST",
url: "createAlbum.php",
data: postData, //send it along with your call
success: function(response){
$('#message').fadeIn();
}
});
/* }); */
}
</script>
createAlbum.php:
<?php
/**********************
File: createDir.php
Author: Frost
Website: http://www.slunked.com
***********************/
// set our absolute path to the directories will be created in:
$path = $_SERVER['DOCUMENT_ROOT'] . '/web/photos/images/';
if (isset($_POST['btn_album'])) {
// Grab our form Data
$dirName = isset($_POST['create_album'])?$_POST['create_album']:false;
// first validate the value:
if ($dirName !== false && preg_match('~([^A-Z0-9]+)~i', $dirName, $matches) === 0) {
// We have a valid directory:
if (!is_dir($path . $dirName)) {
// We are good to create this directory:
if (mkdir($path . $dirName, 0775)) {
$success = "Your directory has been created succesfully!<br /><br />";
}else {
$error = "Unable to create dir {$dirName}.";
}
}else {
$error = "Directory {$dirName} already exists.";
}
}else {
// Invalid data, htmlenttie them incase < > were used.
$dirName = htmlentities($dirName);
$error = "You have invalid values in {$dirName}.";
}
}
?>

There are at least two seperate problems with your code:
In the php-file, you check if $_POST['btn_album'] is set. This field is not sent as it is not part of your ajax-request (You're only sending "create_album" : $("#create_album").val()). So the code that creates the folder is never executed.
Another problem is the part
<?php echo (isset($success)?"<h3>$success</h3>":""); ?>
<?php echo (isset($error)?'<span style="color:red;">' . $error . '</span>':''); ?>
in your response-message. This code is evaluated when the page loads, not during your ajax-request, so the php-variables $success and $error will always be undefined. You have to return those response-messages as response to the actual request and then use javascript to display them.

The ajax request has a bad habit of failing silently.
You should use jQuery post and take advantage of .success(), .complete(), and .error() functions to track your code.
Also use the console.log() to check if the parameters are sent corectly. I'll try out the code myself to see the problem.
http://api.jquery.com/jQuery.post/

Due to the nature of the $.ajax request, $_POST['btn_album'] is not sent. So your php file gets here
if (isset($_POST['btn_album'])) {
and returns false.
also you need to echo $error to get a response.

Related

Obtain AJAX returned object in PHP

I have a program which is running server script on raspberry pi (client which is also a server). I'm scanning a barcode which then executes few commands (including generating XML file). When I submit the form with the 'serial' number, I want to be able to retrieve the filename (string) returned from AJAX ($_POST) method in server.php? if (isset($_POST['filename']) does not return the filename, how do I obtain filename with a single AJAX? and use it in PHP? I have no error messages, the $_POST['filename'] is empty. I tried separating the script into a different file and creating another AJAX calling that PHP script but it did not fully work and I wonder if there is a possibility to do it with a single AJAX and make PHP listen for the returned filename.
Or maybe is there a better way to obtain the filename of the external file than through client-side? (there is always single XML file waiting to be picked up).
server.php
<?php
$show_error = "";
if (isset($_POST['serial'])) {
$serialnumber = $_POST['serial'];
if ($serialnumber > 0) {
if (isset($_POST['filename'])) {
$filenamer = $_POST['filename'];
echo $filenamer;
} else {
echo "no filename returned from ajax call";
}
$remote_file_url = 'http://' . $_SERVER['REMOTE_ADDR'] . '/345.xml'; //FILENAME NEEDED
$local_file = '345.xml'; //FILENAME NEEDED
$copy = copy( $remote_file_url, $local_file );
}
?>
<html>
<body>
<form name="test" method="post">
<input type="number" name="serial" id="serial" value="1">
<input type="submit" name="">
</form>
</body>
<script type="text/javascript">
function scan(serialnumber)
{
return $.ajax({
url : 'http://localhost/test.php',
type : 'POST',
dataType : 'json',
data : { serial_no : serialnumber},
cache : false,
success : function(data) {
var filename = data[Object.keys(data)[1]];
console.log(filename);
}
});
};
scan(<?php echo $serialnumber; ?>);
</script>
</html>
test.php
<?php
header('Access-Control-Allow-Origin: *');
header('Content-type: text/json');
# Get the serial
$serial_no = $_POST['serial_no'];
$return['serial_no'] = $serial_no;
# Get the filename of the XML file
$filename = shell_exec('find /var/www/html/*.xml -printf "%f"');
$return['filename'] = $filename;
$return['scanpink'] = 1;
echo json_encode($return);
?>
As I mentioned in my comment, you don't have filename in php because your form does not include filename field. After receiveing filename from ajax you can do another ajax request with serial & filename fields or the second solution is to use a hidden field. After receiving data in ajax you cannot use them in php - You have to send it (filename) to php.

AJAX Post To PHP File Not Returning Data On Success

this is the flow I am trying to accomplish:
Form completed -> Data Sent to PHP File With Data -> PHP File Takes Data, Queries API -> PHP File Then Returns Query Results back to Original Page as an echo.
The round trip time for this should be around 10 seconds. Here is my form, AJAX, and PHP file.
Form
<form id="query_form">
<input type="text" id="query_input" name="query_input" required>
<button id="send_btn" type="submit" name="send_query" value="Submit Request">
</form>
AJAX
<script type="text/javascript">
$(document).on("click", "button[id='send_btn']", function(e){
e.preventDefault(); // Prevents any default actions by clicking submit in a form.
var query = $("#query_input").val(); // Gets the value of an input
$.ajax({
type: "POST",
url: "run.php",
data: {query:query},
success: function(r){ alert(r); }
});
});
</script>
PHP
<?php
require('RestClient.php');
$term = "";
if(isset($_POST['query'])){
$term = $_POST['query']
try {
$client = new RestClient('https://api.dataforseo.com/', null, '#########', '###########');
$post_array = array("language" => "en","key" => $term); // This is the term to search, correct?
$sv_post_result = $client->post('v2/kwrd_sv', array('data' => $post_array));
$search_volume = $sv_post_result["results"][0]['sv'];
echo "<div id='results_div'>
<table id='results_table'>
<tr class='results_table_row'>
<td id='SEO_Search_Volume_Cell'>
$search_volume <span>Approximate Number Of Searches Per Month</span>
</td>
</tr>
</table>
</div>";
} catch (RestClientException $e) {
echo "\n";
print "HTTP code: {$e->getHttpCode()}\n";
print "Error code: {$e->getCode()}\n";
print "Message: {$e->getMessage()}\n";
print $e->getTraceAsString();
echo "\n";
echo "An Error Has Occured, Please Try Again Later";
exit();
}
}
?>
Obviously the data echo'd back needs to appear on the same page as the form, yet nothing comes back. Why would this be?
try posting the data in a 'string' format, e.g.
var query = $("#query_input").val(); // Gets the value of an input
var queryString = 'query='+ query; and then use it in your $.ajax call with: data: queryString,
pick-up the value with $_POST['query']

Delete local files and database records with AJAX

I am using ajax to delete files from both database and local. There is no problem on the database side. However I can't delete the correct file from local. I think I can't pass the correct file name... It deletes the local file listed top of the page.
My index.php file:
<p><?php echo $file->name; ?></p>
<input type="hidden" name="file-name" value="<?php echo $file->name; ?>">
<button name="delete" id="delete" value="<?php echo $file->id; ?>">
<span>DELETE</span>
</button>
My delete.php file:
if(isset($_POST['deleteFile'])) {
$delFile = $db->execute("DELETE from files WHERE id='{$_POST['id']}'");
$fname = 'upload/'.$_POST['fname'];
if($delFile){
unlink($fname);
echo "File is deleted!";
}
else{
echo "There was a problem!";
}
}
JS file:
$('body').delegate('#delete','click',function(){
var idDelete = $(this).val();
var nameDelete = $("input[name=file-name]").val();
var parent = $(this).parent().parent();
if(confirm){
$.ajax({
url : "delete.php",
type : "POST",
async : true,
data : {
deleteFile : 1,
id : idDelete,
fname : nameDelete,
},
success: function()
{
parent.fadeOut('slow', function() {$(this).remove();});
}
});
}
});
This is more along the lines of "teach a man to fish" rather than an exact answer because it's hard to tell from your code why that file may or may not be deleted.
First, as other have said your code is extremely dangerous and has the ability for anybody to delete any file on your system - never trust user input. You might also have a SQL injection vulnerability too.
But, as far as your problem, you are not able to see what is going on because you are ignoring or masking bugs with your code. To provide some visibility this is what I would do:
if($delFile){
$fname = __DIR__ . '/' . $fname;
if (unlink($fname)) {
echo "File is deleted!";
}
else {
throw new Exception("Unable to delete file with name " . $fname);
}
}
else{
throw new Exception("Unable to delete DB record with id " . $_POST['id']);
}
Then in your javascript, something to the effect which will output the results of the ajax to the console so you can see what the file path is that is being looked for
if(confirm){
$.ajax({...},
success: function(){...},
error: function(jqXHR){console.log(jqXHR.responseText);}
});
}
That probably won't fix your error, but it will allow you to see what is going on, which is likely to be a simple error with the file path.

upload file using ajax like facebook uploading

My problem is, I want to upload a csv file without pressing a submit button and I used ajax for that case. But now, their is something errors appear, and the error said fopen() Filename cannot be empty. But I already get the file value that I want, but the $_FILES[$fie]['tmp_name'] can't read this value. But if I attach the variable in an alert() they display the exact filename. This is my sample codes.
This is the html:
<form id="Form2">
<input type="file" id="fie" />
</form>
this is the javascript:
<script style="text/javascript">
$(function(){
$('#Form2').change(function(e){
e.preventDefault();
var sub = document.getElementById("fie").files[0].name;
if($('#cat1').hasClass('show')){
$('#cat1').hide();
$('#cat2').html("<img src='pb1.gif' />");
$.ajax({
url:'uploading.php',
action:'get',
data: 'fie='+sub,
success: function(data){
$('#cat2').html(data);
}
});
}
});
});
</script>
This is the Php:
uploading.php
<?php
include("conn.php"); //assuming that connected to a database.
if (isset($_GET['fie'])) {
echo "<script>alert('".$_GET['fie']."')</script>";//IN ALERT THEY EXECUTE THE EXACT VALUE OF THE FILE I INPUT
$fie = $_GET['fie'];
$file = $_FILES[$fie]['tmp_name']; //PROBLEM IS THIS. THEY CAN'T READ THE VALUE AND TELL THEIR IS NO FILE.
$handle = fopen($file,'r') or die ('Cannot open file');
fgets($handle);
do {
if (isset($data[0])) {
mysql_query("INSERT INTO tbl_numbers (numbers,cute) VALUES ('".addslashes($data[0])."','".addslashes($data[1])."')");
}
}
while ($data = fgetcsv($handle,1000,",","'"));
echo "Successful Upload~!";
}
?>
Thanks for the reply.

how do i copy a file on button click?

I want to build a one page utility/prototype that will do the following:
provide the admin user with a drop down box. when they select an option and then click on a submit button, i want to be able to COPY a file from /var/www/mysite/abc.txt to /var/www/mysecondsite/abc.txt
I've written the php / html to display the form, but can I use jquery/ajax to call a function on the same php file?
Here's my code:
<?php
$listofcountries='';
echo "<h2>Select a site</h2>";
echo " <script src='http://myserver/myapp/assets/js/jquery-1.8.1.min.js'></script>";
if ($handle = opendir(dirname(__FILE__)."/secrets/")) {
echo "<input type=text list=site >";
echo "<datalist id=site >";
/* This is the correct way to loop over the directory. */
while (false !== ($entry = readdir($handle))) {
//ignore temporary files, and directories.
if ( (strpos($entry, "~") === false) && !(trim($entry)==".") && !( $entry=="..") ){
//echo "$entry\n<BR>";
$country=getCountryName($entry);
echo "<option>".$country;
}
}
}
closedir($handle);
echo "</datalist>";
echo "<input type=submit id='changert'><BR>";
echo "<script>";
echo "$(document).ready(function(){";
echo " $('#changert').live('click', function() {";
echo " alert('in the changert function'); ";
echo " });";
echo " }); "; //end document ready
echo "</script> "; //end javascript
function getCountryName($fileame)
{
$pattern = '/([a-z]*).([a-z]*).([a-z]*).php/i';
preg_match_all($pattern, $fileame, $matches, PREG_SET_ORDER);
foreach ($matches as $match) {
return $match[1];
}
}
in the real version, this solution will be part of a codeigniter solution... so i'll have a proper MVC.
But for now, I'd like to be able to contain all the logic in one file.
Can you tell me how i can do this?
jQuery is just JavaScript so it's all on the client. Any server-side file copying would still need to be handled by your PHP. Simplest solution is just to make an AJAX request on button click which hits your PHP API and passes a token or something so non-session users aren't copying files maliciously.
$('#myButton').on('click', function(e) {
$.ajax({
url : '/copyFile.php',
data : {
fileName : $('#mySelectMenu').val(),
token : someTokenYourPHPInjectedIntoYourJS
},
type : 'POST',
success : function (data) {
// yay
}
});
});
You should check PHP Documentation at: http://mx2.php.net/manual/en/function.copy.php
There's an exaple to copy a file.
<?php
$file = 'example.txt';
$newfile = 'example.txt.bak';
if (!copy($file, $newfile)) {
echo "failed to copy $file...\n";
}
?>
Remember this directories must exists and be visible to each other (inside the same web server)
Add an Ajax call on your user interface,
$.ajax({
url: 'copy.php',
success: function(data) {
if(data == 'true'){
alert('The file has been copied');
}
}
});
Create a second php file to handle the file copy on request
/* copy.php */
<?php
$result = copy('/dir1', '/dir2');
echo $result?'true':'false';
Of curse, this is over-simplified, you have to do some error-handling input-checking and security improvements, but I just wanted to illustrate the way to go.

Categories