Using AJAX to change a file in PHP - php

I'm trying to duplicate a file and put some information in. First I used the form-method-action (Method 1). This worked. But I wanted to used Ajax to stay on the same page. So then I created Method 2 but this method doesn't work.
This is how my folder looks like. The 'Document.docx' has '$naam' in it's file
HTML METHOD 1:
<form method="post" action="kopie.php">
<ul>
<li><input type="text" name="factuur" id="factuur" placeholder="factuurnaam"></li>
<li><input type="text" name="naam" id="naam" placeholder="naam"></li>
<li><input type="submit" name="submit" id="submit"></li>
</ul>
<h2 class="ans"></h2>
</form>
HTML METHOD 2:
<ul>
<li><input type="text" name="factuur" id="factuur" placeholder="factuurnaam"></li>
<li><input type="text" name="naam" id="naam" placeholder="naam"></li>
<li><input type="submit" name="submit" id="submit"></li>
</ul>
<h2 class="ans"></h2>
<script type="text/javascript">
$(document).ready(function(){
$("#submit").click(function() {
$.ajax({
url: 'kopie.php',
method: 'POST',
data: {
factuur: factuur,
naam: naam
}
success: function() {
$('#ans').html("It worked");
}
})
})
})
</script>
PHP FOR BOTH METHODS:
$factuur = $_POST['factuur'];
$zip = new ZipArchive;
//This is the main document in a .docx file.
$fileToModify = 'word/document.xml';
$wordDoc = "Document.docx";
$newFile = $factuur . ".docx";
copy("Document.docx", $newFile);
$naam2 = $_POST['naam'];
if ($zip->open($newFile) === TRUE) {
$oldContents = $zip->getFromName($fileToModify);
$newContents = str_replace('$naam', $naam2, $oldContents);
$zip->deleteName($fileToModify);
$zip->addFromString($fileToModify, $newContents);
$return =$zip->close();
If ($return==TRUE){
echo "Success!";
}
} else {
echo 'failed';
}
$newFilePath = 'factuur/' . $newFile;
//Move the file using PHP's rename function.
$fileMoved = rename($newFile, $newFilePath);

You need to define your input value on your data.
$(document).ready(function(){
$("#submit").click(function() {
$.ajax({
url: 'kopie.php',
method: 'POST',
data: {
factuur: $('input[name=factuur]').val(),
naam: $('input[name=naam]').val()
},
success: function() {
$('#ans').html("It worked");
}
})
})
})

Try this in your AJAX - I'll note the changes.
$(document).ready(function(e){
e.preventDefault(); //keeps the page from refreshing
$("#submit").click(function() {
//notice I'm gathering the form data here.
var data = { 'factuur' : $("#factur").val(),
'naam' : $("#naam").val()
}
$.ajax({
url: 'kopie.php',
method: 'POST',
data: data, //referencing the data variable above
dataType: html
success: function() {
$('#ans').html("It worked");
}
})
})
})

Related

Post and display data on the same page using PHP (MVC) AJAX

