Javascript & PHP ajax error: "Undefined array key" - javascript

for several days I have been facing the problem that PHP cannot find my index.
What I've tried:
Change the data name in ajax
I added the code from PHP Create.php to create.php (at the beginning and at the end of the code)
Various ajax possibilities
The goal
I want to save an image which I have cropped with (cropper.js), using PHP on a SQL server.
My code:
OnSetData.js
canvas = cropper.getCroppedCanvas({
width:700,
height:700
});
canvas.toBlob((blob) => {
url_img = URL.createObjectURL(blob);
//url_img = blob:https://localhost/a37a7cd8-ad48...
$.ajax(
{
url:'assets/php/PHPCreate.php',
type: 'POST',
data: {'image':url_img},
success:function(output) {
console.log('Upload success: ' + output);
//Upload sucess: <output is empty>
},
error() {
console.log('Upload error');
},
});
}, 'image/png');
PHPCreate.php
if (isset($_POST['save_submit']))
{
$data = $_POST["image"];
//Warning: Undefined array key "image" in ..\assets\php\PHPCreate.php on line ..
echo($data);
}
create.php
<link href="assets/assets/cropperjs-main/dist/cropper.css" rel="stylesheet">
<script src="assets/assets/cropperjs-main/dist/cropper.js"></script>
<script src="assets/js/jquery.min.js"></script>
<script src="assets/bootstrap/js/bootstrap.min.js"></script>
<script src="assets/js/OnSetData.js"></script>
<?php
include './assets/php/PHPCreate.php';
?>
.
.
.
.
<form id="formUpload" action="" method="post" class="form-inline" enctype="multipart/form-data">
<button class="btn btn-primary text-uppercase" role="button" name="save_submit" type="submit">Save</button>
</form>

i think you will open create.php in browser
create.php has a form that sends "save_submit" to izself as a new request
so create.php will be opened again but this time with "save_submit", nothing else, so yes, there is no image, that is correct
now lets look at OnSetData.js:
it makes a separate request to PHPCreate.php with "image", but no "save_submit" so PHPCreate.php will do nothing
to clearify:
the button in the form will make a site navigation
OnSetData.js will make a request on its own
both request are handled in separate

Related

how to make a request several times without hard refresh with ajax

