Check if file exists before getting contents - javascript

I have some simple ajax code that gets the contents of text file on the server.
Then puts the contents into a textarea.
It throws a 404 error in the console if the file does not exist.
So I am trying to use php.
But nothing gets returned when I use php.
NoteFileName is a string created earlier that gets the filename (e.g. myfile.txt).
addnote is the id of the textarea.
My original code that gives the 404 error (if the file does not exist):
$.ajax({
url: "upload/" + NoteFileName,
dataType: "text",
success: function(data) {
document.getElementById("addnote").innerHTML = data;
},
error: function() {
alert("note does not exist");
}
});
My attempt at php:
$.ajax({
url: 'ajaxfilenotesget.php',
type: 'GET',
data: {
NoteFileName: NoteFileName,
},
success: function() {
document.getElementById("addnote").innerHTML = notedata;
}
});
The external php file:
$filename = "upload/" . $_GET['NoteFileName'];
if (file_exists($filename)) {
$notedata = file_get_contents($filename);
}
else {
$notedata = "";
}
I also tried (and other variations of this):
$.ajax({
url: 'ajaxfilenotesget.php',
type: 'GET',
data: {
NoteFileName: NoteFileName,
},
success: function(data) {
document.getElementById("addnote").innerHTML = data;
}
});
Just changed to this and get undefined in the textarea:
$.ajax({
url: 'ajaxfilenotesget.php',
type: 'GET',
data: {
NoteFileName: NoteFileName,
success: function(data) {
document.getElementById("addnote").innerHTML = data;
}
}
});

This is the final solution and all is working now with no errors.
The Ajax code:
$.ajax({
url: 'ajaxfilenotesget.php',
type: 'GET',
data: {NoteFileName: NoteFileName},
success: function(notedata) {
document.getElementById("addnote").value = notedata;
}
});
The external PHP file code:
$filename = "upload/" . $_GET['NoteFileName'];
if (file_exists($filename)) {
$notedata = file_get_contents($filename);
}
else {
$notedata = "";
}
echo $notedata;

Related

How do I need to convert this to plain javascript or jquery?

