I am trying to upload a file using ajax which is giving me an error and the rest of data upload successfully i have try without ajax the file is uploading but when i try to upload file via ajax it give me error i am totally confuse why ajax is giving me the problem.here is my code.
<html>
<head>
<script src="jquery-1.8.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#button").click(function(){
var form_data = $('#reg_form').serialize();
$.ajax({
type:"POST",
url:"process.php",
data:form_data,
success: function(data)
{
$("#info").html(data);
}
});
});
});
</script>
</head>
<body>
<form id="reg_form" enctype="multipart/form-data" method="post" action="">
name : <input type="text" name="name" id="name"/>
</br>
message : <input type="text" name="message" id="message" />
</br>
Image : <input type="file" name="file" id="file" />
<input type="button" value="Send Comment" id="button">
<div id="info" />
</form>
</body>
</html>
The process.php file coding is here.
<?php
mysql_connect("localhost","root","");
mysql_select_db("ajaxdatabase");
$name=$_POST["name"];
$message=$_POST["message"];
//storing file in filename variable
$fileName = $_FILES['file']['name'];
//destination dir
$to="image/".$fileName;
move_uploaded_file($_FILES['file']['tmp_name'],$to);
$query=mysql_query("INSERT INTO common(name,message,destination) values('$name','$message','$to') ");
if($query){
echo "Your comment has been sent";
}
else{
echo "Error in sending your comment";
}
?>
First of all serialize() function don't work for file you should have to make an object of form through which you can post the data and will work perfectly I had the same problem and I have just resolved your issue and is working 100% because I have tested this. Please check out.
The form.
<form name="multiform" id="multiform" action="process.php" method="POST" enctype="multipart/form-data">
name : <input type="text" name="name" id="name"/>
</br>
message : <input type="text" name="message" id="message" />
</br>
Image : <input type="file" name="file" id="file" />
</form>
<input type="button" id="multi-post" value="Run Code"></input>
<div id="multi-msg"></div>
The script.
<script type="text/javascript">
$(document).ready(function(){
$("#multiform").submit(function(e)
{
var formObj = $(this);
var formURL = formObj.attr("action");
if(window.FormData !== undefined)
{
var formData = new FormData(this);
$.ajax({
url: formURL,
type: 'POST',
data: formData,
mimeType:"multipart/form-data",
contentType: false,
cache: false,
processData:false,
success: function(data, textStatus, jqXHR)
{
$("#multi-msg").html('<pre><code>'+data+'</code></pre>');
},
error: function(jqXHR, textStatus, errorThrown)
{
$("#multi-msg").html('<pre><code class="prettyprint">AJAX Request Failed<br/> textStatus='+textStatus+', errorThrown='+errorThrown+'</code></pre>');
}
});
e.preventDefault();
e.unbind();
}
});
$("#multi-post").click(function()
{
//sending form from here
$("#multiform").submit();
});
});
</script>
And your php file is the same I have tested and is working.
<?php
mysql_connect("localhost","root","");
mysql_select_db("ajaxdatabase");
$name=$_POST["name"];
$message=$_POST["message"];
//storing file in filename variable
$fileName = $_FILES['file']['name'];
//destination dir
$to="image/".$fileName;
move_uploaded_file($_FILES['file']['tmp_name'],$to);
$query=mysql_query("INSERT INTO common(name,message,destination) values('$name','$message','$to') ");
if($query){
echo "Your comment has been sent";
}
else{
echo "Error in sending your comment";
}
?>
Related
How can I make my error messages appear after validation in PHP using AJAX
Hi, I'm currently working on my ajax and I'm tryng to figure out on how will my error message appear on my form. I've already tried to echo the error but what I want is show the error on every invalid field.
here's my html code:
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<style>
span{
display: none;
}
</style>
</head>
<body>
<form action="test2.php" method="POST" id="formLogin" class="pass">
name: <input type="text" name="name" id="name">
<span id="name">Invalid!</span>
<br>
description: <textarea name="description" id="description"></textarea>
<span id="desc">Invalid!</span>
<br>
image file: <input type="file" name="image" id="image">
<button type="submit" ></button>
</form><br>
<p class="form-message"></p>
<script src="ajax.js"></script>
</body>
heres my ajax code:
$(document).ready(function(){
$("#formLogin").submit(function(event){
event.preventDefault();
$.ajax({
url: 'test2.php',
type: 'POST',
data: new FormData(this),
contentType: false,
cache: false,
processData: false,
success: function(data)
{
if(data.name == "1"){
$("span#name").css("display","block");
}else{
$("span#name").css("display","none");
}
if(data.desc == "1"){
$("span#desc").css("display","block");
}else{
$("span#desc").css("display","none");
}
}
});
});
});
and my php code;
<?php
$myObj = new stdClass();
if(empty($_POST['name'])){
$myObj->name = "1";
}
if(empty($_POST['description'])){
$myObj->description = "1";
}
$myJSON = json_encode($myObj);
echo $myJSON;
?>
In success of ajax, you receive the data in json formate , before use the data.name you have to reqiure parse json like
data=$.parseJSON(data) OR data=JSON.parseJSON(data)
then use data.name
I try to upload file then save filename to mysql the method is same as upload & save file to mysql.
But my problem still happen. error message is uploadedfile is undefined.
HTML :
<form id="flowlist">
<div class="form-group">
<label for="idcar" class="control-label">ID CAR</label>
<input type="text" name="idcar" id="idcar" class="text_field form-control" required>
</div>
<div class="form-group">
<label for="upload">Upload Minute Of Meeting</label>
<input type="hidden" name="MAX_FILE_SIZE" value="20000000">
<input id="upload" name="uploadedfile" type="file">
<input type="hidden" id="filenm" name="filenm" required>
<input type="hidden" name="action" value="updateflow">
</div>
</form>
JS Script (cms.js):
dialog = $( "#flow" ).dialog({
buttons: {
"Update Data":function() {
var params=$('#flowlist').serialize();
$.ajax({
type:"post",
url:"doserver.php",
data:params,
cache :false,
async :false,
success : function() {
$('input').val("");
$('textarea').val("");
table.row('.selected').draw(false);
location.reload();
return this;
},
error : function() {
alert("Data failed to input.");
}
PHP code (doserver.php):
case 'updateflow':
/* catch variable parameter */
$idcar = mysqli_real_escape_string($dbc,$_POST['idcar']);
$file= mysqli_real_escape_string($dbc,$_POST['filenm']);
$target_path = "mom/";
$target_path = $target_path . basename( $_FILES['uploadedfile']['name']);
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path))
{
echo "The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded";
/* UPDATE */
$sql ="UPDATE monitor SET Mom = '".$file."'";
$sql.=" WHERE id_car LIKE '".$idcar."'";
$res =mysqli_query($dbc,$sql) or die(_ERROR30.":".mysqli_error($dbc));
}
else { echo "There was an error uploading the file, please try again!"; }
break;
Edit
add enctype="multipart/form-data"
<form id="flowlist" enctype="multipart/form-data">
</form>
Then make some change to ajax function :
"Update Data":function() {
var formData = new FormData(this);
$.ajax({
type:"post",
url:"doserver.php",
processData:false,
contentType:false,
data:formData,
....
});
I have no error but the idcar wasn't updated and file wasn't uploaded.
if you are using jquery better using $('#flowlist')[0] instead of this. I have solved this using :
"Update Data":function() {
if(window.FormData !== undefined)
{
var formData = new FormData($('#flowlist')[0]);
$.ajax({
type:"post",
url:"doserver.php",
processData:false,
contentType:false,
mimeType:"multipart/form-data",
data:formData,
...
});
}
}
I have a form with some fields and file upload option. I want to send uploaded file through Ajax to upload.php. Here is a code which i have tried and it does not work. Where am i doing wrong? Any suggestions please.
Form.php
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" </script>
<script type="text/javascript">
$(document).ready(function() {
$("#submit_custom").click(function() {
e.preventDefault();
var postData = new FormData();
postData.append('file[]', $('input[type=file]')[0].files[0]);
postData.append('trxid', $('input[name=trxid]'));
postData.append('orderid', $('input[name=orderid]'));
postData.append('custid', $('input[name=custid]'));// Uncaught TypeError: Illegal invocation
if(proceed)
$.post('upload.php', post_data, function(response){
if(response.type == 'error'){ //load json data from server and output message
output = '<div class="error">'+response.text+'</div>';
}else{
output = '<div class="success">'+response.text+'</div>';
$("#upload_form").slideUp(); //hide form after success
}
$("#upload_form").hide().html(output).slideDown();
}, 'json');
});
});
</script>
</head>
<body>
<h2>Hello <?php echo $user ?> </h2> <p> "You have successfully done purchasing process.</p>
<div id="upload_form">
<p>To send your size details for your order please upload the following file:</p>
<p>Download custom size form Provide us your custom size: File.pdf</p>
<form enctype="multipart/form-data" action="" method="post">
<input type="text" name="trxid" value="<?=$trx?>">
<input type="text" name="orderid" value="<?=$orderid?>">
<input type="text" name="custid" value="<?=$customerid?>">
<input type="file" name="file">
<input type="submit" id="submit_custom">
</form>
</div>
</body>
</html>
upload.php
<?php
if(isset($_POST['file'])){
if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
$output = json_encode(array( //create JSON data
'type'=>'error',
'text' => 'Sorry Request must be Ajax POST'
));
die($output);
}
$file=$_FILES['file']['name'];
$trx=$_POST['trxid'];
$oid=$_POST['orderid'];
$cid=$_POST['custid'];
echo $file;
$query=mysqli_query($con,"insert into payments(custom_file) value ('$file') where orderid='$oid',trx_id='$trx' and cust_id='$cid' ");
if($query){
$m=move_uploaded_file($_FILES['file']['name'],'./ServerUploadedFiles/'.$trx.$file);
$output = json_encode(array('type'=>'message', 'text' => 'Hi '.$user_name .' Thank you for your email'));
die($output);
}
else
{
$output = json_encode(array('type'=>'error', 'text' => 'Problem uploading file! .'));
die($output);
}
}
?>
Try
var postData = new FormData();
$('input[type=file]').each(function() {
postData.append('file[]', $('input[type=file]')[0].files[0]);
}
not
post_data = {
'file': $('input[name=file]').val(),
This code send data and get result, your code don't make something
Test file a.php
<html>
<head>
<!-- change jquery version, your give me some warnings -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var proceed=true; /* ** declare proceed */
$("#submit_custom").click(function() {
/*e.preventDefault();*/
var postData = new FormData();
alert('Found file '+$('[type=file]').val());
postData.append('file', $('[type=file]')[0].files[0]);
if(proceed) {
$.ajax({
processData: false, /* important */
contentType: false, /* important */
type: "POST",
url: 'b.php',
data: postData, /* ** here not post_Data but postData like declared in var*/
error: function(jqXHR, textStatus, errorThrown){ alert(textStatus); },
success:function(data, textStatus, jqXHR) {
alert(data);
var response;
/* added */
try { response = JSON.parse(data); } catch (err) { alert('Error parsing response.'); return; }
alert('result after parsing json of a is '+response.a);
/* */
},
dataType: 'html' /* I change it ot html for this example*/
});
}
});
});
</script>
</head>
<body>
<form name="upload" enctypex="multipart/form-data" action="b.php" method="post">
<input type="file" name="file">
<input type="button" id="submit_custom" value="ajax">
<input type="submit" value="post">
</form>
</div>
</body>
</html>
Test file b.php contain response like a json {"a":"2"}
{"a":"2"}
After you will be able to send and get response, you add others pribambasi
I cannot get the alert to work after sending the data in ajax? Could anyone tell me what I'm doing wrong?
My form:
<body>
<form action="" id="form1" method="post">
First name:<br>
<input type="text" name="firstname" value="Mickey">
<br>
Last name:<br>
<input type="text" name="lastname" value="Mouse">
<br><br>
<input type="submit" id="submit1" value="Submit">
</form>
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<script>
// AJAX SEND POST DATA
$('form').on('submit', function() {
var self = this;
$.ajax({
type: 'post',
url: 'submit2.php',
dataType: 'json',
data: $(self).serialize(),
success: function() {
alert("blabla");
}
});
});
</script>
This is my submit2.php file.
<?php echo "bla"; ?>
There is no problem with your HTML or JQuery code. The problem is with submit2.php file. Your AJAX function is looking for a JSON response. Return a JSON response from submit2.php
submit2.php
echo json_encode(array("message"=>"Here is the message"));
Your code should be like this:
HTML
<form action="" id="form1" method="post">
First name:<br>
<input type="text" name="firstname" value="Mickey">
<br>
Last name:<br>
<input type="text" name="lastname" value="Mouse">
<br><br>
<input type="submit" id="submit1" value="Submit">
</form>
jQuery
$("#form1").submit(function(e){
e.preventDefault();
var self = this;
$.ajax({
type: 'post',
url: 'submit2.php',
// dataType: 'json', unless you're expecting json object as server response, remove this
data: $(self).serialize(),
success: function(data) {
alert(data);
},
error: function(jqXHR, textStatus, errorThrown){
alert(errorThrown);
}
});
});
submit2.php
<?php
if(isset($_POST['firstname']) && isset($_POST['lastname'])){
echo $_POST['firstname'] . " " . $_POST['lastname'];
}
?>
I am struggling very hard to get this to work and I don't know what I'm doing wrong. I have a register page that I want to take the data inserted into the form and INSERT it to the database with jQuery and AJAX. I'm not very experienced with AJAX AND jQuery so be gentle! :P I will show you the files that I have...this is a msg.php page when i have submit data sometimes post submit in database`
mostly not so i want to know that why it s happening i am new in this field
<?
php $id=$_GET['id'];
$id1=$_SESSION['id'];
?>
<form method="post" class="msgfrm" id="msgfrm">
<input type="hidden" value="<?php echo $_GET['id']; ?>" name="rcvrid" id="rcvrid">
<input type="hidden" name="senderid" id="senderid" value="<?php echo $id1;?>" >
<div class="msgdiv" id="chatbox"></div>
<div class="textdiv">
<input type="text" name="msg" id="msg" class="textmsg">
<input type="submit" value="Send" onClick="sendChat()">
</div>
</form>
function sendChat()
{
$.ajax({
type: "POST",
url: "msg_save.php",
data: {
senderid:$('#senderid').val(),
rcvrid:$('#rcvrid').val(),
msg: $('#msg').val(),
},
dataType: "json",
success: function(data){
},
});
}
msg_save.php file
<?php
require_once('include/util.php');
$rcvrid=$_POST['rcvrid'];
$senderid=$_POST['senderid'];
$msg=$_POST['msg'];
$sql="insert into message(rcvrid,senderid,msg) values($rcvrid,$senderid,'$msg')";
mysql_query($sql);
?>
$.ajax({
type: "POST",
url: "msg_save.php",
data: " senderid="+$('#senderid').val()+"rcvrid="+$('#rcvrid').val()+"msg="+$('#msg').val(),
dataType: "json",
success: function(data){
},
});
please try this code and send data ,and use post method in php to get data,it will work
if you are trying chat application check this, it is old but just for idea:
http://www.codeproject.com/Articles/649771/Chat-Application-in-PHP
use mysqli_query instead of mysql_query recommended
<?php
$id=$_GET['id'];
//$id1=$_SESSION['id']; COMMENTED THIS AS I AM NOT IN SESSION. HARDCODED IT IN THE FORM AS VALUE 5
?>
<html>
<head>
<script src="//code.jquery.com/jquery-1.10.2.min.js"></script>
</head>
<body>
<form method="post" class="msgfrm" id="msgfrm">
<input type="hidden" value="<?php echo $_GET['id']; ?>" name="rcvrid" id="rcvrid">
<input type="hidden" name="senderid" id="senderid" value="5" >
<div class="msgdiv" id="chatbox"></div>
<div class="textdiv">
<input type="text" name="msg" id="msg" class="textmsg">
<input type="submit" value="Send" >
</div>
</form>
<script>
$("#msgfrm").on("submit", function(event) {
event.preventDefault();
$.ajax({
type: "POST",
url: "msg_save.php",
data: $(this).serialize(),
success: function(data) {
$("#chatbox").append(data+"<br/>");//instead this line here you can call some function to read database values and display
},
});
});
</script>
</body>
</html>
msg_save.php
<?php
//require_once('include/util.php');
$rcvrid = $_POST['rcvrid'];
$senderid = $_POST['senderid'];
$msg = $_POST['msg'];
echo $rcvrid.$senderid.$msg;
$con = mysqli_connect("localhost", "root", "", "dummy");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "insert into message(rcvrid,senderid,msg) values($rcvrid,$senderid,'$msg')";
mysqli_query($con,$sql);
mysqli_close($con);
echo "successful"
?>
check that whether you have inserted jquery file or not.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
Then include your function sendChat() inside <script> tags.
On submit button
<button type="submit" id="button">SAVE</button>
<script>
$(document).ready(function(){
$("#button").click(function(){
var firstname=$("#firstname").val();
var lastname=$("#lastname").val();
var email=$("#email").val();
$.ajax({
url:'dbConfigAndInsertionQuery.php',
method:'POST',
data:{
firstname:firstname,
lastname:lastname,
email:email
},
success:function(data){
alert(data);
}
});
});
});
</script>