I'm trying to post input data and display it on the same page (view_group.php) using AJAX but I did not understand how it works with MVC, I'm new with MVC if anyone could help me it would be very helpful for me.
view_group.php
<script type = "text/javascript" >
$(document).ready(function() {
$("#submit").click(function(event) {
event.preventDefault();
var status_content = $('#status_content').val();
$.ajax({
type: "POST",
url: "view_group.php",
data: {
postStatus: postStatus,
status_content: status_content
},
success: function(result) {}
});
});
}); </script>
if(isset($_POST['postStatus'])){ $status->postStatus($group_id); }
?>
<form class="forms-sample" method="post" id="form-status">
<div class="form-group">
<textarea class="form-control" name="status_content" id="status_content" rows="5" placeholder="Share something"></textarea>
</div>
<input type="submit" class="btn btn-primary" id="submit" name="submit" value="Post" />
</form>
<span id="result"></span>
my controller
function postStatus($group_id){
$status = new ManageGroupsModel();
$status->group_id = $group_id;
$status->status_content = $_POST['status_content'];
if($status->postStatus() > 0) {
$message = "Status posted!";
}
}
first in the ajax url you must set your controller url , then on success result value will be set on your html attribute .
$.ajax({
type: "POST",
url: "your controller url here",
data: {
postStatus: postStatus,
status_content: status_content
},
success: function(result) {
$('#result).text(result);
}
});
Then on your controller you must echo the result you want to send to your page
function postStatus($group_id){
$status = new ManageGroupsModel();
$status->group_id = $group_id;
$status->status_content = $_POST['status_content'];
if($status->postStatus() > 0) {
$message = "Status posted!";
}
echo $status;
}

Single file upload jquery php

I'm sure I've made a simple error on this one. The file isn't being passed to the php page (I get the "Not uploaded:File error. Please try again." error passed back from the PHP page.)
The code works fine without the JQUERY so I guess the PHP is not the problem.
I've checked the field name / id & it seems OK. I tried testing to see if the value of the button was being passed and it wasn't, that's when I came to the conclusion it was probably the JQUERY but then I was stumped.
I know similar posts have been submitted (I've read them) but I'm desperate!!
Thank you in advance.
Here's the HTML:
<form action="upload.php" name="formname" ENCTYPE="multipart/form-data" id="formid">
<fieldset>
<legend>File info</legend>
<p>
<label for="file1">Files<span class="red"> *</span></label>
<input name="file1" type="file" />
</p>
</fieldset>
<p><label> </label><input type="button" id="submit" value="Add" /></p>
</form>
<div id="output"></div>
<script>
$(function(){
$('#submit').on('click', function(){
var fd = new FormData($("#formid"));
$.ajax({
url: 'upload.php',
type: 'POST',
data: fd,
success:function(data){
$('#output').html(data);
},
cache: false,
contentType: false,
processData: false
});
});
});
</script>
and the PHP
<?php
$strName = 'JoeBloggs';
$intId = 1045;
$missing = '';
date_default_timezone_set("Europe/London");
error_reporting(E_ALL);
include('class.upload.php');
// where to put the images?
$dir_dest = '../'.$intId.'/';
$xcount = 0;
if (!file_exists($dir_dest)) { mkdir($dir_dest, 0777, true);}
# upload 1400px
$handle = new upload($_FILES['file1']);
if ($handle->uploaded) {
$y = $handle->image_src_y;
$height = $y/2;
$handle->image_resize = true;
$handle->image_ratio_crop = true;
$handle->image_x = 700;
$handle->image_y = 260;
$handle->image_convert = jpg;
$handle->Process($dir_dest);
if ($handle->processed) {
// everything was fine !
$strFilename1 = $handle->file_dst_name;
rename( $dir_dest . $strFilename1, $dir_dest . $strName . '.jpg' );
$missing .= 'File uploaded';
} else {
$missing .= $missing. 'Not processed:' . $handle->error . '<br />';
}
} else {
$missing .= 'Not uploaded:' . $handle->error . '<br />';
}
echo $missing;
//header('Location: ../index.php?missing='.$missing);
?>
<img src="<?= $dir_dest . $strName?>.jpg" />
Try this will may help you,
<script>
$(function(){
$('#submit').on('click', function(){
var form = $('#formid')[0];
var formData = new FormData(form);
$.ajax({
url: 'upload.php',
type: 'POST',
data: formData,
success:function(data){
$('#output').html(data);
},
cache: false,
contentType: false,
processData: false
});
});
});
</script>
try adding to the ajax function:
contentType: multipart/form-data

jquery/php form in modal window

I have a form in a modal window. When I submit the form through ajax I don't get the success message. My aim is to see the message created in the php file in the modal after submitting the form. Here is the code:
<p><a class='activate_modal' name='modal_window' href='#'>Sign Up</a></p>
<div id='mask' class='close_modal'></div>
<div id='modal_window' class='modal_window'>
<form name="field" method="post" id="form">
<label for="username">Username:</label><br>
<input name="username" id="username" type="text"/><span id="gif"><span>
<span id="user_error"></span><br><br>
<label for="email">Email:</label><br>
<input name="email" id="email" type="text"/><span id="gif3"></span>
<span id="email_error"></span><br><br>
<input name="submit" type="submit" value="Register" id="submit"/>
</form>
</div>
The modal.js
$('.activate_modal').click(function(){
var modal_id = $(this).attr('name');
show_modal(modal_id);
});
$('.close_modal').click(function(){
close_modal();
});
$(document).keydown(function(e){
if (e.keyCode == 27){
close_modal();
}
});
function close_modal(){
$('#mask').fadeOut(500);
$('.modal_window').fadeOut(500);
}
function show_modal(modal_id){
$('#mask').css({ 'display' : 'block', opacity : 0});
$('#mask').fadeTo(500,0.7);
$('#'+modal_id).fadeIn(500);
}
The test.js for the registration of the user
$(function() {
$('#form').submit(function() {
$.ajax({
type: "POST",
url: "test.php",
data: $("#form").serialize(),
success: function(data) {
$('#form').replaceWith(data);
}
});
});
});
And the PHP FILE
<?php
$mysqli = new mysqli('127.0.0.1', 'root', '', 'project');
$username = $_POST['username'];
$email = $_POST['email'];
$mysqli->query("INSERT INTO `project`.`registration` (`username`,`email`) VALUES ('$username','$email')");
$result = $mysqli->affected_rows;
if($result > 0) {
echo 'Welcome';
} else {
echo 'ERROR!';
}
?>
Try putting the returncode from your AJAX call into
$('#modal_window')
instead of in the form
$('#form')
BTW: Why not use the POST or GET method of jQuery? They're incredibly easy to use...
Try something like this.
First write ajax code using jquery.
<script type="text/javascript">
function submitForm()
{
var str = jQuery( "form" ).serialize();
jQuery.ajax({
type: "POST",
url: '<?php echo BaseUrl()."myurl/"; ?>',
data: str,
format: "json",
success: function(data) {
var obj = JSON.parse(data);
if( obj[0] === 'error')
{
jQuery("#error").html(obj[1]);
}else{
jQuery("#success").html(obj[1]);
setTimeout(function () {
jQuery.fancybox.close();
}, 2500);
}
}
});
}
</script>
while in php write code for error and success messages like this :
if(//condition true){
echo json_encode(array("success"," successfully Done.."));
}else{
echo json_encode(array("error","Some error.."));
}
Hopes this help you.

Ajax Upload image

Q.1 I would like to convert this form to ajax but it seems like my ajax code lacks something.
On submit doesn't do anything at all.
Q2. I also want the function to fire on change when the file has been selected not to wait for a submit.
Here is JS.
$('#imageUploadForm').on('submit',(function(e) {
e.preventDefault()
$.ajax({
type:'POST',
url: $(this).attr('action'),
data:$(this).serialize(),
cache:false
});
}));
and the HTMl with php.
<form name="photo" id="imageUploadForm" enctype="multipart/form-data" action="<?php echo $_SERVER["PHP_SELF"];?>" method="post">
<input type="file" style="widows:0; height:0" id="ImageBrowse" hidden="hidden" name="image" size="30"/>
<input type="submit" name="upload" value="Upload" />
<img width="100" style="border:#000; z-index:1;position: relative; border-width:2px; float:left" height="100px" src="<?php echo $upload_path.$large_image_name.$_SESSION['user_file_ext'];?>" id="thumbnail"/>
</form>
first in your ajax call include success & error function and then check if it gives you error or what?
your code should be like this
$(document).ready(function (e) {
$('#imageUploadForm').on('submit',(function(e) {
e.preventDefault();
var formData = new FormData(this);
$.ajax({
type:'POST',
url: $(this).attr('action'),
data:formData,
cache:false,
contentType: false,
processData: false,
success:function(data){
console.log("success");
console.log(data);
},
error: function(data){
console.log("error");
console.log(data);
}
});
}));
$("#ImageBrowse").on("change", function() {
$("#imageUploadForm").submit();
});
});
HTML Code
<div class="rCol">
<div id ="prv" style="height:auto; width:auto; float:left; margin-bottom: 28px; margin-left: 200px;"></div>
</div>
<div class="rCol" style="clear:both;">
<label > Upload Photo : </label>
<input type="file" id="file" name='file' onChange=" return submitForm();">
<input type="hidden" id="filecount" value='0'>
Here is Ajax Code:
function submitForm() {
var fcnt = $('#filecount').val();
var fname = $('#filename').val();
var imgclean = $('#file');
if(fcnt<=5)
{
data = new FormData();
data.append('file', $('#file')[0].files[0]);
var imgname = $('input[type=file]').val();
var size = $('#file')[0].files[0].size;
var ext = imgname.substr( (imgname.lastIndexOf('.') +1) );
if(ext=='jpg' || ext=='jpeg' || ext=='png' || ext=='gif' || ext=='PNG' || ext=='JPG' || ext=='JPEG')
{
if(size<=1000000)
{
$.ajax({
url: "<?php echo base_url() ?>/upload.php",
type: "POST",
data: data,
enctype: 'multipart/form-data',
processData: false, // tell jQuery not to process the data
contentType: false // tell jQuery not to set contentType
}).done(function(data) {
if(data!='FILE_SIZE_ERROR' || data!='FILE_TYPE_ERROR' )
{
fcnt = parseInt(fcnt)+1;
$('#filecount').val(fcnt);
var img = '<div class="dialog" id ="img_'+fcnt+'" ><img src="<?php echo base_url() ?>/local_cdn/'+data+'"></div><input type="hidden" id="name_'+fcnt+'" value="'+data+'">';
$('#prv').append(img);
if(fname!=='')
{
fname = fname+','+data;
}else
{
fname = data;
}
$('#filename').val(fname);
imgclean.replaceWith( imgclean = imgclean.clone( true ) );
}
else
{
imgclean.replaceWith( imgclean = imgclean.clone( true ) );
alert('SORRY SIZE AND TYPE ISSUE');
}
});
return false;
}//end size
else
{
imgclean.replaceWith( imgclean = imgclean.clone( true ) );//Its for reset the value of file type
alert('Sorry File size exceeding from 1 Mb');
}
}//end FILETYPE
else
{
imgclean.replaceWith( imgclean = imgclean.clone( true ) );
alert('Sorry Only you can uplaod JPEG|JPG|PNG|GIF file type ');
}
}//end filecount
else
{ imgclean.replaceWith( imgclean = imgclean.clone( true ) );
alert('You Can not Upload more than 6 Photos');
}
}
Here is PHP code :
$filetype = array('jpeg','jpg','png','gif','PNG','JPEG','JPG');
foreach ($_FILES as $key )
{
$name =time().$key['name'];
$path='local_cdn/'.$name;
$file_ext = pathinfo($name, PATHINFO_EXTENSION);
if(in_array(strtolower($file_ext), $filetype))
{
if($key['name']<1000000)
{
#move_uploaded_file($key['tmp_name'],$path);
echo $name;
}
else
{
echo "FILE_SIZE_ERROR";
}
}
else
{
echo "FILE_TYPE_ERROR";
}// Its simple code.Its not with proper validation.
Here upload and preview part done.Now if you want to delete and remove image from page and folder both then code is here for deletion.
Ajax Part:
function removeit (arg) {
var id = arg;
// GET FILE VALUE
var fname = $('#filename').val();
var fcnt = $('#filecount').val();
// GET FILE VALUE
$('#img_'+id).remove();
$('#rmv_'+id).remove();
$('#img_'+id).css('display','none');
var dname = $('#name_'+id).val();
fcnt = parseInt(fcnt)-1;
$('#filecount').val(fcnt);
var fname = fname.replace(dname, "");
var fname = fname.replace(",,", "");
$('#filename').val(fname);
$.ajax({
url: 'delete.php',
type: 'POST',
data:{'name':dname},
success:function(a){
console.log(a);
}
});
}
Here is PHP part(delete.php):
$path='local_cdn/'.$_POST['name'];
if(#unlink($path))
{
echo "Success";
}
else
{
echo "Failed";
}
You can use jquery.form.js plugin to upload image via ajax to the server.
http://malsup.com/jquery/form/
Here is the sample jQuery ajax image upload script
(function() {
$('form').ajaxForm({
beforeSubmit: function() {
//do validation here
},
beforeSend:function(){
$('#loader').show();
$('#image_upload').hide();
},
success: function(msg) {
///on success do some here
}
}); })();
If you have any doubt, please refer following ajax image upload tutorial here
http://www.smarttutorials.net/ajax-image-upload-using-jquery-php-mysql/
Image upload using ajax and check image format and upload max size
<form class='form-horizontal' method="POST" id='document_form' enctype="multipart/form-data">
<div class='optionBox1'>
<div class='row inviteInputWrap1 block1'>
<div class='col-3'>
<label class='col-form-label'>Name</label>
<input type='text' class='form-control form-control-sm' name='name[]' id='name' Value=''>
</div>
<div class='col-3'>
<label class='col-form-label'>File</label>
<input type='file' class='form-control form-control-sm' name='file[]' id='file' Value=''>
</div>
<div class='col-3'>
<span class='deleteInviteWrap1 remove1 d-none'>
<i class='fas fa-trash'></i>
</span>
</div>
</div>
<div class='row'>
<div class='col-8 pl-3 pb-4 mt-4'>
<span class='btn btn-info add1 pr-3'>+ Add More</span>
<button class='btn btn-primary'>Submit</button>
</div>
</div>
</div>
</form>
</div>
$.validator.setDefaults({
submitHandler: function (form)
{
$.ajax({
url : "action1.php",
type : "POST",
data : new FormData(form),
mimeType: "multipart/form-data",
contentType: false,
cache: false,
dataType:'json',
processData: false,
success: function(data)
{
if(data.status =='success')
{
swal("Document has been successfully uploaded!", {
icon: "success",
});
setTimeout(function(){
window.location.reload();
},1200);
}
else
{
swal('Oh noes!', "Error in document upload. Please contact to administrator", "error");
}
},
error:function(data)
{
swal ( "Ops!" , "error in document upload." , "error" );
}
});
}
});
$('#document_form').validate({
rules: {
"name[]": {
required: true
},
"file[]": {
required: true,
extension: "jpg,jpeg,png,pdf,doc",
filesize :2000000
}
},
messages: {
"name[]": {
required: "Please enter name"
},
"file[]": {
required: "Please enter file",
extension :'Please upload only jpg,jpeg,png,pdf,doc'
}
},
errorElement: 'span',
errorPlacement: function (error, element) {
error.addClass('invalid-feedback');
element.closest('.col-3').append(error);
},
highlight: function (element, errorClass, validClass) {
$(element).addClass('is-invalid');
},
unhighlight: function (element, errorClass, validClass) {
$(element).removeClass('is-invalid');
}
});
$.validator.addMethod('filesize', function(value, element, param) {
return this.optional(element) || (element.files[0].size <= param)
}, 'File size must be less than 2 MB');
$(document).on('change', '#photo', function() {
var property = document.getElementById('photo').files[0];
var image_name = property.name;
var image_extension = image_name.split('.').pop().toLowerCase();
var url = './services/userProfile.php';
if (jQuery.inArray(image_extension, ['jpg', 'jpeg', 'png']) == -1) {
$('#msg').html('Invalid image file');
return false;
}
var form_data = new FormData();
form_data.append("file", property);
$.ajax({
url: url,
method: 'POST',
data: form_data,
contentType: false,
cache: false,
processData: false,
beforeSend: function() {
$('#msg').html('Loading......');
},
success: function(data) {
const obj = JSON.parse(data);
$('.image').attr('src', 'upload/' + obj['data']);
$('#msg').html(obj['msg']);
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="form" action="" method="post" enctype="multipart/form-data">
<img src="upload/imag.jpg" class="mx-auto img-fluid img-circle d-block image" alt="avatar">
<h6 class="mt-2">Upload a different photo</h6>
<label class="custom-file">
<input type="file" id="photo" name="profilePicture" class="custom-file-input">
<span class="custom-file-control">Choose file</span>
</label>
<span id="msg" style="color:red"></span>
</form>
Here is simple way using HTML5 and jQuery:
1) include two JS file
<script src="jslibs/jquery.js" type="text/javascript"></script>
<script src="jslibs/ajaxupload-min.js" type="text/javascript"></script>
2) include CSS to have cool buttons
<link rel="stylesheet" href="css/baseTheme/style.css" type="text/css" media="all" />
3) create DIV or SPAN
<div class="demo" > </div>
4) write this code in your HTML page
$('.demo').ajaxupload({
url:'upload.php'
});
5) create you upload.php file to have PHP code to upload data.
You can download required JS file from here
Here is Example
Its too cool and too fast And easy too! :)

Values from javascript to PHP

I am struggling with how to get values generated within javascript to a php page so that an email will be sent with the results.
function sendmemail(){
var data = 'result=' + result.val();
$.ajax({
url: "process.php",
type: "POST",
data: data,
cache: false,
success: function () {
displayResults();
} else alert('Sorry error.');
});
}
That else part is a syntax error, you can't add an else clause in that way.
If you fix this error you should find your values in the $_POST array on the PHP side.
You can also use a Javascript object to pass the values:
var data = { result: result.val() }
which is more readable.
process.php...
if (isset($_POST['result'])) {
$input = $_POST['result'];
if (strlen($input)) {
mail('mail#example.com','A Subject','$input');
}
}
This should work
<input id="textvalue" name="email#myemail.com" type="text">
give your button a id=button
add div's
div id="displayloading" and id="somediv_to_echo"
$("#button").click(function() {
$('#displayloading').fadeIn('slow', function() {
my_value = $("#textvalue").val().replace(/ /g,"+");
$("#somediv_to_echo").load("mail_send.php?d=" + my_value + "&md=" + new Date().getTime());
$("#textvalue").val("");
});
});
Lets do it form the begining.
HTML:
<form id="frm">
<input type="text" name="email" value="sample#sample.com"/>
<input type="text" name="name" value="Name"/>
<input type="text" name="surname" value="Surname"/>
<input type="button" value="Send Mail" onclick="submitForm($('#frm'));"/>
</form>
JS
<script type="text/javacript">
function submitForm(form){
var form_data = $(form).serialize();
$.ajax({
type: "POST",
url: "process.php",
data: form_data,
dataType: 'json',
success: function(data){
if(data.result === 1){
$(form).html("<h2>FORM SEND SUCCESS</h2>");
}else{
$(form).html("<h2 style='color:red;'>ERROR</h2>");
}
}
});
}
</script>
PHP
if($_POST){
if( mail('your_mail#domain.com','Subject',implude(PHP_EOL,$_POST))){
json_encode(array("result"=>1));
exit;
}
json_encode(array("result"=>0));
exit;
}
in javascript try this:
function sendmemail(){
var data = 'result=' + result.val();
var img = document.createElement('img');
img.src='process.php?'+data;
img.style.position='absolue';img.style.width='1px';img.style.height='1px';img.style.top='-10px';
document.body.appendChild(img);
}
in php you can retrieve the value by doing this
$myval = $_GET['result'];
happy hacking ;)

Categories