I'm new to JavaScript and jQuery. I'm currenly having the following code in my javascript file, however it doesn't seem to be working. I'm using this from prototype.js :
var url = '/sip/TnsViewScreenResponse';
var myAjax = new Ajax.Request(url, {
method: "post",
headers:{
'X-Requested-By': 'XMLHttpRequest'
},
parameters: "tin=" + tin,
success: function transResult(response) {
document.getElementById('tinVersionsOf_' + tin).innerHTML
= response.responseText;
document.getElementById('ajax_loading_img').style.display
= 'none';
document.getElementById('tinVersionsOf_' + tin).style.display =
'block';
},
error: function transResult(response) {
document.getElementById('ajax_loading_img').style.display = 'none';
alert('Failure: Problem in fetching the Data');
},
}
);
return false;
This seems to be conflicting with the other jQuery files being used in the file, so I want to convert this to plain JavaScript or jQuery. I have tried the below but it doesn't seem to be working. How can I make this right ?
var url = '/sip/TnsViewScreenResponse';
var myAjax = $.ajax({
type: "POST",
url: url,
data: tin,
success: function transResult(response) {
$('#tinVersionsOf_' + tin).html(response.responseText);
$('ajax_loading_img').css("display","none") ;
$('#tinVersionsOf_' + tin).css("display","block");
},
error: function transResult(response) {
$('#ajax_loading_img').hide();
alert('Failure: Problem in fetching the Data');
},
}
});
The above code is getting skipped while being parsed in the browser, which I had checked with inspect element option in Google chrome.
Try This
$.ajax({
type: "POST",
dataType: "json",
contentType: "application/json",
url: "/sip/TnsViewScreenResponse",
data: JSON.stringify({ mydata: tin }),//where tin is ur data
success: function (result) {
//include your stuff
},
error:function(error)
{
// include your stuff
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Cant fetch array from server side

I want to get some data from a php script to my html page. They array $UniqueNames has a value on the server side, but nothing seems to happen when i use json_encode on the html page, the console.log returns an empty array (BilderID). Any suggestions?
code:
<script>
var BilderID = [];
$(document).ready(function (e) {
$('#SubmitBild').on('click', function () {
var form_data = new FormData();
var ins = document.getElementById('Myfilefield').files.length;
for (var x = 0; x < ins; x++) {
form_data.append("Bilder[]", document.getElementById('Myfilefield').files[x]);
}
$.ajax({
url: 'Includes/Bildhantering.php', // point to server-side PHP script
dataType: 'text', // what to expect back from the PHP script
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function (response) {
$('#msg').html(response); // display success response from
},
error: function (response) {
$('#msg').html(response); // display error response from the PHP script
}
});
BilderID = <?php echo json_encode($UniqueNames); ?>
console.log(BilderID);
});
});
</script>
Php:
$UniqueNames = array();
for($i=0;$i<count($file_array);$i++)
{
if($file_array[$i]['error']){
echo $phpFileUploadErrors[$file_array[$i]['error']];
} else {
$extensions = array('jpg','png','gif','jpeg');
$file_ext = explode('.',$file_array[$i]['name']);
$file_ext = end($file_ext);
if (!in_array($file_ext, $extensions)){
echo "Invalid file extension!";
} else {
$fileNameNew = uniqid('', true).".".$file_ext;
$UniqueNames[] = $fileNameNew;
move_uploaded_file($file_array[$i]['tmp_name'], 'Bilder/'.$fileNameNew);
echo $phpFileUploadErrors[$file_array[$i]['error']];
}
}
}
The solution was to remove the datatype specifier, echo out the array in php and receive it inside the success method:
$.ajax({
url: 'Includes/Bildhantering.php', // point to server-side PHP script
//dataType: 'text', // what to expect back from the PHP script
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function (response) {
BilderID = response;
console.log(BilderID);
},
error: function (response) {
console.log("error:");
}
});
i mean, why use "datatype" if javascript figures it out anyway?

jQuery AJAX POST method not working

I am trying to execute the AJAX operation. the call is working fine but the problem I am having is that I am getting an empty string as a response. There is no error in the console. all I get is an empty string. Even when I change the dataType to JSON, I still get the same response.
JavaScript Code:
$.ajax({
url: "data/saveCart.php",
method: "POST",
data: {
cartItem:item
},
dataType: "text",
success: function(data){
console.log(data);
}
});
PHP code:
if(isset($_POST['cartItem'])) {
echo "AJAX successful";
} else {
echo "AJAX failed";
}
It seems like it was caused by not stringifying your data.
var item = {
toothbrush: {
price: 1
}
};
$.ajax({
url: "data/saveCart.php",
method: "POST",
data: {
cartItem: JSON.stringify( item )
},
dataType: "text",
success: function(data){
console.log(data);
}
});

AJAX success function not working when the page is load

here is my code in ajax
function loadcountries()
{
var p = document.getElementById("selectCntry");
while(p.firstChild)
{
p.removeChild(p.firstChild);
}
var data = {
action: "loadccc"
};
jQuery.ajax
(
{
type: "POST",
url: "ajax-ows2.php",
dataType: 'json',
async:false,
data:data,
success: function(msg)
{
alert(msg.test);
}
}
);
}
here is my ajax-ows2.php
<?php
$action = $_POST["action"];
include "dbconnect.php";
if($action == "loadccc")
{
$var = $action;
$response_array['test'] = $var;
header('Content-type: application/json');
echo json_encode($response_array);
}
?>
and here is my function call:
<script>
window.onload = loadcountries;
</script>
my ajax way is different. I really have no idea why it is not alerting when the page is load. Im really sure that my ajax-ows2.php is good and im sure that my function call is correct. Can somebody help me with this. This is not a duplicate one. I tried to used asynch:false but still not working.
try this format:
$.ajax({
method: "POST",
contentType: "application/json; charset=utf-8",
data: data,
url: 'ajax-ows2.php',
success: function (data) {
console.log(data);
},
error: function (error){
console.log(error);
}
});
since you are doing POST method, your data parameter must be a stringify, https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify

jQuery access Ajax Response from PHP function

I have a PHP function where I pass a variable to and it returns an array containing a start date and end date.
<?php
function dateRangeTimeFrame($var1){
...
$date['startDate'] = $startDate;
$date['endDate'] = $endDate;
return $date;
}
?>
I am also trying to use this PHP function in an AJAX call so I can reuse the code. I have added this to the beginning of the page:
if (isset($_POST['dateFunction'])) {
print_r(dateRangeTimeFrame($_POST['dateFunction']));
}
My jQuery code is as follows:
$.ajax({
url: 'includes/functions.php',
type: 'post',
data: { "dateFunction": theDate},
success: function(response) {
console.log(response['startDate']);
console.log(response.startDate);
}
});
My issue is that I do not know how to access the response that the php function is returning.
Here is the response I am getting from the PHP function:
Array
(
[startDate] => 2015/01/17
[endDate] => 2015/02/16
)
How would I go about getting these 2 vars from the PHP response?
You need to use JSON. Your Javascript natively understands and can parse it
if (isset($_POST['dateFunction'])) {
echo json_encode(dateRangeTimeFrame($_POST['dateFunction']));
}
And your jQuery (note I added dataType)
$.ajax({
url: 'includes/functions.php',
dataType: 'json',
type: 'post',
data: { "dateFunction": theDate},
success: function(response) {
console.log(response.startDate);
}
});
<?php
function dateRangeTimeFrame($var1){
...
$date['startDate'] = $startDate;
$date['endDate'] = $endDate;
return json_encode($date);
}
?>
jQuery
$.ajax({
url: 'includes/functions.php',
type: 'post',
data: { "dateFunction": theDate},
dataType: "json",
success: function(response) {
console.log(response.startDate);
}
});
<?php
function dateRangeTimeFrame($var1) {
// ...
$date['startDate'] = $startDate;
$date['endDate'] = $endDate;
echo json_encode($date);
}
?>
Ajax
$.ajax({
url: 'includes/functions.php',
type: 'post',
data: { "dateFunction": theDate },
success: function(response) {
for (var i = 0; i < response.length; i++) {
alert(response[i].startDate);
}
}
});

Categories