I send a request via ajax to delete a file. The first time , ajax handles the request, but the second time not anymorte. i got a "hard refresh"
This is my code:
<?php
if(isset($_POST['deletefile'])) {
// if is directory -> remove dir
if(is_dir($_POST['deletefile'])){
removeDirectory($_POST['deletefile']);
exit;
}
// else (must be a file) -> unlink file
else {
unlink($_POST['deletefile']);
exit;
}
}
?>
<div class="myFiles">
<form class="sfmform" method="post" action="">
<input type="hidden" name="deletefile" value="<?php echo $dir.'/'.$file; ?>" />
<input type="submit" class="sfmdelete" name="delete" value=" " />
</form>
<script>
$(".sfmform").on('submit',(function(e) {
e.preventDefault();
$.ajax({
url: "",
type: "POST",
data: new FormData(this),
contentType: false,
processData: false,
success: function(response)
{
$('.myFiles').load(document.URL + ' .myFiles');
},
});
}));
</script>
</div> <!-- END myFiles -->
To see immediately when i file has been deleted, i use this line
$('.myFiles').load(document.URL + ' .myFiles');
The first delete request goes fine, but the second: he makes a hard refresh and dies in the php loop. I was hoping that after the exit in the php the line $('.myFiles').load(document.URL + ' .myFiles'); was executing but the second time it loads not the <div class="myFiles> anymore.
How can i make this work properly?
Even when i put the js in the ready handler, it does not work!
The reason why i use an exit in the php: otherwise the <div class="myFiles"> appears 2 times under each other
You changed the html of .myFiles so everything in it in the second time is dynamically generated . so you need Event binding on dynamically created elements? .. change
$(".sfmform").on('submit',(function(e) {
to
$(document).on('submit' , ".sfmform" , (function(e) {
Note: for me its not a good practice to use $.ajax with the same file url: better for me to make a separate file

Send php request onclick via ajax

I know this question have been asked alot but none of the answer are related to my case ,I have a button ,onclick it should call a javascript function send it a php variable,and ajax would call a php file via post and send that vriable and the php file updates my table
so here is the onclick event first
<button class="button button6 " onclick="incrementclicks('<?php echo $id; ?>');">increment</button>
it should send a variable called $id to the javascript function
<script type="text/javascript">
function incrementclicks(id) {
$.ajax({
url: "increment.php",
data: "id=" + id,
type: "POST"
});
}
</script>
and the php file increment.php (I'm 100% sure it connects to the server just fine )
<?php
require_once 'dbconnect.php';
$db_handle = new DBController();
$id=$_POST["id"];
$q="UPDATE clicks SET linkclicks = linkclicks + 1 WHERE id = '".$id."'";
$result = mysql_query($q);
?>
it doesn't increment, I don't understand what did i do wrong here
First of all you can debug your code on the php by doing
echo $id;
exit();
My quess is that your are missing something there..
Use this method of ajax to check the issue.And if error found check in console for the issue
$.ajax({
url: "increment.php",
type: "post", //send it through post method
data: {
id:id
},
success: function (response) {
alert("success");
},
error: function (xhr) {
//Do Something to handle error
alert("some error found");
}
});
NB:Try to add type="button" to your button for not to reload
<button class="button button6 " onclick="incrementclicks(5);" type="button">increment</button>
I just want to answer this if anyone have future problems like this
The problem is I forgot to add script src at the beginning
<script src="https://code.jquery.com/jquery-2.1.1.min.js" type="text/javascript"></script>
after adding this my code worked just fine :)

Upload PDF using AJAX

I'm trying to upload a PDF document using AJAX, but it keeps on failing with an unknown error. What am I doing wrong?
HTML File:
<form id="document">
<p>
Title<br>
<input type="text" name="name" size="30">
</p>
<p>
Please specify a file, or a set of files:<br>
<input type="file" name="datafile" size="40">
</p>
<div>
<input id="submit-button" type="button" value="Send">
</div>
</form>
<script src="jquery.js"></script>
<script>
$(document).ready(function(){
$('#submit-button').click(function() {
$.ajax({
type: "POST",
dataType: "JSON",
url: "upload_document.php",
data: $("#document").serialize(),
success : function(data){
alert(data.message);
}, error : function(data) {
alert(data.message);
}
});
});
});
</script>
PHP File (upload_document.php)
<?php
header("Access-Control-Allow-Origin: *");
try {
$id = "[RANDOM_GENERATED_GUID]";
$targetDir = "../../../../modules/sites/documents/";
if (!is_dir($targetDir)) {
if (!mkdir($targetDir, 0777, true)) {
throw new Exception("Unable to upload your document. We were unable to create the required directories");
}
}
$targetFile = $targetDir . $id . ".pdf";
$fileType = pathinfo($targetFile, PATHINFO_EXTENSION);
if (file_exists($targetFile)) {
throw new Exception("Unable to upload your document. The file already exists");
}
if ($_FILES["datafile"]["size"] > 2000000) {
throw new Exception("Unable to upload your document. The file is to large (Maximum of 2MB)");
}
if ($fileType != "pdf") {
throw new Exception("Unable to upload your document. Only PDF documents can be uploaded");
}
if (!move_uploaded_file($_FILES["datafile"]["tmp_name"], $targetFile)) {
//Keeps failing here with error code 0
throw new Exception("Unable to upload your document. There was an error uploading the file");
}
echo json_encode(array(
"error" => false,
"message" => "Your document was successfully uploaded"
));
} catch (Exception $ex) {
echo json_encode(array(
"error" => true,
"message" => $ex->getMessage()
));
}
I also checked on the server, and the directory is being created successfully. Thanks for the help!
Edit
This exact same PHP script works if I set the action on the form, and use a submit button. The only reason I want to use AJAX, is to display a modal dialog after receiving a response
When you start using AJAX POST, the posted parameter should be looked for in $_POST instead of $_FILES.
This is because $_FILES is a cache for files uploaded through multipart post. Since you have serialized it and sent using AJAX, PHP parses the JSON and put everything inside $_POST
Look here for an example

using POST to send js variable to php from iframe

I am trying to pass a variable from js to a backoffice page.
So far I've tried using a form and submitting it from javascript (but that refreshes the page, which I don't want)
I ditched the form and when for an iframe (so the page doesn't reload everytime the data is submitted). The function is run every few seconds (so the form should be submitting):
<iframe style="visibility:hidden;display:none" action="location.php" method="post" name="location" id="location">
<script>
/*Some other stuff*/
var posSend = document.getElementById("location");
posSend.value = pos;
posSend.form.submit();
</script>
However my php page does not display the value posted (im not quite sure how to actually get the $_POST variable):
<?php
$postion = $_POST['location'];
echo $_POST['posSend'];
echo "this is the";
echo $position;
?>
I also tried $.post as suggested here Using $.post to send JS variables but that didn't work either.
How do I get the $_POST variable value? I cannot use $_SESSION - as the backoffice is a different session. What is the best method to do this?
EDIT I'd rather avoid ajax and jquery
And i think you no need to use form or iframe for this purpose . You just want to know the user onf without refreshing then use the following method with ajax.
index.html the code in this will
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<script>
navigator.geolocation.getCurrentPosition(function(position)
{
pos = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
$.ajax(
{
url:'location.php',
type: 'POST',
datatype: 'json',
data: {'pos':pos}, // post to location.php
success: function(data) {
aler(data);
// success
},
error: function(data) {
alert("There may an error on uploading. Try again later");
},
});
});
</script>
location.php
echo "position :=".$_POST['pos'];
Instead of using iframe to submit your form with out reloading you submit form using ajax call.
$.ajax({
type: "POST",
url: url,
data: $("#formId").serialize(), // This will hold the form data
success: success, // Action to perform on success
dataType: "JSON" or "HTML" or "TEXT" // return type of function
});
There are various alternative to submit the form without reloading the page check here
Thanks
You can use plugin ajaxForm. On action and method you can form options
$(function() {
$('#form_f').ajaxForm({
beforeSubmit: ShowRequest, //show request
success:SubmitSuccesful, //success
error: AjaxError //error
});
});
Lakhan is right, you should try to use ajax instead of an iframe as they cause a lot of issues. If you absolutely need to use an iframe add a target attribute to your form (target the iframe not the main page) and only the iframe will reload.
<form action="action" method="post" target="target_frame">
<!-- input elements here -->
</form>
<iframe name="target_frame" src="" id="target_frame" width="XX" height="YY">
</iframe>
Here's a fully worked example that makes use of a <form>, the FormData object and AJAX to do the submission. It will update the page every 5 seconds. Do note that in PHP, the use of single quotes ( ' ) and double quotes ( " ) is not always interchangeable. If you use single quotes, the contents are printed literally. If you use double-quotes, the content is interpretted if the string contains a variable name. Since I wanted to print the variable name along with the preceding dollar sign ($) I've used single quotes in the php file.
First, the PHP
location.php
<?php
$location = $_POST['location'];
$posSend = $_POST['posSend'];
echo '$location: ' . $location . '<br>';
echo '$posSend: ' . $posSend;
?>
Next, the HTML
index.html
<!DOCTYPE html>
<html>
<head>
<script>
"use strict";
function byId(id,parent){return (parent == undefined ? document : parent).getElementById(id);}
function myAjaxPostForm(url, formElem, successCallback, errorCallback)
{
var ajax = new XMLHttpRequest();
ajax.onreadystatechange = function()
{
if (this.readyState==4 && this.status==200)
successCallback(this);
}
ajax.onerror = function()
{
console.log("AJAX request failed to: " + url);
errorCallback(this);
}
ajax.open("POST", url, true);
var formData = new FormData(formElem);
ajax.send( formData );
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
window.addEventListener('load', onDocLoaded, false);
function onDocLoaded()
{
var submitIntervalHandle = setInterval( doAjaxFormSubmit, 5000 ); // call the function to submit the form every 5 seconds
}
function doAjaxFormSubmit()
{
myAjaxPostForm('location.php', byId('myForm'), onSubmitSuccess, onSubmitError);
function onSubmitSuccess(ajax)
{
byId('ajaxResultTarget').innerHTML = ajax.responseText;
}
function onSubmitError(ajax)
{
byId('ajaxResultTarget').innerHTML = "Sorry, there was an error submitting your request";
}
}
</script>
<style>
</style>
</head>
<body>
<form id='myForm'>
<input name='location'/><br>
<input name='posSend'/><br>
</form>
<hr>
<div id='ajaxResultTarget'>
</div>
</body>
</html>

AJAX Code For Uploading

My html page for uploading has only two things on it: a file open button, and a Submit. It's no problem getting the open dialog up, but after the user clicks OK, where can I find the path string?
</td>
<td style="width: 109.8pt; padding: .75pt .75pt .75pt .75pt" width="146">
<input id="file" name="file" type="file">
<p class="MsoNormal"> </p>
</td>
Does the php file below come with development tools, or is it part of default Windows javaScrpt?
action="upload.php"
Pekka is correct, this has nothing to do with either asp.net or javascript. When you submit a file upload (whether it be in an asp.net app or php) there will be some standard Response information, some of which will be details on the selected file (filename, etc.).
A quick Google search brings up several open source PHP upload utilities, as well as file upload DOM references, such as:
http://sourceforge.net/projects/uploadtool/
http://www.tizag.com/phpT/fileupload.php
http://www.w3schools.com/php/php_file_upload.asp
I'd recommend editing your question to exclude the asp.net tag and replace it with PHP. That way more PHP developers will see your question.
Try the below code
You have to make an "images" folder in the current directory and make two files :
1: Index.php 2: upload.php
You will also get the image name in the success which can be used for saving image name in the database.
1: Index.php
<html>
<head>
<title>
</title>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript" >
var imgName = "";
$(function () {
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
url: "upload.php",
type: "POST" ,
data: new FormData(this),
contentType: false,
cache: false,
processData: false,
success: function (data) {
data = JSON.parse(data);
imgName = data.path;
var pic = imgName;
},
error: function () {}
});
});
});
</script>
</head>
<body>
<form enctype="multipart/form-data">
<input type="file" name="pic" id="pic">
<br>
<input name="submit" type="submit" value="Submit">
</form>
</body>
</html>
2: Upload.php
<?php
if (is_array($_FILES)) {
if (is_uploaded_file($_FILES['pic']['tmp_name'])) {
$sourcePath = $_FILES['pic']['tmp_name'];
$targetPath = "./images/" .time(). $_FILES['pic']['name'];
if (move_uploaded_file($sourcePath, $targetPath)) {
$imgPath['path']=$targetPath;
echo json_encode($imgPath);
}
}
}

Categories