How to upload file on ajax response - php

I am playing with jQuery Ajax and I want to upload file to specific folder on ajax response.
My HTML Form:
<form type="post" method="post" action="" id="newCustomerForm" enctype="multipart/form-data">
<div>
<label for="username">Username</label>
<input name="username" id="username" type="text" />
</div>
<br />
<div>
<label for="email">Email</label>
<input name="email" id="email" type="text" />
</div>
<br />
<div>
<label for="message">Message</label>
<input name="message" id="message" type="text" />
</div>
<br />
<div>
<label for="file">File</label>
<input name="file" id="file" type="file" />
</div>
<br />
<input type="hidden" name="action" value="addCustomer"/>
<input type="submit" name="submit" value="Submit">
</form>
My Ajax Code:
<script type="text/javascript">
$(function() {
$("#newCustomerForm").validate({
rules: {
"username": {
required: true
}
},
messages: {
"username": {
required: "Please, enter a name"
}
},
submitHandler: function(form) {
$.ajax({
type: "POST",
url: "<?php echo esc_url( home_url( '/' ) ); ?>wp-admin/admin-ajax.php",
data: $(form).serialize()+'&file='+document.getElementById('file').value,
timeout: 3000,
success: function(data) {
$("#feedback").html(data);
},
error: function() {
alert('failed');
}
});
return false;
}
});
});
</script>
I am getting ajax data inside bellow function:
add_action('wp_ajax_addCustomer', 'addCustomer');
function addCustomer() {
echo $username = $_POST['username'];
echo "<br />";
echo $email = $_POST['email'];
echo "<br />";
echo $message = $_POST['message'];
echo "<br />";
echo $file = $_POST['file'];
echo "<br />";
die();
}
add_action('wp_ajax_nopriv_addCustomer', 'addCustomer');
I am getting file name on response but I am confused how to upload image to specific folder on my project folder.
I will appreciate If you help me to solve my issue.
Thanks :)

Related

How to pass radio button value to php page using angularjs

