I want to send form data from ajax to php. My ajax retrieves the form data but it doesnt send it i dont see anything wrong with the code maybe i need a much more professional help. Thanks in advance
HTML5 syntax
<div align="center"><a id="hi">Header</a></div>
<a id="signup" data-add-back-btn="true" style="float:right;" data-icon="arrow-r">Sign- In</a>
</div>
<form class="check-user" action="php/sup.php" method="POST">
<label>Username</label>
<input id="Susername" name="username" placeholder="username" type="text" >
</div>
<div align="center" data-role="fieldcontain" style="width:100%;overflow:hidden" data-position="static">
<label>Email</label>
<input id="Semail" name="email" placeholder="email" type="email" >
</div>
<div align="center" data-role="fieldcontain" style="width:100%;overflow:hidden" data-position="static">
<label>Password</label>
<input id="Spassword" name="password" placeholder="password" type="password" >
</div>
<!---input type="submit" style="visibility:hidden;" id="send"/-->
</form>
Ajax syntax
$('#signup').live('click', function(){
//var name = document.getElementById('Susername').value;
//var email = document.getElementById('Semail').value;
//var pass = document.getElementById('Spassword').value;
var that = $('form.check-user'),
urls = that.attr('action'),
methods = that.attr('method'),
data = {};
that.find('[name]').each(function(index, element) {
var that = $(this),
name = that.attr('name'),
element = that.val();
alert(name+'='+element+' '+methods);
data[name] = element;
});
$.ajax(
{
url: urls,
type: methods,
data : data,
beforeSend: function(response){alert('Sending');},
success: function(response){ alert('success');},
error: function(response){alert('failed');},
complete: function(response){alert('finished');},
}
);
return false;
});
PHP syntax
session_start();
$name = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
if(isset($name) && isset($email) && isset($password))
{
echo $name;
$_SESSION['username'] = $name;
}
else
{
die('data not set');
}
You can use serialize method on form, it will gather everything correct.
$('#signup').live('click', function(){
var that = $('form.check-user'),
urls = that.attr('action'),
methods = that.attr('method'),
data = that.serialize();
$.ajax(
{
url: urls,
type: methods,
data : data,
beforeSend: function(response){alert('Sending');},
success: function(response){ alert('success');},
error: function(response){alert('failed');},
complete: function(response){alert('finished');},
}
);
return false;
});
Try this,
$('#signup').live('click', function(){
$.ajax({
url:’’,//url to submit
type: "post",
dataType : 'json',
data : {
'Susername' : $('#Susername').val(),
'Semail' : $('#Semail').val(),
'Spassword' : $('#Spassword').val()
},
success: function (data)
{
}
});
return false;
});
I solved it works this way on the php side you do this
$name = isset(json_decode($_POST['username']));//htmlentities($values[0]);
$email = isset(json_decode(($_POST['email'])));//htmlentities($values[1]);
$password = isset(json_decode($_POST['password']));//htmlentities($values[2]);
The Ajax side
$(document).ready(function(e) {
$('#signup').live('click', function(){
//var name = document.getElementById('Susername').value;
//var email = document.getElementById('Semail').value;
//var pass = document.getElementById('Spassword').value;
var that = $('form.check-user'),
urls = that.attr('action'),
methods = that.attr('method'),
data = {};
data = that.serialize();
console.log(data);
$.ajax(
{
url: urls,
type: methods,
dataType:'json',
data : data,
beforeSend: function(response){$.mobile.showPageLoadingMsg(true);},
success: function(response){ $.mobile.showPageLoadingMsg(false);},
error: function(xhr, textStatus, errorThrown){alert(textStatus);},
complete: function(response){},
}
);
return false;
});
});
Related
I am using Codeigniter and javaScript file upload and insert database but not responce so please check my code abd share valuable idea. share all code heare...view page form data , javascript code responce error and modals submit data code here.....
view
<form id="frm_submit" enctype="multipart/form-data">
<input type="file" name="reportfile" class="form-control">
<button type="submit" class="btn btn-info" name="submit"> Save</button>
</form>
javaScript
$("#frm_submit").on('submit', function (e){
e.preventDefault();
$.ajax({
url: '<?php echo base_url() ?>vendors/upload-report-file',
type: 'POST',
data: $("#frm_submit").serialize()
}).always(function (response){
var r = (response.trim());
if(r !=0){
$(".success").show();
$(".danger").css("display","none");
setInterval('location.reload()',2000);
}else{
$(".danger").show();
$(".success").css("display","none");
}
});
});
models
public function vendors_upload_report_file()
{
$db2 = $this->load->database('bstdc',TRUE);
date_default_timezone_set('Asia/Kolkata');
$vendorsid = $this->session->userdata['vendors_data'][0]['vendor_id'];
$file_request_id = $this->input->post('file_department_id');
$file_request_id = $this->input->post('file_request_id');
$reportfile = $this->input->post('reportfile');
$today_date = date("Y-m-d");
if(!empty($reportfile)){
$filename = $_FILES['reportfile']['name'];
if (!empty($filename)){
$pic = $a.'-'.rand(5,10).time()."".$filename;
move_uploaded_file($_FILES['reportfile']['tmp_name'],'upload/files/'.$pic);
$report_pic_url = ''.base_url().'upload/files/'.$pic.'';
$db2->query('INSERT INTO bstdc_reports_file (request_id,sendor_type,sendor_id,reports_file,reports_file_url,created_date,act_status,del_status)
VALUES ("'.$file_request_id.'","Vendors","'.$vendorsid.'","'.$pic.'","'.$report_pic_url.'", "'.$today_date.'", "Y","N")');
return true;
}else{
return false;
}
}
}
Use FormData object to upload file
$("#frm_submit").on('submit', function (e) {
e.preventDefault();
$.ajax({
url: '<?php echo base_url() ?>vendors/upload-report-file',
type: 'POST',
data: new FormData(this), // <== changed from $("#frm_submit").serialize()
}).always(function (response) {
var r = (response.trim());
if (r != 0) {
$(".success").show();
$(".danger").css("display", "none");
setInterval('location.reload()', 2000);
}
else {
$(".danger").show();
$(".success").css("display", "none");
}
});
});
I would like to get the 2 values separately in order to fill automatically the input in the first file from the PHP via AJAX, but when i console.log(data) I get all the data and I want to retrieve it separately in order to put it in different tags
<input id="regist" type="text" name="regist" onblur="passdata();">
<input id="atyp" type="text" name="atyp" >
<input id="mtow" type="text" name="mtow" >
<script>
$(document).ready(function(){})
function passdata() {
var regist = $('#regist').val();
$.ajax({
type: 'post',
url: 'checkdb.php',
data: 'regist='+regist,
success: function(data){
var atyp = $('#myvalue1').val();
var mtow = $('#myvalue1').val();
$('#atyp').text(atyp);
$('#mtow').text(mtow);
alert (aty+mtow);
console.log(data);
}
})
}
</script>
and PHP file.... of course with db connection
$regist = $_POST['regist'];
$conn = mysqli_connect($host,$user,$pwd,$db);
$sql= ("SELECT * FROM aircrafts where regist='$regist'");
$datas = mysqli_query($conn,$sql);
foreach ($datas as $row) {};
if(mysqli_num_rows($datas) == 0) {
echo 'non ce niente';
} else { ?>
<span id="myvalue1"><?php echo $atyp = $row['atyp'];?></span>
<span id="myvalue2"><?php echo $atyp = $row['mtow'];?></span>
<?php };
?>
Change your Ajax request to:
$.ajax({
type: 'post',
url: 'checkdb.php',
data: 'regist='+regist,
dataType: 'json', // NEW LINE
success: function(data) {
//var atyp = $('#myvalue1').val();
//var mtow = $('#myvalue1').val();
//$('#atyp').text(atyp);
//$('#mtow').text(mtow);
var atyp = data.atyp;
var mtow = data.mtow;
alert ('aty: ' + aty , 'mtow: ' + mtow);
console.log(data);
}
})
and in your PHP: change these lines
else{?>
<span id="myvalue1"><?php echo $atyp = $row['atyp'];?></span>
<span id="myvalue2"><?php echo $atyp = $row['mtow'];?></span>
<?php };
to this exactly lines
else {
echo json_encode( $row );
}
EDIT
Regarding your "DOM-event"-handling ("document onready" and "input#regist onblur") I recommend to do it like this.
HTML:
<!-- <input id="regist" type="text" name="regist" onblur="passdata();"> -->
<input id="regist" type="text" name="regist">
<input id="atyp" type="text" name="atyp">
<input id="mtow" type="text" name="mtow">
JavaScript:
function passdata(event) {
$.ajax({
type: 'post',
url: 'checkdb.php',
data: 'regist=' + $(event.target).val(),
dataType: 'json',
success: function(data){
console.log(data);
}
})
}
$(document).ready(function(){
// on blur event
$('#regist').on('blur', passdata)
// on input event | maybe this would be also an interesting option as it fires immidiately on input
// $('#regist').on('input', passdata)
})
This bootstrap seperates the logic from the markup which is a good practice in general.
I have created a simple form consisting of a textarea field, so when user clicks on submit button its linked to a jquery script containing a url executing the process and store the data, but problem is every time i hit submit, ID & created_at data is stored but the data given on textarea is ignored and not stored, never faced this problem before..please help me out!
HTML
<form id="form" name="form" method="POST" action="profile_1.php" class="wizard-big" autocomplete="off" enctype="multipart/form-data" required="">
<div class="form-group col-sm-12">
<textarea type="text" name="status" id="status" placeholder="What's on your mind.." class="form-control" style="height:100px;"></textarea>
</div>
<div class="col-sm-12 form-group">
<input style="width:100%" type="submit" name="submit" id="submit" value="Post" class="btn btn-success">
</div>
</form>
Jquery
$(document).ready(function() {
$("#submit").click(function(e) {
var status = $('form')[0].checkValidity();
if (status) {
var formData = new FormData($('form')[0]);
$.ajax({
url: "form_post.php",
type: "POST",
data: formData,
processData: false,
contentType: false,
async: false,
dataType: "JSON",
success: function(json) {
if (json.error) {
alert(json.error_msg);
e.preventDefault();
} else {
alert("Post updated successfully!");
}
},
error: function(jqXHR, textStatus, errorThrown) {
alert(errorThrown);
}
});
}
});
});
php
<?php
session_start();
define('HOST','localhost');
define('USER','**');
define('PASS','**');
define('DB','**');
$response = array();
$con = mysqli_connect(HOST,USER,PASS,DB) or die('Unable to Connect');
if(!mysqli_connect_errno()){
$error_flag = false;
/*foreach($_POST as $value){
if(empty($value)){
$error_flag = true;
break;
}
}*/
if(!$error_flag){
//receiving post parameters
$status =$_POST['status'];
// create a new user profile
$sql = "INSERT INTO status (via, status, created_at) VALUES ('".$_SESSION['vault_no']."', '$status', NOW())";
if(mysqli_query($con,$sql)){
$response["error"] = false;
$response['via'] = $via;
echo json_encode($response);
}else{
$response["error"] = true;
$response["error_msg"] = "INSERT operation failed";
echo json_encode($response);
}
}else{
$response["error"] = true;
$response["error_msg"] = "Few fields are missing";
echo json_encode($response);
}
}else{
$response["error"] = true;
$response["error_msg"] = "Database connection failed";
echo json_encode($response);
}
?>
Note: The solution is in the comments for other readers of this question
Maybe this helps you out. You need to change it to your wish offcourse
And save this function, it could be usefull for you in the future.
This function serializes the form as how it should be done.
<script>
$.fn.serializeObject = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name] !== undefined) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
$(function() {
$('form').submit(function() {
var formData = $('form').serializeObject();
$.ajax({
data: formData,
type: 'POST',
url: 'form_post.php',
success: function(result) {
$('#result').html(result);
},
error: function(jqXHR, textStatus, errorThrown) { alert(textStatus); }
});
return false;
});
});
</script>
Well my problem is this:
I want to successfully upload 2 files to my server and then send an email attaching this 2 files. But when i call the jquery function it only send the email before it successfuly upload and i don't get any attach. I want to wait untill the upload it's done and then send the email with the 2 files correctly attached. By the way im using PHPmailer.
I have this html
<form enctype="multipart/form-data" class="formulario2">
<label for="cel" class="control-label">Presentación Corporativa</label>
<div class="controls">
<input type="file" name="file_name2" id="presentacion_web" class="inputfile">
<label for="presentacion_web" class="btn btn-primary">Elija un Archivo</label>
<input id="nombre_archivo2" disabled>
<div class="messages2"></div><br /><br />
</div>
</form>
<form enctype="multipart/form-data" class="formulario">
<label for="dni" class="control-label">Diseño Aprobado</label>
<div class="controls">
<input type="file" name="file_name1" id="diseno_aprobado_web" class="inputfile">
<label for="diseno_aprobado_web" class="btn btn-primary">Elija un Archivo</label>
<input id="nombre_archivo1" disabled>
<div class="messages"></div><br /><br />
</div>
</form>
this function in jquery:
$var3 = $("#diseno_aprobado_web").val();
$var6 = $("#presentacion_web").val();
$var7 = $var3.substring(12);
$var8 = $var6.substring(12);
$.when( enviando1(), enviando2() ).then( function(){
$.ajax({
type: 'POST',
data: ('var3='+$var7+'&var6='+$var8),
url: 'send_mail.php',
success: function(salida){
alert('Mensaje Enviado');
}
});
}).done( function(){
console.log( ' Everything was OK!' );
})
.fail( function(){
console.log( 'Something was failed' );
});
function enviando1(){
var formData = new FormData($(".formulario")[0]);
var message = "";
$.ajax({
url: 'upload.php',
type: 'POST',
data: formData,
cache: false,
contentType: false,
processData: false,
beforeSend: function(){
message = $("<span class='before'>Subiendo el archivo, por favor espere...</span>");
showMessage(message);
},
success: function(data){
message = $("<span class='success'>El archivo ha subido correctamente.</span>");
showMessage(message);
},
error: function(){
message = $("<span class='error'>Ha ocurrido un error.</span>");
showMessage(message);
}
});
};
function showMessage(message){
$(".messages").html("").show();
$(".messages").html(message);
}
function enviando2(){
var formData2 = new FormData($(".formulario2")[0]);
var message2 = "";
$.ajax({
url: 'upload2.php',
type: 'POST',
data: formData2,
cache: false,
contentType: false,
processData: false,
beforeSend: function(){
message2 = $("<span class='before'>Subiendo el archivo, por favor espere...</span>");
showMessage2(message2);
},
success: function(data){
message2 = $("<span class='success'>El archivo ha subido correctamente.</span>");
showMessage2(message2);
},
error: function(){
message2 = $("<span class='error'>Ha ocurrido un error.</span>");
showMessage2(message2);
}
});
};
function showMessage2(message2){
$(".messages2").html("").show();
$(".messages2").html(message2);
}
And this php file (send_mail.php) :
require('phpmailer/class.phpmailer.php');
$bodytext = "Correct Message";
$email = new PHPMailer();
$email->From = 'test#mydomain.com';
$email->FromName = 'test bot';
$email->Subject = 'New mail from phpmailer';
$email->Body = $bodytext;
$email->AddAddress( 'test2#test2.com' );
$file_to_attach1 = 'folder/' . $_POST['var6'];
$file_to_attach2 = 'folder/' . $_POST['var3'];
$email->AddAttachment( $file_to_attach1 , $_POST['var6'] );
$email->AddAttachment( $file_to_attach2 , $_POST['var3'] );
return $email->Send();
I was trying a lot of code and i'm really stuck and frustrated now. Sorry if is something simple but i couldn't get an answer to my problem.
Thanks!
Update1:
I found this in my upload.php, and i think it's the problem:
$file = $_FILES['file_name']['name'];
if ($file && move_uploaded_file($_FILES['file_name']['tmp_name'],"folder/".$file))
{
sleep(3);
echo $file;
}
This is returning a success in my ajax after 3 seconds, how i can turn this
"sleep(3)"
Into the time required to upload the file?.
Update 2:
upload.php
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest'){
$file = $_FILES['file_name1']['name'];
if(!is_dir("folder"))
mkdir("folder", 0777);
if ($file && move_uploaded_file($_FILES['file_name1']['tmp_name'],"folder/".$file)){
sleep(3);
echo $file;
}}else{ throw new Exception("Error Processing Request", 1); }
upload2.php
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest'){
$file = $_FILES['file_name2']['name'];
if(!is_dir("folder"))
mkdir("folder", 0777);
if ($file && move_uploaded_file($_FILES['file_name2']['tmp_name'],"folder/".$file))
{
sleep(3);
echo $file;
}}else{ throw new Exception("Error Processing Request", 1);}
Add return's
You have:
function enviando1(){
var formData = new FormData($(".formulario")[0]);
var message = "";
$.ajax({
Must be:
function enviando1(){
var formData = new FormData($(".formulario")[0]);
var message = "";
return $.ajax({
You have:
function enviando2(){
var formData2 = new FormData($(".formulario2")[0]);
var message2 = "";
$.ajax({
Must be:
function enviando2(){
var formData2 = new FormData($(".formulario2")[0]);
var message2 = "";
return $.ajax({
I think you should try .done instead of .then in the following line of your code
$.when( enviando1(), enviando2() ).then( function(){
The method will resolve its .done request as soon as all the request resolve (enviando1(),enviando1()), or reject the .done request as soon as one of the request is rejected.
You want to use dynamic file name but have $var3 and $var6 static. Use this to get the name of the file being uploaded.
$var6 = $(presentacion_web).val().split('\\').pop();
$var3 = $(diseno_aprobado_web).val().split('\\').pop();
I have a login form and I want to send a Post which contains a json.
Here is what I've done so far.
<form id="myForm">
Login
<input id="login" type="text" name="login" value=""/>
Password
<input id="password" type="password" name="password" value=""/>
<button type="submit" >Login</button>
</form>
and my js file
$("#myForm").submit(function(event) {
var frm = $("#myForm");
var data = JSON.stringify(frm);
event.preventDefault();
$.ajax({
url: "/register/",
data: data,
type: "POST",
contentType: "application/json"
});
});
Here is jsfiddle https://jsfiddle.net/p143s6tp/
I expected json to look like this :
{
"login" : "some_value",
"password" : "some_value"
}
but I got this :
{"0":{"0":{},"1":{},"2":{}},"length":1,"context":{"location":{}},"selector":"#myForm"}
I read some topics where people use .serializeArray() , but as a result I got array of single objects
You are stringifying the form jQuery object returned by the selector $("#myForm");.
.serializeArray() would yield the output in the following format (name,value pairs),
[{"name":"login","value":"test"},{"name":"password","value":"test"}]
You can modify the output returned by .serializeArray().
var frm = $("#myForm");
var formData = frm.serializeArray();
var data = {};
$.map(formData, function (obj,i) {
data[obj['name']] = obj['value'];
});
Applying JSON.stringify() will yield:
{"login":"test","password":"test"}
Updated Fiddle
The simplest way:
JS
var login = $('#login').val();
var password = $('#password').val();
$("#myForm").submit(function(event) {
$.ajax({
url: "/register/",
data: {'login':login,'password':password},
type: "POST",
success: function(data) {
alert(data);
}
});
});
PHP
$login = $_POST['login'];
$password = $_POST['password'];
echo 'login:' . $login . ' - password: ' . $password;
$("#myForm").submit(function(event) {
var frm = $("#myForm");
var data = frm.serialize();
event.preventDefault();
$.ajax({
url: "/register/",
data: JSON.stringify(data),
type: "POST",
contentType: "application/json"
});
});
As yourself noted, you have to use .serializeArray(). It returns array of names and values which you can convert to desired format using Array's methods.
Something like this:
var data = {};
frm.serializeArray().forEach(function(el) {
data[el.name] = el.value;
});
var json = JSON.stringify(data);