Well the thing is there is already a edited form with a lot of fields but all the save and validate goes trough ajax.
They asked me now to put a file upload , i tough that just will be set a input and get it on back , but since all goes trough ajax i cant.
I don't want to change all the function and go trough a submit if it's not necessary.
I looked for some uploaders of file trough ajax but all of them are type drag and drop and i don't like them because y only need a simple file.
And the ones that i found that looked simple where in flash...
Is there any simple script that allows me to upload a simple file trough ajax without need of change the type of submitting the fields.
Thank's in advance mates ;)
//the js that saves all the inputs
function _edit_campaign(){
var data = formvalues_inspinia("body");
data.action=_action;
data.status=$("#smf_ior_status").val();
$.ajax({
url: "/save_changes",
dataType: "json",
data: data,
method:"POST",
success: function (response) {
if(!response.status){
toastr_error(response.desc);
$( "#submit_confirm" ).prop( "disabled", false );
$("#"+response.camp).focus();
}else{
toastr_success(response.desc);
}
}
});
}
client side
$.ajax({
url: "ajax_php_file.php", // Url to which the request is send
type: "POST", // Type of request to be send, called as method
data: new FormData(this), // Data sent to server, a set of key/value pairs (i.e. form fields and values)
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) // A function to be called if request succeeds
{
});
server side
$sourcePath = $_FILES['file']['tmp_name']; // Storing source path of the file in a variable
$targetPath = "upload/".$_FILES['file']['name']; // Target path where file is to be stored
move_uploaded_file($sourcePath,$targetPath) ; // Moving Uploaded file
You can achieve this in simpler way using "ajaxSubmit".
Include jquery.form.js on your page and submit your form.
$(form).ajaxSubmit({
url: url,
type: "POST",
success: function (response) {
// do what you need with response
});
It sends all form data including file on server then you can handle these data in regular manner.
Related
I have searched through the amazing answers offered on similar subjects, but I just can't seem to find one that answers my question.
I am trying to POST data to a separate PHP page via AJAX to send an email without the page reloading. However, I can either get the data to POST and have the page reloaded, or the form POSTs nothing and the page remains exactly as it was. The following example is of the latter scenario.
I'm not sure if this is relevant, but the form is contained within a modal. I can post it if necessary.
jQuery:
$("#submit").click(function(e) {
e.preventDefault();
$.ajax({
method: "POST",
url: "email.php",
data: {
name: $("#name").val(),
email: $("#returnEmail").val(),
subject: $("#subject").val(),
body: $("#body").val(),
},
dataType: "html",
success: function() {
$("#errorSuccess").html('<div class="alert alert-success" role="alert">Email Sent!</div>');
}
});
});
Thanks in advance!
you're appending data in a wrong way.
When you post something in ajax to a php (And then you read it there with $_POST["name"]) PHP recieves it as url encoded data (?name=value&name=value).
So, here are a few solutions:
Identify your form element with some id (id="myform") and then retrieve the values you're needing with serialize() method. Like this:
method: "POST",
url: "email.php",
data: $("#myform").serialize(),
You can append it to a Javascript Array like this:
var form_data = {};
form_data["name"] = $("#name").val();
form_data["email"] = $("#email").val();
And then you can send it as regular data in Ajax parameters,
data:form_data,
Use the FormData object. And append data from your form - FormData is recommended when you're appending data and files in the same form .
var form_data = new FormData();
form_data.append("name", $("#name").val());
form_data.append("email", $("#email").val());
Or even easier, again with an ID in the form:
var form = document.getElementById('myform');
var form_data = new FormData(form);
and for sending, you use this in your ajax parameters:
data: form_data,
processData: false,
contentType: false
*processData and contentType are very important, if they're not present, it will throw an error (Illegal invocation if I remember right)
Add it manually to a string (ugly and not recommended way). But it shows you how does it work (you know, just for curiosity)...
data: '?name='+$("#name").val()+'&email='+$("#email").val()
Success and error in your ajax would be great. Don't forget to set a response in your PHP, seeing that PHP would be great for helping you.
Hope it helps :)
hey i have following codes:
index.php
select.php
and you can also find whole project in GitHub (simple-online-library)
which works fine and save bookname bookauthor bookpages in mysql database but its just save image name and image path in database i just want to move image in to new folder called images and try several ways but none of them works for me.
Should be fixed as below
<?php
require_once("db.php");
$file = addslashes(file_get_contents($_FILES["images"]["tmp_name"]));
$sql = "INSERT INTO test1(name, lastname, age , images) VALUES('".$_POST["name"]."', '".$_POST["lastname"]."', '".$_POST["age"]."', '".$file."')";
if(mysqli_query($connect, $sql))
{
echo 'infos saved';
}
?>
UPDATE
your AJAX script only sending filename, not the image. Correct JS should be similar to one below.
$.ajax({
url: "ajax_php_file.php", // Url to which the request is send
type: "POST", // Type of request to be send, called as method
data: new FormData(this), // Data sent to server, a set of key/value pairs (i.e. form fields and values)
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) // A function to be called if request succeeds
{
// do something ex. $('#loading').hide();
}
});
I am coding a video platform. When anyone sees the video and hit the like button the like should be incremented by one and should be written to xml file - I want to do this with php. And when the like symbol is clicked, the php should not be loaded but it should be executed.
Here is my code:
HTML:
<a href='#' onclick='doLike(id)'><i class='material-icons' style='float:bottom'>thumb_up</i></a>
JavaScript:
function doLike(id){
$.ajax({
type: "POST",
async: true,
url: "likup.php",
cache: false,
contentType: false,
processData: false,
error: function(){alert('Cannot reach file');},
success:
function(){
alert("Saved Successfully");
}
});}
PHP:
error_reporting(E_ALL);
$file = 'xml/shortfilm/filmname.xml';
$xml = simplexml_load_file($file);
$xml->Shortfilm[0]->like= 2;
But I am still unable to achieve what I want.
onclick='doLike(id)'
On click doList(id) will be called. What is id? Is it defined? You need to make sure that this parameter has the correct value. Your doLike does not send the id to the server. You need to send it, otherwise your server will not receive it. Your server, in turn should process the request and save the like into the xml.
I'm using a great plugin - dropzone.js (dropzonejs.com) to make my site a little more fancy when registering a new user.
Basically, the user fills out a form, drops a couple images into the "dropzone", and clicks "Submit", which fires an ajax call that posts the form to a php script.
I have dropzone parameters set to enqueForUpload:false, which keeps the files from auto-uploading, since I need them to upload into uploads/$userid, after the new user id has been created. I can give dropzone header params, which I'm assuming post to the url, similar to an ajax call, instead of data: {'userid': userid}, dropzone uses headers: {'userid': userid}... However, dropzone gets initialized on document.ready, and as the userid variable isn't declared yet, dropzone fails to initialize.
I'm guessing I'm going to need to initialize dropzone with document.ready, but not give it headers just yet. Then after the ajax form processing is successful and returns userid, call dropzone to upload and give it the headers at that point. Problem is, I don't know what code would need to be called to make that happen.
Initialize Dropzone on ready:
$(document).ready(function(){
$('#dropzone').dropzone({
url: 'dropzoneprocess.php',
maxFilesize: 1,
paramName: 'photos',
addRemoveLinks: true,
enqueueForUpload: false,
});
});
Then...
$('#submit').on('click', function(){
validation crap here
$.ajax({
type: 'post',
url: 'postform.php',
data: {'various': form, 'values': here}
datatype: 'json',
success: function(data){
var userid = data.userid;
/* (and this is what I can't figure out:)
tell dropzone to upload, and make it
post userid to 'dropzone.php' */
});
});
If you use the latest Dropzone version, the parameter enqueueForUpload has been removed, in favour of autoProcessQueue which makes the whole queuing easier.
So, just call myDropzone.processQueue() as soon as you want all files to be uploaded.
To add additional parameters to the XHR you can simply register to the sending event, which gets the xhr object as second and formData as third parameter, and add the data yourself. Something like this:
myDropzone.on("sending", function(file, xhr, formData) {
// add headers with xhr.setRequestHeader() or
// form data with formData.append(name, value);
});
I used enyo answer, but i used many dropzones with data-id attribute in my page so I used:
$('div.dropzone').dropzone({
url: 'img.php'
});
var sendingHandler = function(file, xhr, formData) {
formData.append('id', $(this.element).data('id'));
};
$('div.dropzone').each(function() {
Dropzone.forElement(this).on('sending', sendingHandler);
});
I have an application where a user is allowed to save some text data into a MYSQL database through a web interface. In addition, they can also attach a file to this text and I save this into a blob field. The file types that get attached are simple .txt files.
I am able to save this data into the database but I am having trouble retrieving it. This is what I am doing to retrieve it right now:
//Events that take place when trying to retreive an attached file
function getFile(rowid){
//Make an AJAX Request to fetch the file
$.ajax({
type: 'get',
url: 'point-of-contact.php',
data: 'page=attachment&row='+rowid,
dataType: 'text',
success: function(data) {
console.log (data);
}
});
}
The AJAX request above leads to the following PHP code:
$attachments = $poc -> getPOC($_GET['row']);
header('Content-type: text/plain');
echo $attachments;
The problem I face is that when I console log the data received from the AJAX request I get this:
How do I go about getting the data in simple text format?
Could it be that the way I am uploading the file to the database is incorrect? This is how the file is uploaded to the DB:
//File upload code
var fileInput = document.getElementById('upload');
var file = fileInput.files[0];
//Hide the save button
$("#save-button-1").hide();
//Make the AJAX request
$.ajax({
type: 'post',
url: 'point-of-contact.php?page=add',
data: 'point_of_contact=' + $("#textarea1").val() + '&point_of_contact_attachment=' + file,
success: function(data) {
$('#done-1').show();
setTimeout(function() {
$('#done-1').fadeOut();
}, 2500);
$('.loader').fadeOut();
}
});
There is problem in your upload section. The line
var file = fileInput.files[0];
assignes file object into file variable. Later, when you add it to
"point_of_contact_attachment="
it gets converted to string. So you will have
"point_of_contact_attachment=[object file]"
And that is it.
try pointing the browser directly to the file instead of using ajax.
Like this
document.location = point-of-contact.php?page=attachment&row='+rowid;
Since it is not a file the browser can read, it will just download it.
However you will still need to get the TXT via ajax, because document.location redirect to the user to a plain text page.