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
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
As the title says, i have try many times to get it working, but without success... the alert window show always the entire source of html part.
Where am i wrong? Please, help me.
Thanks.
PHP:
<?php
if (isset($_POST['send'])) {
$file = $_POST['fblink'];
$contents = file_get_contents($file);
echo $_POST['fblink'];
exit;
}
?>
HTML:
<html>
<head>
<script type="text/javascript" src="https://code.jquery.com/jquery-1.8.3.min.js"></script>
<script>
$(document).ready(function() {
$("input#invia").click(function(e) {
if( !confirm('Are you sure?')) {
return false;
}
var fbvideo = $("#videolink").val();
$.ajax({
type: 'POST',
data: fbvideo ,
cache: false,
//dataType: "html",
success: function(test){
alert(test);
}
});
e.preventDefault();
});
});
</script>
</head>
<div style="position:relative; margin-top:2000px;">
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<input id="videolink" type="text" name="fblink" style="width:500px;">
<br>
<input id="invia" type="submit" name="send" value="Get Link!">
</form>
</div>
</html>
Your Problem is that you think, that your form fields are automatic send with ajax. But you must define each one into it.
Try this code:
<script>
$(document).ready(function() {
$("input#invia").click(function(e) {
if( !confirm('Are you sure?')) {
return false;
}
var fbvideo = $("#videolink").val();
$.ajax({
type: 'POST',
data: {
send: 1,
fblink: fbvideo
},
cache: false,
//dataType: "html",
success: function(test){
alert(test);
}
});
e.preventDefault();
});
});
</script>
Instead of define each input for itself, jQuery has the method .serialize(), with this method you can easily read all input of your form.
Look at the docs.
And maybe You use .submit() instead of click the submit button. Because the user have multiple ways the submit the form.
$("input#invia").closest('form').submit(function(e) {
You must specify the url to where you're going to send the data.
It can be manual or you can get the action attribute of your form tag.
If you need some additional as the send value, that's not as input in the form you can add it to the serialized form values with formSerializedValues += "&item" + value;' where formSerializedValues is already defined previously as formSerializedValues = <form>.serialize() (<form> is your current form).
<html>
<head>
<script type="text/javascript" src="https://code.jquery.com/jquery-1.8.3.min.js"></script>
<script>
$(document).ready(function() {
$("#invia").click(function(e) {
e.preventDefault();
if (!confirm('Are you sure?')) {
return false;
}
// Now you're getting the data in the form to send as object
let fbvideo = $("#videolink").parent().serialize();
// Better if you give it an id or a class to identify it
let formAction = $("#videolink").parent().attr('action');
// If you need any additional value that's not as input in the form
// fbvideo += '&item' + value;
$.ajax({
type: 'POST',
data: fbvideo ,
cache: false,
// dataType: "html",
// url optional in this case
// url: formAction,
success: function(test){
alert(test);
}
});
});
});
</script>
</head>
<body>
<div style="position:relative; margin-top:2000px;">
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<input id="videolink" type="text" name="fblink" style="width:500px;">
<br>
<input id="invia" type="submit" name="send" value="Get Link!">
</form>
</div>
</body>
I am doing form validation through ajax and php and it works fine.
Now there are two files i.e., ajax.html and codeValidate.php.
html form is in ajax and it checks the code validation using another file i.e. codeValidation.php.
Now I would like to have both in the same file and name it as Ajax.php. The code is as below.
//Ajax file
<html>
<form id="form_submit">
<input id="coupon" name="coupon" type="text" size="50" maxlength="13" />
<input id="btn_submit" type="button" value="Submit">
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
$("form_submit").submit(function(e){ e.preventDefault(); return false;});
$("#btn_submit").click(function(e) { e.preventDefault();
var coupon = $("#coupon").val();
// validate for emptiness
if(coupon.length < 1 ){ window.location.href="success.html"; }
else{
$.ajax({
url: './codeValidate.php',
type: 'POST',
data: {coupon: coupon},
success: function(result){
console.log(result);
if(result){ window.location.href="success.html"; }
else{ alert("Error: Failed to validate the coupon"); }
}
});
}
});
</script>
</html>
My working php file :-
<?php
require("dbconfig.php");
if(isset($_POST['coupon']) && !empty($_POST['coupon']) ){
$coupon = trim($_POST['coupon']);
$checkcoupon = "SELECT couponCode FROM cc WHERE couponCode='".$coupon."'";
$results_coupon = mysqli_query($dbc,$checkcoupon);
if(mysqli_num_rows($results_coupon)) { echo true; }
else { echo false; }
}
?>
I am using HTML, PHP and AJAX to create a search field.
Here is my HTML Code:
<form action="search.php" id="search_form" method="post" >
<div class="search_bar">
<input type="text" name="search_text" id="search_text" placeholder="Search anything" >
</div>
<div class="search_button">
<button type="submit" id="search_button" name="search_submit" >Search</button>
</div>
</form>
This is my AJAX Code:
$('#search_button').click(function(event) {
var search_data = $('#search_text').val();
var postData ={
"content":search_data};
event.preventDefault();
$.ajax({
type: 'POST',
url: 'search.php',
data:{myData: postData},
error: function()
{
alert("Request Failed");
},
success: function(response)
{
alert("Success");
}
});
});
In PHP I tried the following:
$obj = $_POST['myData'];
echo $obj;
print_r($_POST);
All I am getting is:
Notice: Undefined index: myData in C:\xampp\htdocs\workspace\MakeMyApp\WebContent\search.php on line 9
Array ( )
I have also tried with:
file_get_contents('php //input')
but there also I am getting empty array. I don't know what exactly the problem is. Am I missing anything?
Sorry, I can't comment as I don't have enough 'reputation'.
I have tried to replicate your issue and it seems to work ok for me.
Here is the HTML page ...
<html>
<head>
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="//code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#search_button').click(function(event) {
var search_data = $('#search_text').val();
var postData ={
"content":search_data};
event.preventDefault();
$.ajax({
type: 'POST',
url: 'search-submit.php',
data:{myData: postData},
error: function()
{
alert("Request Failed");
},
success: function(response)
{
alert(response);
}
});
});
});
</script>
</head>
<body>
<form action="search.php" id="search_form" method="post" >
<div class="search_bar">
<input type="text" name="search_text" id="search_text" placeholder="Search anything" >
</div>
<div class="search_button">
<button type="submit" id="search_button" name="search_submit" >Search</button>
</div>
</form>
</body>
</html>
And this is the receiving PHP page
<?php
echo '<pre>';
print_r($_POST);
echo '</pre>';
?>
In the ajax request, you can see I'm using alert to output the response in an alert but, and if all goes well it should output the content outputted by the receiving PHP page.
Also, it may not help much, but his is how I would have done the ajax request; it's slightly less code and you don't have to define each form field individually (if you have more than one field)
$(document).ready(function(){
$('#search_form').submit(function() {
var formData = $(this).serialize();
$.ajax({
type: 'POST',
url: 'search-submit.php',
data: formData,
error: function()
{
alert("Request Failed");
},
success: function(response)
{
alert(response);
}
});
return false;
});
});
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";
}
?>