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?
Related
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;
I have form with input for attachment:
<form enctype="multipart/form-data" action="" method="post" id="sendInvoiceForm">
.....
<div class="templateDiv">
<span class="invoice_email_label">Email attachments:</span>
<input name="email_attachment[]" type="file" multiple="">
</div>
<div class="templateDiv">
<button id="send_invoice_btn" class="bigButton redButton">Send</button>
</div>
</form>
And js:
data = new FormData($("#sendInvoiceForm")[0]);
data.append('flagSend', 1);
data.append('send_invoice_subject', sendInvoiceSubject);
....
$.ajax({
type: 'POST',
data: data,
processData: false,
contentType: false,
url: sJSUrlSavePdfInvoiceToServer,
dataType: 'json',
success: function (data) {
if (data.msg === 'Error. This invoice number exists.') {
alert(data.msg);
} else {
...
}
},
error: function () {
alert('error');
}
});
I tested and seems it doesnt work. All data pass well, but not file.
When I print_r $_FILES it is empty. What is my error? Thanks.
it's work for me --
var form_data = new FormData($('#submitForm')[0]);
$.ajax({
url: "<?php echo base_url() . 'backends/update_documents' ?>",
type: "POST",
dataType: 'json', // what to expect back from the PHP script, if anything
cache: false,
contentType: false,
processData: false,
data: form_data,
success: function (res) {
// console.log(res);
},
error: function (xhr, ajaxOptions, thrownError) {
//console.log(xhr);
}
});
you can try with cache: false
and mention for button, type="button"
this is what i do and works
append the formdata,
var formData = new FormData(your_form);
// for multiple files , because i need to check
new_files is class, i use because i am creating form dynamically
$.each($(".new_files"), function (i, obj) {
// console.log(obj.files);
$.each(obj.files, function (j, file) {
var max_size = 5120000;
var file_type= file.type;
var match = ["image/jpeg", "image/png", "image/jpg", "application/pdf"];
// after validation etc
// append formdata
formData.append('file[' + j + ']', file);
});
});
// if you want something else,
formData.append("id", $('#kreditornr').val());
// ajax
$.ajax({
type: "POST",
url: "url",
data: formData,
contentType: false, // The content type used when sending data to the server.
cache: false, // To unable request pages to be cached
processData: false, // To send DOMDocument or non processed data file it is set to false
success: function (data) {
// success
}
});
First remove dataType: 'json' Then if it still shows error then replace
data = new FormData($("#sendInvoiceForm")[0]);
with
data = new FormData($("#sendInvoiceForm").prop('files')[0]);
try to send the data via :
data: $('#sendInvoiceForm').serialize();
This is probably very simply but I cannot figure it out. I am using a jquery script I found to display a timer. I then want to send the number of seconds to a PHP file. Below is the script, if I just alert the value variable, it contains the correct data, so I am accessing it correctly but its empty on the PHP side when it arrives.
$('.get-timer-btn').on('click', function() {
var value = $('.timer').data('seconds');
$.ajax({
type: 'POST',
url: 'test.php',
data: { value : value },
cache: false,
success: function(result){
alert(result);
}
});
});
The result alert displays empty based on this test php file
<?php
if (isset($_POST['value'])) {
$value = $_POST['value'];
echo $value;
} else {
$value = "Empty!";
echo $value;
}
?>
I would really appreciate some help.
I thought you must add a header to Ajax object.
edits :
change var name
check URL address
add header
$('.get-timer-btn').on('click', function() {
//change this name !
var value_data = $('.timer').data('seconds');
$.ajax({
type: 'POST',
url: 'test.php', //make sure correct address
headers: {'Accept': 'application/json'}, //add header is so important
data: { value : value_data },
cache: false,
success: function(result){
alert(result);
}
});
});
You must end php hier is a worked example:
<?php
if(isset($_POST['value'])){
$value = $_POST['value'];
echo ($value)?$value:'Empty';
die;}
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<p class="timer" data-seconds="2"></p>
<button class="get-timer-btn">BTN</button>
<script>
$('.get-timer-btn').on('click', function() {
var value = $('.timer').data('seconds');
$.ajax({
type: 'POST',
url: 'test.php',
data: { value : value },
cache: false,
success: function(result){
alert(result);
}
});
});
</script>
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
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);
}
}
});