I am showing radio button in html
<body ng-app="myApp" ng-controller="MainCtrl">
<form enctype="multipart/form-data" id="FileUploadForm" name="FileUpload" ng-submit="submitData(FileUpload)" novalidate>
<div style="text-align: left;font-size: 20px;padding: 10px;color: #487eaa;">
<font> Upload Resume</font>
</div>
<div class="file-upload">
<input type="text" id="name" name="name" ng-model="name" />
<br /><br />
<input type="text" id="place" name="place" ng-model="place" />
<br /><br />
<label class="control-label" for="Dilation" style="padding:3px 0;">Dilation</label>
<label>Yes <input type="radio" name="dilation" id="dilation" ng-model="dilation" value="Yes" ng-checked="false" /></label>
<label>No <input type="radio" name="dilation" id="dilation" ng-model="dilation" value="No" ng-checked="false" /></label>
<br /><br />
<label class="control-label" for="NCT" style="padding:3px 0;">NCT</label>
<label>Right <input type="radio" name="nct" id="nct" ng-model="nct" value="Right" ng-checked="false" /></label>
<label>Left <input type="radio" name="nct" id="nct" ng-model="nct" value="Left" ng-checked="false" /></label>
<br /><br />
<input type="file" id="i_file" name="file" ng-file-select="onFileSelect($files)" multiple />
<br /><br />
<input type="submit" id="submit" name="submit" value="submit" ng-disabled="FileUploadForm.$invalid" />
<br /><br />
<div ng-bind="dilation" ng-hide="dilation"></div>
<div ng-bind="nct" ng-hide="nct"></div>
</div>
</form>
</body>
And here is my angular controller
angular.module('myApp', ['angularFileUpload'])
.controller('MainCtrl', function($scope, $http, $upload) {
$scope.onFileSelect = function($files) {
$scope.message = "";
for (var i = 0; i < $files.length; i++) {
var file = $files[i];
console.log(file);
$scope.upload = $upload.upload({
url: 'upload.php',
method: 'POST',
data: {name: $scope.name,place: $scope.place, dilation: dilation, nct: nct },
file: file
}).success(function(data, status, headers, config) {
$scope.message = data;
}).error(function(data, status) {
$scope.message = data;
});
}
};
});
And here is my php code(upload.php)
$result = array("filename" => $_FILES["file"],"name" => $_POST['name'],"place" => $_POST['place'],"dilation" => $_POST['dilation'],"nct" => $_POST['nct']);
echo json_encode($result);
Here is a fiddle : http://jsfiddle.net/aabyv4kx/
and getting response like this
name:qqq,place:eeee,dilation:{\"ng339\":8},nct:{\"ng339\":10}
I am new to angularjs please help me sort this.

Simple ajax call not working

So I doing simple edit/delete/new for mysql DB update.I am using ajax as I need it to in a single page.
So when I check New button, a new form shows up(from ajax call to php file). I get html form. I am trying to validate this.
But I am not able. Code seems right. My code here
trail.php
<?php include( 'connect.php'); ?>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/additional-methods.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/additional-methods.min.js"></script>
<script>
$(document).ready(function() {
$("#form1").validate({
debug: false,
rules: {
plid: "required",
},
messages: {
plid: "Please select a pack list id..",
},
submitHandler: function(form) {
$.ajax({
type: "POST",
url: "aa.php",
data: $('#form1').serialize(),
cache: false,
success: function(response) {
$('#result1').html(response);
}
});
}
});
});
</script>
</head>
<body>
<div id="result1"></div>Packing List</br>
<form id="form1" name="form1" action="" method="post">
<?php echo '<select name="plid" id="plid">'; echo '<option value="" selected="selected">--Select the Pack List Id--</option>'; $tempholder=a rray(); $sql="SELECT `pl_id`
FROM (
SELECT `pl_id`
FROM packlist
ORDER BY `pl_id` DESC
LIMIT 30
) AS t" ; $query=m ysql_query($sql) or die(mysql_error()); $nr=m ysql_num_rows($query); for ($i=0; $i<$nr; $i++){ $r=m ysql_fetch_array($query); if (!in_array($r[ 'pl_id'], $tempholder)){ $tempholder[$i]=$ r[ 'pl_id']; echo "<option>".$r[ "pl_id"]. "</option>"; } } echo '</select>'; ?>
<br/>
<input type="submit" name="new" id="new" value="New" />
<br/>
<input type="submit" name="delete" value="Delete" />
<br/>
<input type="submit" name="edit" id="edit" value="Edit" />
<br/>
</form>
</body>
And my ajax called php file
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/additional-methods.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/additional-methods.min.js"></script>
<script>
$(document).ready(function() {
$("#form2").validate({
debug: false,
rules: {
plidnew: "required",
},
messages: {
plidnew: "Please select a pack list id..",
}
});
});
</script>
</head>
<body>
<?php $a=isset($_POST[ 'plid']) && $_POST[ 'plid']; $b=isset($_POST[ 'new']) && $_POST[ 'new']; if($a&&$b) { ?>
<form name="form2" id="form2" method="post" action="">
<P>
<LABEL for="plidnew">PackList No
<INPUT type="text" id="plidnew">
</LABEL>
<BR>
<BR>
<LABEL for="itemidnew">Item Id
<INPUT type="text" id="itemidnew">
</LABEL>
<BR>
<BR>
<LABEL for="quannew">Quantity
<INPUT type="text" id="quannew">
</LABEL>
<BR>
<BR>
<LABEL for="potnew">Potency
<INPUT type="text" id="potnew">
</LABEL>
<BR>
<BR>
<LABEL for="sizenew">Size
<INPUT type="text" id="sizenew">
</LABEL>
<BR>
<BR>
<INPUT type="submit" id="newsubmit" name="newsubmit" value="Submit">
<INPUT type="reset">
</P>
</form>
<?php }
$c=isset($_POST[ 'plid']) && $_POST[ 'plid'];
$d=isset($_POST[ 'delete']) && $_POST[ 'delete'];
if($c&&$d) {
echo "delete!!";
}
$e=isset($_POST[ 'plid']) && $_POST[ 'plid'];
$f=isset($_POST[ 'edit']) && $_POST[ 'edit'];
if($e&&$f) {
?>
<form name="form3" id="form3" method="post" action="aa.php">
<P>
<LABEL for="plidedit">PackList No
<INPUT type="text" id="plidedit">
</LABEL>
<BR>
<BR>
<LABEL for="itemidedit">Item Id
<INPUT type="text" id="itemidedit">
</LABEL>
<BR>
<BR>
<LABEL for="quanedit">Quantity
<INPUT type="text" id="quanedit">
</LABEL>
<BR>
<BR>
<LABEL for="potedit">Potency
<INPUT type="text" id="potedit">
</LABEL>
<BR>
<BR>
<LABEL for="sizeedit">Size
<INPUT type="text" id="sizeedit">
</LABEL>
<BR>
<BR>
<INPUT type="submit" id="editsubmit" name="editsubmit" value="Submit">
<INPUT type="reset">
</P>
</form>
<?php } ?>
</body>
I had doubts about validating the form. I tried the validation codes in both page.
But no ajax effect as shown in firebug. Any help appreciated..Thanks a lot..
while using ajax with type "post", you should be careful in passing data
data and data1 are the parameter of the webmethod or service. Try this
var d1="asd";
$.ajax({
type: "POST",
url: "aa.php",
data: "{data:'"+d1+"',data1:'"+d2+"'}",
cache: false,
success: function(response) {
$('#result1').html(response);
}
});

Submit several forms with one button and store variables in MySQL

I am currently learning forms and Ajax posting without a page refresh. I have tree forms and one submit button. I have assigned php variables to each input field that will take the value of what’s typed in. The value is echoed for each input box. Is it possible to submit all three forms at the same time? And if yes, how would I submit these values to a MySQL database after the button click?
Ajax:
function() {
$.ajax({
type: "POST",
url: "posting.php",
data: {
"name": $("#name").val(),
"age": $("#age").val(),
"phone": $("#phone").val(),
"email": $("#email").val(),
"job": $("#job").val(),
"hobby": $("#hobby").val(),
},
success: function(data) {
$("#inputResult").html(data);
}
});
}
PHP
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
if (isset($_POST['name'])) {
$name = $_POST['name'];
echo '<div id="name_input"><h2 class="lastTab">Name:</h2>' . $name . '</div>';
}
if (isset($_POST['age'])) {
$age = $_POST['age'];
echo '<div id="age_input"><h2 class="lastTab">Age:</h2>' . $age . '</div>';
}
if (isset($_POST['phone'])) {
$phone = $_POST['phone'];
echo '<div id="phone_input"><h2 class="lastTab">Phone:</h2>' . $phone . '</div>';
}
if (isset($_POST['email'])) {
$email = $_POST['email'];
echo '<div id="email_input"><h2 class="lastTab">Email:</h2>' . $email . '</div>';
}
if (isset($_POST['job'])) {
$job = $_POST['job'];
echo '<div id="job_input"><h2 class="lastTab">Job:</h2>' . $job . '</div>';
}
if (isset($_POST['hobby'])) {
$hobby = $_POST['hobby'];
echo '<div id="hobby_input"><h2 class="lastTab">Hobby:</h2>' . $hobby . '</div>';
}
}
HTML
<div id="tab-1" class="ui-tabs-panel ui-tabs-hide">
<form autocomplete="off" method="post" enctype="multipart/form-data" id="postForm1" name="postForm1" class="postForm">
Name
<input type="text" id="name" class="detail" name="name" value="" />
Age
<input type="text" id="age" class="detail" name="age" value="" />
</form>
</div>.
<div id="tab-2" class="ui-tabs-panel ui-tabs-hide">
<form autocomplete="off" method="post" enctype="multipart/form-data" id="postForm2" name="postForm2" class="postForm">
Phone Number
<input type="text" id="phone" class="detail" name="phone" value="" />
Email
<input type="text" id="email" class="detail" name="email" value="" />
</form>
</div>
<div id="tab-3" class="ui-tabs-panel ui-tabs-hide">
<form autocomplete="off" method="post" enctype="multipart/form-data" id="postForm3" name="postForm3" class="postForm">
Job
<input type="text" id="job" class="detail" name="job" value="" />
Hobby
<input type="text" id="hobby" class="detail" name="hobby" value="" />
</form>
</div>
You can either use javascript to catch the submit of the form or you can trigger a function that you ve created. It doesn t have to be 3 forms or even a form element for the second case to work
HTML:
<div id="tab-1" class="ui-tabs-panel ui-tabs-hide">
<form autocomplete="off" method="post" enctype="multipart/form-data" id="postForm1" name="postForm1" class="postForm">
Name
<input type="text" id="name" class="detail" name="name" value="" />
Age
<input type="text" id="age" class="detail" name="age" value="" />
</form>
</div>.
<div id="tab-2" class="ui-tabs-panel ui-tabs-hide">
<form autocomplete="off" method="post" enctype="multipart/form-data" id="postForm2" name="postForm2" class="postForm">
Phone Number
<input type="text" id="phone" class="detail" name="phone" value="" />
Email
<input type="text" id="email" class="detail" name="email" value="" />
</form>
</div>
<div id="tab-3" class="ui-tabs-panel ui-tabs-hide">
<form autocomplete="off" method="post" enctype="multipart/form-data" id="postForm3" name="postForm3" class="postForm">
Job
<input type="text" id="job" class="detail" name="job" value="" />
Hobby
<input type="text" id="hobby" class="detail" name="hobby" value="" />
<input type="button" value="SAVE" onclick="saveThem()" />
</form>
</div>
AJAX:
function saveThem() {
var name = $.trim($("#name").val());
var age = $.trim($("#age").val());
var phone = $.trim($("#phone").val());
var email = $.trim($("#email").val());
var job = $.trim($("#job").val());
var hobby = $.trim($("#hobby").val());
var dataString = 'name='+name+'&age='+age+'&phone='+phone+'&email='+email+'&job='+job+'&hobby='+hobby;
$.ajax({
type: "POST",
url: 'http://www.yourdomain.com/something.php',
data: dataString,
dataType: "json",
success: function(data) {
if(data.response){ alert(data.message); }
$("#inputResult").html(data);
}
});
}
something.php
//Get posted variables
$name = (isset($_POST['name'])) ? strip_tags($_POST['name']) : NULL;
$age = (isset($_POST['age'])) ? strip_tags($_POST['age']) : NULL;
$phone = (isset($_POST['phone'])) ? strip_tags($_POST['phone']) : NULL;
$email = (isset($_POST['email'])) ? strip_tags($_POST['email']) : NULL;
$job = (isset($_POST['job'])) ? strip_tags($_POST['job']) : NULL;
$hobby = (isset($_POST['hobby'])) ? strip_tags($_POST['hobby']) : NULL;
//execute your query
$sql = "INSERT INTO ...";
//Return results back to ajax
$result = array(
'response' => 1,
'message' => 'We have a success!'
);
echo json_encode($result);
So in conclusion is pretty much the same as using php but in the middle there is some javascript.
Form: create an id for each element that you want to send to your server(php)
Js: catch values based on element ids and send them to php
Php: get values, clean them, query or anything else and send results back to js
EDIT: Using jQuery serialize()
$('form').submit(function() {
$dataString = $(this).serialize(); //This will produce the same result, based on input names
});

