Can't reach php file with ajax - php

I have a page where one can upload an image and crop it (to do so i've used this plugin), the result of this crop is then saved in a server.
After looking at the documentation i tried this:
JQUERY
var zis = //some div where i uploaded the image;
$('.export').click(function() {
var imageData = $('.image-editor').cropit('export');
zis.find('#img_val').val(imageData);
zis.find('.salvaImmagine').click();
});
PHP
public function immagine_profilo(){
if (isset($_POST['crop'])){
var_dump($_POST['img_val']);
// Get the base-64 string from data
$filteredData = substr($_POST['img_val'], strpos($_POST['img_val'], ",")+1);
// Decode the string
$unencodedData = base64_decode($filteredData);
// image new name
$newfilename = 'images/immProf' . $_SESSION['auth'] . '.png';
file_put_contents($newfilename, $unencodedData);
// saves the path into a database
$query = "UPDATE users SET pic = '{$newfilename}'
WHERE id = {$_SESSION['auth']}";
$result = mysqli_query($_SESSION['connessione'], $query);
return // function to retrive the image;
}
}
So far so good, the images is saved in the server, its path is saves aswell, only one problem remains: the page needs to be reloaded in order to see the image change, ok we can do better: update the image without a page reload.
So i searched the web to find out about ajax, after some time i've come up with this:
JQUERY
$('.export').click(function() {
var imageData = $('.image-editor').cropit('export');
zis.find('#img_val').val(imageData);
lightbox(false);
zis.find('.salvaImmagine').click();
});
$('.salvaImmagine').on('click', function(event) {
event.preventDefault();
var imageData = $('.cop').cropit('export');
$.ajax({
url: 'lib/ottieniCose.php',
type: 'POST',
dataType: 'html',
data: {
crop: 'Salva',
crop_cop: 'Salva',
img_val: imageData
},
})
.done(function(response) {
console.log("success");
$(".copertina").css('background-image', 'url(' + response + ')');
})
.fail(function() {
console.log("error");
})
});
PHP (lib/ottieniCose.php)
//rquire bla bla bla
if (isset($_POST['crop']) || isset($_POST['crop_cop'])) {
var_dump("test");
//calls the function to save the image
$login->immagine_profilo();
}
Now, i get absolutely no result, the images isn't saved, the path isn't saved, the php page doesn't seem to be called at all (althoug there are no 404 errors) but the image is being cropped, i know that by looking into the code.
I also tried changing the POST method to GET method in ajax, but i get error 414, any help?
the HTML
<div id="lightbox">
<div class="image-editor">
<div class="scegliImm">
<p>Scegli un'imagine</p>
</div>
<input type="file" class="cropit-image-input">
<div class="cropit-image-preview-container">
<div class="cropit-image-preview" style="background-image: url(<?php print $login->get_profile_pic() ?>)"></div>
</div>
<div class="image-size-label">
<p>Nessuna immagine selzionata,<br> seleziona un'immagine.<br>P.S. Puoi trascinare l'immagine<br> nuova sopra quella vecchia</p>
<div class="esci">
<p>Esci</p>
</div>
</div>
<div class="neh">
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<div>
<input type="hidden" name="img_val" id="img_val" value="">
<input type="submit" name="crop" value="Salva" class="salvaImmagine">
</div>
</form>
<div id="salvaImma">
<input type="range" class="cropit-image-zoom-input">
<button class="export">Salva</button>
</div>
</div>
</div>
</div>

Try to give absolute path to that ajax call or if your lib folder at the root of your website then use backslash before the lib
so your url will be :- /lib/ottieniCose.php
It may help you.

Related

Passing HTML form values / loading .php file

I'm trying to pass the parameter of a form $_POST['txtBody'] into a div via jquery/javascript.
the PHP file to be loaded:
ajax-rewriter.php
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
print_r($_POST);
$articleBody = strtolower($_POST['txt']);
echo "<pre><b>Original:</b><br /><br /><p>" . $articleBody . "</p></pre>";
$word = "";
$length = strlen($articleBody);
$OutputBody = "";
for ($i = 0; $i < $length; $i++) {
$word = $word . $articleBody[$i];
if ($i == $length - 1)
$comeCha = " ";
else
$comeCha = $articleBody[$i + 1];
$retStr = getWordPattern($word, $comeCha, "syn/en.syn");
if ($retStr != "") {
$OutputBody .= $retStr;
$word = "";
}
}
echo "<br>";
echo "<pre><b>Spun:</b><br /><br /><p>" . $OutputBody . $word . "</p></pre>";
}
?>
The HTML form:
<div id="mainContent"></div>
<div class="panel panel-primary">
<div class="panel-heading">Your article rewriter API is: (<span class="results"><b>http://www.wraithseo.com/api.php?rewriter=1&key=<?php echo $user['api_key']; ?></b></span>)</div>
<div class="panel-body">
<form id="frmAjax" action="rewriter.php" method="post" class="form-horizontal container-fluid" role="form">
<div class="row form-group">
<div class="col-sm-4 text-right"><label for="txtBody" class="control-label">Article:</label></div>
<div class="col-sm-8"><textarea class="form-control" id="txtBody" name="txtBody" required="required"></textarea></div>
</div>
<div class="row form-group">
<div class="col-sm-12 text-right">
<button type="submit" name="spinText" class="btn btn-default">Spin!</button>
</div>
</div>
</form>
</div>
<div class="panel-footer">Paste in an article above and hit <b>Spin</b>!</div>
</div>
<script>
$(document).ready(function(){
$('#frmAjax').submit(function(e) {
e.preventDefault(); // important so the submit doesn't clear the data...
$.ajax({
type: "POST",
url: "ajax-rewriter.php",
data:{ txt: <?php echo $_POST['txtBody']; ?> }
})
$("#mainContent").load('ajax-rewriter.php')
});
});
</script>
I have tried but cannot remember the proper way to pass the $_POST['txtBody'] value to the loaded .php file and show it in the div
Any help would be appreciated.
So it looks like you want to send whatever is typed into the <textarea class="form-control" id="txtBody" name="txtBody" required="required"></textarea> element to be passed to the php file ajax-rewriter.php for processing via JQuery ajax, correct?
I don't think you should be trying to get from your $_POST variable inside your AJAX request. Rather, you're sending the value of the textarea through your AJAX request (which is utilizing the POST method to send the data).
Here is what I believe you are looking for:
$(document).ready(function(){
$('#frmAjax').submit(function(e) {
var text = $('#txtBody').val(); // ADDED THIS
e.preventDefault();
$.ajax({
type: "POST",
url: "ajax-rewriter.php",
data:{textData : text} // MODIFIED THIS
})
$("#mainContent").load('ajax-rewriter.php')
});
});
Then, in your php file, you can get the text variable through the $_POST variable:
$data = $_POST["textData"];
You can then choose what to do whatever you want with the data in your php file. If you are trying to send the data via ajax to php, modify it via php, then send it back as a response to the ajax request, look into JQuery's success and complete callback functions that are part of the JQuery ajax call.
Here is an example using the success callback:
$.ajax({
type: "POST",
url: "email.php",
data: {fullName, phoneNumber, email, comments, response},
success: function(dataRetrieved){
$("#response").html(dataRetrieved);
}
});
The php file email.php receives the data via $_POST through the ajax request, processes it, and then the email.php file will echo data as output from the server. The data that is echoed is sent back as a response to the ajax request, which can be retrieved as a parameter in the success callback.

Cant make my upload form work using 2 versions of jQuery despite jQuery.noConflict()

I have one webpage that has 2 different forms in it, the 1st one is for uploading pictures (and it's supposed to give the link of the freshly uploaded images), and the second one is a "regular" form that allows to add a product to the database, in which I use the links given by the 1st form. The problem is that I use bootstrap's jQuery, and the upload form uses the 1.7.2 version (no need to say, there are conflicts.)
Once I hit the "send" button, it's supposed to make a loading bar appear and show "100%", followed by the image URL, while the upload process is done in another file named 'upload.php'
The problem is, even though I used 'jQuery.noConflic();' it still continues to redirect me to upload.php where there's nothing to see, but I can't find the problem...
Here's the upload form :
<form id="myForm" action="upload.php" name="upload" method="post" enctype="multipart/form-data">
<div class="form-group">
<label class="col-md-4 control-label" for="filebutton">Uploader une image</label>
<div class="col-md-3">
<input id="filebutton" name="filebutton" class="input-file" type="file">
<div id="progress">
<div id="bar"></div>
<div id="percent">0%</div >
<br />
<div id="alerte"></div>
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label" for="envoyer"></label>
<div class="col-md-3">
<button type="file" value="envoyer" id="formenvoyer" name="myfile" class="btn btn-primary">Envoyer</button>
</div>
</div>
</div>
</form>
Here is the PHP file :
<?php
$output_dir = "img/";
if(isset($_FILES["myfile"]))
{
//Filter the file types , if you want.
if ($_FILES["myfile"]["error"] > 0)
{
echo "Error: " . $_FILES["file"]["error"] . "<br>";
}
else
{
//move the uploaded file to uploads folder;
move_uploaded_file($_FILES["myfile"]["tmp_name"],$output_dir. $_FILES["myfile"]["name"]);
echo "<p>Uploaded File :<br />http://grindhouseleather.esy.es/admin/img/".$_FILES["myfile"]["name"]."</p>";
}
}
?>
And here's the JS :
jQuery = jQuery.noConflict();
jQuery(document).ready(function()
{
var options = {
beforeSend: function()
{
$("#progress").show();
//clear everything
$("#bar").width('0%');
$("#alerte").html("");
$("#percent").html("0%");
},
uploadProgress: function(event, position, total, percentComplete)
{
$("#bar").width(percentComplete+'%');
$("#percent").html(percentComplete+'%');
},
success: function()
{
$("#bar").width('100%');
$("#percent").html('100%');
},
complete: function(response)
{
$("#alerte").html("<font color='green'>"+response.responseText+"</font>");
},
error: function()
{
$("#alerte").html("<font color='red'> ERROR: Impossible d'uploader les fichiers</font>");
}
};
$("#myForm").ajaxForm(options);
});
What did I miss ?
Thank you in advance !
You shouldn't use jQuery for jQuery.noConflict();. Change it to:
jq = jQuery.noConflict();
The reason is:
jQuery = jQuery.noConflict();
The above code makes no difference.

Getting file out of url with php

So I give my users the possibility to upload a xml file of their iTunes playlist. Once they've uploaded their xml-file, i need to read out that xml file. I tried it first with just an ajax call and a local xml file and it worked fine, but now i need to get acces to the uploaded xml file.
This is my upload form
<form id="formulier" action="playlist.php" method="post" enctype="multipart/form-data">
<fieldset>
<legend>Upload your playlist</legend>
</br>
<label>
<input type="file" name="bestand">
</label>
</br>
</br>
<input type="submit" value="Generate">
</fieldset>
this is my playlist.php file:
<?php
$path = "playlists/" . ($_FILES['bestand']['name']);
if(move_uploaded_file($_FILES['bestand']['tmp_name'], $path)){
}
header("Location:index.html?url=".$path);
?>
this is my ajax call that i previously used:
var my_fn = function(callback) { // <-- this is callback to be called later
var jax = [];
$.ajax({
url: "",
dataType: "xml",
success: function (data) {
var song = $(data).find('key').filter(function () {
return $(this).text().indexOf('Name') != -1;
}).each(function() {
var content = $(this).next('string').text();
jax.push(content);
});
callback(jax);
}
});
};
How do I get to read out the xml file that is uploaded by the user? I really do not have a clue...

how to upload image using ajax in php

<div class="control-group">
<label class="control-label" for="inputEmail">Image</label>
<div class="controls">
<input type="file" value="Browse" name="image" id="image" />
<span style="color: #61625F; font-weight: bolder;" class="sixth"></span>
</div>
</div>
ajax code below
$("#reg").click(function() {
$.ajax({
url: "process_service_person_register.php",
type: "post",
data: "image": $("#image").val()},
});
how will i send the image to the "process file"
You have to use the FormData object.
<script>
if ("FormData" in window)
{
var fd = new FormData();
fd.append('file', $('#image')[0].files[0]);
$.ajax({
url: "process_service_person_register.php",
data: fd,
processData: false,
contentType: false,
type: 'POST',
success: function(result) {
console.log(result);
}
});
}
else
{
console.log('sorry, FormData object is not available.');
}
</script>
Without FormData, you will have to go old school like using the hidden iframe method
Here is my php page when i post through ajaxform
<?php
include('phpfunc.php');
$path = "images/news/";
$utime = time();
$valid_formats = array("jpg", "png", "bmp","jpeg","gif");
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST"){
$name = strtolower($_FILES['uploadnews']['name']);
if(strlen($name)){
$extpos = strrpos($name, '.', -1);
$ext = substr($name,$extpos+1);
if(in_array($ext,$valid_formats)){
$actual_image_name = $utime.".".$ext;
$fpath = $path.$actual_image_name;
$tmp = $_FILES['uploadnews']['tmp_name'];
if(move_uploaded_file($tmp, '../'.$fpath)){
echo $fpath;
}else{
echo "failed";
}
}else{
echo "Invalid file format..";
}
}else{
echo "Please select image..!";
}
exit;
}
?>
There is no way to upload files using AJAX
BUT, you can imitate the behavior of AJAX by using hidden Iframe (other ways exists - but this is the most compatible way for old and new browsers)
for example:
This is your form:
<form target="upload_frame" action="upload_handler.php" method="POST" enctype="multipart/form-data">
<div class="control-group">
<label class="control-label" for="inputEmail">Image</label>
<div class="controls">
<input type="file" value="Browse" name="image" id="image" />
<span style="color: #61625F; font-weight: bolder;" class="sixth"></span>
</div>
</div>
</form>
Now you should have a hidden IFrame inside your page, and name it upload_frame
<iframe name="upload_frame" id="upload_frame" width="1" height="1" frameborder="no" ></iframe>
And in upload_handler.php or whatever file that suppose to handle your upload request you should output something like
<script type="text/javascript">
window.parent.onUploadCallback(callback_data);
</script>
This will call onUploadCallback function set on the original's page JavaScript.
The callback_data parameter better be JSON serialized so you can use it inside the function as a native JavaScript object.
For example:
function onUploadCallback(response){
if(response.success)
alert("File uploaded: "+response.file_path);
} else {
alert("Error while uploading the file: "+response.error_message);
}
}
For making the all thing more generic - you should use "JSONP" like style and pass "callback" parameter to upload_handler.php with the name of the function you want to call. and then add it to the form as hidden field <input type="hidden" name="callback" value="window.parent.onSuccessCallback" />
After all that description - my real suggestion to you is - use an already made jQuery library for the task

Upload on iframe in modal

I have a modal containing a form and an iframe.
The form has a file field and post to the iframe.
The php controller return the uniqid (basically the name) of the uploaded file.
The upload works well and my iframe contains the uniqid.
I would like to display this uniqid on my main page.
My issue is that I don't know how to wait the end of the upload to show the uniqid.
The form and iframe :
<form id="uploadForm" enctype="multipart/form-data" action="{{ path('lesson_upload') }}" target="uploadFrame" method="post">
<label for="uploadFile">Document :</label>
<input id="uploadFile" name="uploadFile" type="file" />
<br /><br />
<input class="btn btn-primary" id="uploadSubmit" type="submit" value="Upload" />
</form>
<div id="uploadInfos">
<div id="uploadStatus">Aucun upload en cours</div>
<iframe hidden id="uploadFrame" name="uploadFrame"></iframe>
</div>
The JavaScript to fill the modal with the form :
$(document).on('click', '#computer-upload', function ()
{
var url = Routing.generate('lesson_upload_computer');
$.get(url, function (data)
{
$('#modal-various .modal-body').html(data);
return false;
});
return false;
});
The iframe at the end of an upload :
<div id="uploadInfos">
<div id="uploadStatus">Aucun upload en cours</div>
<iframe hidden="" id="uploadFrame" name="uploadFrame">
#document
<html>
<body>
<body>533ebac647b7e</body>
</body>
</html>
</iframe>
</div>
Does anyone have an idea ?
Thanks !
If you don't use an AJAX upload, after a little research, you cannot add an event that detects when the upload has finished.
You now have 2 options:
Fetch the id from the iframe every ~100ms and if it is not empty or null, the id will be in:
document.checkForId = function() {
id = $('#uploadFrame').contents().find('#idInIframeDivOrOtherContainer');
if (id) {
window.clearInterval(intervalId);
}
};
$(document).ready(function() {
intervalId = window.setInterval('document.checkForId', 100);
});
When posting data, return javascript that sets the id in the main page (if you have jquery in the iframe):
<script>
$(document).ready(function() {
$('#divInParentWindow', parent.document).text('<?php echo $id; ?>');
});
</script>
If your iFrame has its source on the same server/domain level as your main page. You could simply define a function at your main page
function iframeHasLoaded() {
var body = document.getElementById('uploadFrame').contentWindow.document.body.innerHTML;
}
And, from your iFrame
window.onload=function() { parent.iframeHasLoaded() };
This should work.

Categories