I am trying to save image using ajax .and passing data through Formdata()
but at php file i can not retrieve data or image name please help me
here is my code
<form name='signup' id='signup'>
<div class="row">
<!--<form id="uploadimage" action="" method="post" enctype="multipart/form-data">-->
<div id="selectImage">
<label>Select Image</label>
<div id="image_preview">
<img id="previewing" src="uploaded_files/259700.png" height="150" width="150" />
</div>
<input type="file" name="file" id="file" required />
<!--<input type="submit" value="Upload" class="submit" />-->
</div>
<!--</form>-->
</div>
<div class='row'>
<p>
<label for='username'>First name</label>
<input type='text' name='firstname' id='firstname' value='' placeholder='Enter First name' />
</p>
</div>
<div class='row'>
<p>
<label for='lastname'>Last name</label>
<input type='text' name='lastname' id='lastname' value='' placeholder='Enter Last name' />
</p>
</div>
<div class='row'>
<p>
<label for='email'>Email</label>
<input type='text' name='email' id='email' value='' placeholder='Enter Email' />
</p>
</div>
<div class='row'>
<p>
<label for='phno'>Phno.</label>
<input type='text' name='phno' id='phno' maxlength="10" value='' placeholder='Enter ph no' />
</p>
</div>
<!--<input type="hidden" name="actionfunction" value="saveData" />-->
<input type="hidden" name="actionfunction" value="saveData" />
<div class='row'>
<input type='button' id='formsubmit' class='submit' value='Submit' />
<!--<input type='submit' id='formsubmit' class='submit' value='Submit' />-->
</div>
</form>
here is my ajax script code:
$("#signup").on('submit', (function() {
var fname = $("#firstname");
var lname = $("#lastname");
var email = $("#email");
var phno = $("#phno");
if (validateform(fname, lname, email, phno)) {
var formdata = new FormData(this);
$.ajax({
url: "DbManipute.php",
type: "POST",
data: formdata,
processdata: false,
cache: false,
contentType: false,
success: function(response) {
//alert(response);
if (response == 'added') {
$("#show_user").trigger("click");
getusers();
$("#msg").html("user added");
}
},
});
}
});
And here is my "DbManipute.php" code:
function saveData($data,$con){
$imgfile=$_FILES['file']['name'];
$fname = $data['firstname'];
$lname = $data['lastname'];
$email = $data['email'];
$phno = $data['phno'];
//$fname = $_POST['firstname'];
//$lname = $_POST['lastname'];
//$email = $_POST['email'];
//$phno = $_POST['phno'];
$sql = "insert into tbl_employees(emp_name,emp_lname,emp_email,emp_phno,emp_pic) values('$fname','$lname','$email','$phno','$imgfile')";
if($con->query($sql)){
echo "added";
} else {
echo "error";
}
}
i didn't get any error and data also not inserted.
when i remove image upload and use serialize method then data is saved successfully but in serialize method image file name can not retrieve
please help me regarding this.
You need to append the type="file" separately.
$("#signup").on('submit', (function() {
var fname = $("#firstname");
var lname = $("#lastname");
var email = $("#email");
var phno = $("#phno");
if (validateform(fname, lname, email, phno)) {
var formdata = new FormData(this);
formdata.append( 'file', $("input[name='file']")[0].files[0] );
$.ajax({
url: "DbManipute.php",
type: "POST",
data: formdata,
processdata: false,
cache: false,
contentType: false,
success: function(response) {
//alert(response);
if (response == 'added') {
$("#show_user").trigger("click");
getusers();
$("#msg").html("user added");
}
},
});
}
});
Your client side error will not be shown in the page just like php.
You have some errors in your javascript code. You have missed an closing parenthesis at the end of js code: });
If you are using chrome or firefox browser, press F12 button and console will be shown and will show you your js errors.
Tip: you can debug your project by printing any variables in your code. For example try to use console.log('test'); in your js code to check if your ajax command is working. console.log() will print in console box of browser.
When i did this in your code i understood that your code is not running at all. Because you have set your code to be run on submit and you do not have any submit button. Then you need to change your button's type="submit".
After that you need to prevent form by submitting the form using browser and tell browser that you want to run your js code. For that you need need to prevent default action for form submit event like this:
$("#signup").on('submit', (function(evt) {
evt.preventDefault();
Another tip is that your php code is in a function that is never called. you need to call your php function in your php file or you should put your codes out of function.
Try changing your code like this. This should make your code work. And to check if your ajax request is working try to echo something in your code and in your js code alert the response.
Edit#1 One more thing to consider is that for cases that you want to upload files using ajax, you can not set data like FormData(this). For ajax uploading purpose you should create object of FormData (new FormData()) and append the data separately. (as Rejith R Krishnan said).
Related
Here is what I'm trying to do.
I'm uploading a file on the form and send the data via ajax.
Here is my code:
<form enctype="multipart/form-data" name="addcert_form" id="addcert_form" method="post" >
<input type='hidden' id="staffid" name="staffid" value="<?php echo $staffid; ?>" />
<label for="certNumber"><?php echo("Certification Number"); ?></label>
<input type="text" class="form-control certNumber" id="certNumber" name="certNumber" >
<div class="form-group" style="margin-bottom: 0px;margin-left: 15px;">
<label for="file-upload"><?php echo('File Upload'); ?></label>
<input type='hidden' id="file-upload-hidden" name="file-upload-hidden" />
<input type="file" name="file-upload" id="file-upload" accept="application/pdf">
</div>
</form>
$(document).on('change', "#cert-upload", function() {
var ajaxurl = generalObj.ajax_url;
var form = $("#addcert_form");
var params = form.serializeArray();
var formData = new FormData();
var file_data = $('#file-upload').prop('files')[0];
$(params).each(function (index, element) {
formData.append(element.name, element.value);
});
formData.append('file-upload', file_data);
$.ajax({
url: ajaxurl + "rzvy_staff_ajax.php",
data: formData,
cache: false,
contentType: false,
processData: false,
type: 'POST',
success: function (res) {
if(res=="file-uploaded"){
swal.fire(generalObj.updated, generalObj.cert-upload_changed, "success");
//location.reload();
}
}
});
});
However, when I see the information, I'm only getting the file info.
I have tried doing $_POST, and $_FILES, however, I'm not getting the information from the form. How can I get all of the information from the form when I upload the file?
Thank you,
Kevin
Here is what I found out. The data was coming over, I should have used both $_FILES and $_POST
I have a php function:
<?php
function send_message($userid, $projectid, $message) {
//some code
}
$userid = '1';
$projectid = '2';
$message = 'hello';
?>
<form id="myform" method="post" action="">
<textarea name="message" id="project-message"></textarea>
<input type="submit" name="send" value="send message">
</form>
I want the submit button to do jQuery Ajax so my page won't refresh:
js:
$('#myform').on('submit',function(e) {
e.preventDefault();
$.ajax({
url: //my valid url,
type: 'post',
dataType : 'json',
data: {
action: 'send_message', //this is the PHP function
projectid: projectid //how do I write this?,
userid: userid //how do I write this?,
message: message//how do I write this?'
},
})
.done(function(data) { console.dir(data);; })
.fail(function(jqXHR) { alert('You are fail. ' + jqXHR); });
});
On my error.log, I get NULL for the 3 parameters because I'm not sure how to access them from my PHP. How do you access the PHP variables from jQuery?
Put your PHP variables into hidden inputs so they'll be automatically sent when it is submitted.
For example : <input type="hidden" name="userid" value="1">
Serialize the form data : var formData = $(form).serialize();
On submit attach your form data :
$.ajax({
url: admin_ajax.ajax_url,
type: 'POST',
data: formData
})
Access it from PHP with a classic way : $_POST['userid']
<form id="insert_form">
<textarea name="message" id="project-message"></textarea>
<input type="submit" name="send" id="send" value="send message">
<input type="hidden" name="userid" id="userid" value="<?php echo $userid= '1'; ?>">
<input type="hidden" name="projectid" id="projectid" value="<?php echo $projectid='2'; ?>">
<input type="hidden" name="message" id="message" value="<?php echo $message=
'hello'; ?>">
</form>
var project-message=document.getElementById('project-message').value;
var send=document.getElementById('send').value;
var userid=document.getElementById('userid').value;
var projectid=document.getElementById('projectid').value;
var message=document.getElementById('message').value;
$.ajax({
url:"your_url.php",
type:"POST",
data:$('#insert_form').serialize(),
success:function(data)
{
}
})
You can get all the values of the form, and submit it.
Also you can set other the values in the form as hidden.
<form id="myform" method="post" action="" id='form1'>
<textarea name="projectMessage" id="project-message"></textarea>
<input type="submit" name="send" value="send message">
<?php print "<input type='hidden' value='$userid' > "; name='userid' ?>
<?php print "<input type='hidden' value='$projectid' > "; name='projectid' ?>
<?php print "<input type='hidden' value='$message' > "; name='message' ?>
</form>
$('#myform').on('submit',function(e) {
e.preventDefault();
$.ajax({
url: admin_ajax.ajax_url,
type: 'post',
dataType:'json',
data: $("#form1").serialize(),
})
.done(function(data) { console.dir(data);; })
.fail(function(jqXHR) { alert('You are fail. ' + jqXHR); });
});
I like this approach because I can reuse the ajax multiple times or even create a generic function to submit the form on the background with ajax. Also I can fill the form using a for each loop in php, having all the values in an array (like a database result)
ex.
<?php
foreach($values as $k=>$v}{
print "<input name='$key' value='$v'>\n";
}
?>
I have a page with a POST form, when I submit the form the details are updated in a database.
And I have another page where I use AJAX TAB, which means I load the first page with AJAX, when I do this and use the Form, the details are not updated in the database.
I would appreciate help.
<?php
if( isset($_POST['newcst']) )
{
/*client add*/
//getting post from user add form
$c_name = $_POST['c_name'];
$c_adress = $_POST['c_adress'];
$c_idnum = $_POST['c_idnum'];
$c_phone = $_POST['c_phone'];
$c_mail = $_POST['c_mail'];
echo $c_num;
//insert client into SQL
$wpdb->insert('se_clients',array(
'c_name' => $c_name,
'c_adress' => $c_adress,
'user_id'=>$cur_id,
'c_num'=>$c_idnum,
'c_phone'=>$c_phone,
'c_mail'=>$c_mail,
));
}
?>
<html>
</head>
<body>
<div id="newcst">
<form action="" method="post">
<label>Full name:</label>
<input type='text' name='c_name' /><br><br>
<label>ID: </label>
<input type='text' name='c_idnum' /><br><br>
<label>PHONE:</label>
<input type='text' name='c_phone' /><br><br>
<label>ADRESS: </label>
<input type='text' name='c_adress' /><br><br>
<label>EMAIL: </label>
<input type='text' name='c_mail' /><br><br>
<input name="newcst" type="submit" value="create">
</form>
</div>
</body>
</html>
Ajax tab:
$(document).ready(function() {
$("#nav li a").click(function() {
$("#ajax-content").empty().append("<div id='loading'><img src='http://wigot.net/project/wp-content/themes/projthem/vendor/images/loader.gif' alt='Loading' /></div>");
$("#nav li a").removeClass('current');
$(this).addClass('current');
$.ajax({ url: this.href, success: function(html) {
$("#ajax-content").empty().append(html);
}
});
return false;
});
$("#ajax-content").empty().append("<div id='loading'><img src='http://wigot.net/project/wp-content/themes/projthem/vendor/images/loader.gif' alt='Loading' /></div>");
$.ajax({ url: 'invoice', success: function(html) {
$("#ajax-content").empty().append(html);
}
});
});
hover(), click(), bind(), on() and others works only after reloading page.
So you can use live()
or
$(document).on('click', 'element', function () {
...
});
I found the solution, you need to add the PHP code that is responsible for entering data to the database on the main page that contains the AJAX and not the page with the form itself.
I have a form that is posting data to a php api file. I got the api working and it creates an account but want to use AJAX to send the data so I can make the UX better. Here is what the PHP sending script is expecting:
<form id="modal-signup" action="/crowdhub_api_v2/api_user_create.php" method="post">
<div class="modal-half">
<input type="text" placeholder="First Name" name="user_firstname"></input>
</div>
<div class="modal-half">
<input type="text" placeholder="Last Name" name="user_lastname"></input>
</div>
<div class="modal-half">
<input type="Radio" placeholder="Gender" value="male" name="user_gender">Male</input>
</div>
<div class="modal-half">
<input type="Radio" placeholder="Gender" value="female" name="user_gender">Female</input>
</div>
<div class="modal-half">
<input type="date" placeholder="DOB" name="user_dateofbirth"></input>
</div>
<div class="modal-half">
<input type="text" placeholder="Zip Code" name="user_zip"></input>
</div>
<input class="end" type="email" placeholder="Email" name="user_email"></input>
<input type="password" placeholder="Password" name="user_password"></input>
<input type="submit"></input>
</form>
PHP
$user_firstname = $_REQUEST['user_firstname'];
$user_lastname = $_REQUEST['user_lastname'];
$user_email = $_REQUEST['user_email'];
$user_password = $_REQUEST['user_password'];
$user_zip = $_REQUEST['user_zip'];
$user_dateofbirth = $_REQUEST['user_dateofbirth'];
$user_gender = $_REQUEST['user_gender'];
$user_phone = $_REQUEST['user_phone'];
$user_newsletter = $_REQUEST['user_newsletter'];
How would I send this via ajax? I found this script that says it worked, but it did not create a user. I imagine its sending the data not the right way.
Ajax
$(function () {
$('#modal-signup').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: '/api_v2/api_user_create.php',
data: $('form').serialize(),
success: function () {
alert('form was submitted');
}
});
});
});
First, let's get ajax in order:
$(function () {
$('#modal-signup').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
//same url as the form
url: '/crowdhub_api_v2/api_user_create.php',
data: $('form').serialize(),
//we need a variable here to see what happened with PHP
success: function (msg) {
//output to the page
$('#output').html(msg);
//or to the console
//console.log('return from ajax: ', msg);
}
});
});
});
Somewhere on the form page, add a div with id output:
<div id="output></div>
Finally, in api_user_create.php, there is an error:
$user_gender = $_REQUEST['user_gender'];
//these last two do not exist on the form
$user_phone = $_REQUEST['user_phone'];
$user_newsletter = $_REQUEST['user_newsletter'];
I'd recommend some error-checking on the PHP side, like this
if(!empty($_REQUEST)){
//For developing, you may want to just print the incoming data to see what came through
//This data returns into the msg variable of the ajax function
print_r($_POST);
//once that's good, process data
if(isset($_REQUEST['user_gender'])){
$user_gender = $_REQUEST['user_gender'];
}
//etc... as before
} else {
echo 'no data received';
}
This is the first time I am trying to upload a file and for some reason my $_FILES array is empty. I have checked again and again my HTML and it looks okay to me. When i try to debug the below code in eclipse the $_Files array is empty when i check it. I have checked the php_ini file it has:
file_uploads = On
upload_max_filesize = 2M
The form is in a fancybox modal window.
My HTML looks like this:
<form action="/CiREM/attachments/addAttachmentsModal.php?requestId=120" enctype="multipart/form-data" method="post" id="addattachment" name="addattachment" class="form-vertical" autocomplete="off">
<input type='hidden' id='requestId' name='requestId' value="120"/>
<input type='hidden' id='listScreen' name='listScreen' value=""?>
<input type='hidden' name='MAX_FILE_SIZE' value='4000000' /><br/> <strong>Max File size Allowed: </strong>4 Mb <br/><strong>File Formats Allowed: </strong>gif,jpeg,jpg,png<br/><hr/> <div class="control-group">
<div class="controls input">
<input class="input-file" type="file" name="upload_file[]" id="upload_file[]"/><br/>
</div>
</div>
<input class="input-file" type="file" name="upload_file[]" id="upload_file[]"/><br/>
</div>
</div>
</div>
<div class ="clear"></div>
<input id="addAttachmentsBtn" type="submit" class="btn btn-primary btn-large" value="Add Attachments"/>
</form>
My php is
<form action="<?php echo $_SERVER['PHP_SELF']."?requestId=".$requestId?>" enctype="multipart/form-data" method="post" id="addattachment" name="addattachment" class="form-vertical" autocomplete="off">
<input type='hidden' id='requestId' name='requestId' value="<?php echo $requestId;?>"/>
<input type='hidden' id='listScreen' name='listScreen' value="<?php echo $listScreen;?>"?>
<?php
if ($CIREM['MAX_IMG_NUM']>0){
echo "<input type='hidden' name='MAX_FILE_SIZE' value='".$CIREM['MAX_IMG_SIZE']."' />";
echo "<br/> <strong>Max File size Allowed: </strong>".($CIREM['MAX_IMG_SIZE']/1000000)." Mb <br/><strong>File Formats Allowed: </strong>".$CIREM['IMG_TYPES']."<br/><hr/>";?>
<?php for ($i=1;$i<=$CIREM['MAX_IMG_NUM'];$i++){?>
<div class="controls input">
<input class="input-file" type="file" name="upload_file[]" id="upload_file[]"/><br/>
</div>
<?php }?>
<?php }
else{
echo "<p class='alert alert-info'>Attachment uploading is not allowed</p>";
}
?>
Any help will be greatly appreciated.
Thanks,
Shakira
Without looking through that spaghetti code, first check whether your $_POST is also empty.
If it is, make sure that post_max_size is larger than upload_max_filesize. The two settings have to be congruent.
First of all sorry for the late reply but since sometimes people stumble upon old topics on stackoverflow, I decided to write the way it works for me.
So, to send files via ajax you have to use FormData.
I'll paste a link to a github project I have to submit forms via ajax so you can check the working example and paste here the snippet.
Link: https://github.com/pihh/auto-ajax-form
Code:
$( "form" ).on('submit',function( event ) {
if($(this).attr('ajax')){
event.preventDefault();
var marianaFormUrl = $(this).attr('action');
var marianaFormId = $(this).attr('id');
var marianaFormMethod = $(this).attr('type');
var marianaFormSucess = $(this).attr('success');
var marianaFormComplete = $(this).attr('complete');
var marianaFormBefore = $(this).attr('before');
var marianaFormInputs = $('#' + marianaFormId +' :input');
var marianaEncType = $(this).attr('enctype');
var marianaFormData = {};
// Set enctype
if(marianaEncType === undefined || marianaEncType == ''){
$(this).attr('enctype','multipart/form-data');
}
// Run Ajax Call
$.ajax({
url: marianaFormUrl,
type: marianaFormMethod,
dataType: 'JSON',
data: new FormData( this ),
processData: false,
contentType: false,
cache: false,
success:function(data){
// Run success
if(marianaFormSucess !== undefined && marianaFormSucess !== ''){
var fn = marianaFormSucess;
var func = fn +'( data )';
eval(func);
}
},
complete:function(data){
// Run complete
if(marianaFormComplete !== undefined && marianaFormComplete !== ''){
var fn = marianaFormComplete;
var func = fn +'( data )';
eval(func);
}
}
});
}
});
This is it, using formData it sends the files just fine.