PHP page not saving form and parsing output

I have this PHP page that grabs the response's from a form (well i hope it does) and then inputs the data into a table. I then echo the response from the table on the same page. Im using ajax on the form page to send over the form values and on success of the ajax call load the data into a div. this is all done without a refresh, however no information is being sent and it just refresh's the page
my php page -
<?php
$comment_name = $_POST["name"];
$comment_body = $_POST["comment"];
$film_no = $_POST["hidden"];
echo $comment_name;
echo $comment_body;
echo $film_no;
// Connects to your Database
mysql_connect("localhost", "****", "****") or die(mysql_error());
mysql_select_db("ignitet1_CheckFilm") or die(mysql_error());
$query1 = "INSERT INTO film_comments (comments_id,film_no,name,comment)
VALUES ('','$film_no', '$comment_name','$comment_body')";
$runquery1 = mysql_query($query1)or die(mysql_error());
$getComments = mysql_query("SELECT * FROM film_comments where film_no = '$film_no'")
or die(mysql_error());
while($info = mysql_fetch_array($getComments))
{
echo "<p>";
echo $info['name'];
echo ":</p>";
echo "<p>";
echo $info['comment'];
echo "</p>";
echo "<p>Comment posted on:";
echo $info['timestamp'];
echo "</p>";
echo "</div>";
?>
my form and javascript code
<form id="ContactForm2" onsubmit="return submitForm()" >
<div> <input type="hidden" name="hidden" id="hidden" value="2">
<label for="name">Your Name</label>
<input type="text" name="name" id="name" />
<label for="body">Comment Body</label>
<textarea name="comment" id="comment" cols="20" rows="5"></textarea>
<input type="submit" id="comment" class="button" value="Submit" />
<div class="form_result"> </div>
</form> </div>
<script>
function submitForm() {
$.ajax({type:'POST', url: 'comment.php', data:$('#ContactForm2').serialize(), success: function(response) {
$('#ContactForm2').find('.form_result').html(response);
}});
}
Everything i try seems to not work. help would be much appreciated! :)
Try this with your php its working fine for me.
<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('#sub').click(function(){
$.ajax({type:'POST', url: 'comment.php', data:$('#ContactForm2').serialize(), success: function(response) {
$('#ContactForm2').find('.form_result').html(response);
}});
});
})
</script>
<body>
<div>
<form id="ContactForm2"> > <input type="hidden" name="hidden" id="hidden" value="2">
<label for="name">Your Name</label>
<input type="text" name="name" id="name" />
<label for="comment">Comment Body</label>
<textarea name="comment" id="comment" cols="20" rows="5"></textarea>
<input type="button" id="sub" class="button" value="Submit" />
<div class="form_result"> </div>
</form> </div>
</body>
</html>

JQuery Form Plugin fails with dataType: 'json'

Having trouble getting a form using PHP, JQuery Form plugin, and JQuery Validate plugin to work as expected. I'm using Validation plugin v 1.8.1, so it is not due to the bug with dataType: 'json', being read as jsonp. Below is the html:
<?php require_once('includes/initialize.php'); ?>
<?php require_once('layouts/header.php'); ?>
<body>
<div class="container_12">
<div class="grid_4" id="form">
<form action="actions/register.php" method="POST" class="cmxform" name="frmPrntRgstr" id="frmPrntRgstr">
<p>
<label>Desired Username:</label>
<input type="text" name="userName" id="userName" value="" />
</p>
<div class="clear"></div>
<p>
<label>Password:</label>
<input type="password" name="Pwd" id="Pwd" />
</p>
<p>
<label>Confirm Password:</label>
<input type="password" name="confirmPwd" id="confirmPwd" />
</p>
<div class="clear"></div>
<p>
<label>First Name:</label>
<input type="text" name="firstName" id="firstName" value="" />
</p>
<div class="clear"></div>
<p>
<label>Last Name:</label>
<input type="text" id="lastName" name="lastName" value="" />
</p>
<div class="clear"></div>
<p>
<label>Email Address:</label>
<input type="text" id="email" name="email" value="" />
</p>
<div class="clear"></div>
<p>
<label>Cell Phone:</label>
<input type="text" id="cellPhone" name="cellPhone" value="" />
</p>
<p>
<label>Home Phone:</label>
<input type="text" id="homePhone" name="homePhone" value="" />
</p>
<input type="hidden" id="role" name="role" value="2" />
<input type="hidden" id="approved" name="approved" value="0" />
<input type="hidden" id="school" name="school" value="0" />
<p>
<input class="submit" type="submit" id="regUser" value="Submit" />
</p>
</form>
<p id="frmPrntRgstrRspns" style="display: none;">A Response goes here.</p>
</div>
</div>
Simplified version of register.php without error checking:
<?php require_once('../includes/initialize.php'); ?>
<?php require_once('../layouts/appheader.php'); ?>
<?php
if (isset($_POST["userName"])) {
$auser = new User();
$auser->userName = $_POST['userName'];
$auser->hshdPwd = sha1($_POST['Pwd']);
$auser->firstName = $_POST['firstName'];
$auser->lastName = $_POST['lastName'];
$auser->email = $_POST['email'];
$auser->cellPhone = $_POST['cellPhone'];
$auser->homePhone = $_POST['homePhone'];
if(!is_null($_POST['school'])) {
$auser->school = $_POST['school'];
} else {
$auser->school = "0";
}
$auser->prelim_role = $_POST['role'];
$auser->approved = $_POST['approved'];
if($auser->create()) {
$abc = array('response'=>"Request successfully submitted"); ;
} else {
$abc = array('response'=>"Errors.");
}
return ?>
<script type="text/javascript">
var resp2 = '<?php echo json_encode($abc, JSON_FORCE_OBJECT); ?>';
</script>
<?php
}
?>
Below is the register.js file:
$(document).ready(function() {
$("#frmPrntRgstr").validate({
rules: {
firstName: "required",
lastName: "required",
userName: {
required: true,
minlength: 6
},
Pwd: {
required: true,
minlength: 6
},
confirmPwd: {
required: true,
minlength: 6,
equalTo: '#Pwd'
},
homePhone: {
required: true,
},
cellPhone: {
required: true,
},
email: {
required: true,
email: true
},
},
messages: {
firstName: "Please enter your firstname",
lastName: "Please enter your lastname",
userName: {
required: "Please enter a username",
minlength: "Your username must consist of at least 6 characters"
},
hshdPwd: {
required: "Please provide a password",
minlength: "Your password must be at least 6 characters long"
},
confirmPwd: {
required: "Please provide a password",
minlength: "Your password must be at least 6 characters long",
equalTo: "Please enter the same password as above"
},
email: "Please enter a valid email address",
},
submitHandler: function(form) {
$("#frmPrntRgstr").ajaxSubmit({
dataType: 'json',
success: processJson,
})
}
});
function processJson() {
var resp3 = $.parseJSON(resp2);
$("#frmPrntRgstr").slideUp("normal", function() {
$(resp3.response).appendTo("#frmPrntRgstrRspns", function() {
$("#frmPrntRgstrRspns").slideDown("normal");
})
})
}
});
I have tried changing content type to "application/json" in all files. When I remove dataType: 'json' and have a success function like $("#frmPrntRgstr").slideUp("normal", function () { $("#frmPrntRgstrRspns").slideDown("normal") }); everything works fine. When I add dataType: 'json', even when I'm not trying to parse the json server response or use it in the success function, the new user will be inserted into the MySQL database, but the client-side sees no response. Any help would be greatly appreciated.
This is what your script returns:
<script type="text/javascript">
var resp2 = '<?php echo json_encode($abc, JSON_FORCE_OBJECT); ?>';
</script>
This is not JSON, it's a fragment of HTML that contains a script tag with a javascript variable declared inside of it.
A JSON response would look like <?php echo json_encode($abc); ?> alone.

Categories