I have a modal form using bootstrap. The form contains some text inputs and a image input.
I submit the form with ajax, and all data is received at the PHP file correctly. Alas, the image isn't being uploaded.
What is my code problem?
<script>
$(document).ready(function () {
$("input#submit").click(function(){
$.ajax({
type: "POST",
url: "insert.php",
data: $('form.contact').serialize(),
success: function(msg){
$("#th").html(msg)
$("#form-content").modal('hide');
$("#pro").html(content);
},
error: function(){
alert("failure");
}
});
});
});
</script>
The form:
<form class="contact" name="contact" enctype="multipart/form-data">
<label for="inputNombre" class="sr-only">Título</label>
<input id="inputNombre" name="inputNombre" class="form-control" placeholder="Título" required="TRUE" autofocus="" type="text">
<br>
....
<div class="upload_pic1 inline">
<input id="imagen" name="imagen" type="file">
</div>
<div class="modal-footer">
Cerrar
<input id="submit" class="btn btn-success" type="submit" value="Crear">
</div>
</div>
</form>
EDIT:
insert.php
<?php
session_start();
if (!isset($_SESSION["name"]) && $_SESSION["name"] == "") {
// user already logged in the site
header("location: Login.html");
}
require_once('funt.php');
conectar('localhost', 'root', '', 'db');
if (isset($_POST['inputNombre'])) {
$nombre = strip_tags($_POST['inputNombre']);
....
//Here the var imagen
if(is_uploaded_file($_FILES['imagen']['tmp_name'])){
$rutaEnServidor='imagenes';
$rutaTemporal=$_FILES['imagen']['tmp_name'];
$nombreImagen=$_FILES['imagen']['name'];
$rutaDestino=$rutaEnServidor.'/'.$nombreImagen;
move_uploaded_file($rutaTemporal,$rutaDestino);
} else { //Always enter here, so is not uploaded
$rutaEnServidor='imagenes';
$rutaTemporal='/noPicture.png';
$rutaDestino=$rutaEnServidor.'/noPicture.png';
move_uploaded_file($rutaTemporal,$rutaDestino);
}
...
How can I change this and upload the picture with all data in form?
You can use FormData interface. Then you have to tell jQuery not to set content type, nor process data.
Check compatibility table for the FormData constructor first. It might suffice.
Otherwise read through this discussion, How can I upload files asynchronously?.
Related
I am using http://www.formvalidator.net/index.html to validate my form but the form gets submitted even when the validation get failed.
Form code:
<form name="add-todo" class="form-horizontal" action="" method="post">
<h5>Add New Item</h5>
<div class="form-group">
<div class="col-md-12">
<input type="text" data-validation="required" class="form-control" id="todo-text-input" name="todo-text">
</div>
</div>
<div class="form-group">
<div class="col-md-12">
<button type="submit" class="btn btn-primary btn-add">Add</button>
</div>
</div>
</form>
jQuery code:
$(document).ready(function() {
$.validate({
modules: 'security'
});
$('form[name=add-todo]').submit(function(e) {
e.preventDefault();
var text = $("#todo-text-input").val();
$('.btn-add').text('Saving ....');
$.ajax({
url: this.action,
type: this.method,
data: {
text: text
},
success: function(response) {
$("#todo-text-input").empty();
$('.messages').removeClass('hide-element');
$('.alert').addClass('alert-success');
$('.alert').text('To do item added successfully.');
$('.alert').fadeTo(2000, 500).slideUp(500, function() {
$('.alert').slideUp(500);
});
}
});
});
});
dont use submit button. You can use
<button type="button" class="btn btn-primary btn-add">Add</button>
after that check your validation status. if its valid then submit the form.
<input type="text" data-validation="required" class="form-control" id="todo-text-input" name="todo-text">
In your input field you don't need to use data-validation="required" just use required like
<input type="text" required class="form-control" id="todo-text-input" name="todo-text">
Please change you form validation code configuration like this:
$.validate({
form : '#registration-form',
modules : 'security',
onSuccess : function($form) {
alert('The form '+$form.attr('id')+' is valid!');
// write your ajax code to submit form data on server
return false; // Will stop the submission of the form
}
});
For more info follow:
http://www.formvalidator.net/index.html#configuration
I am getting problem to save my form data in the database. I am done small code on that which is shown below, when i enter data in form and click on my submit button it not work.
$(".btn").click(function(e) {
e.preventDefault();
var form = $("#frm");
$.ajax({
url: '/Form/Index',
data: form.serialize(),
type: 'POST',
success: function(data) {
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form role="form" id="frm">
<div class="form-group">
<div class="col-sm-6 col-lg-12 col-md-12">
<div class="form-group">
<label for="name" style="color:black;">Product Name</label>
<input type="text" class="form-control" id="name"
placeholder="Product Name" style="color:black;">
</div>
<div class="form-group">
<label for="name" style="color:black;">Product Date</label>
<input type="text" class="form-control" id="Text1"
placeholder="Date" style="color:black;">
</div>
<div class="form-group">
<label for="name" style="color:black;">Product Price</label>
<input type="text" class="form-control" id="Text2"
placeholder="Date" style="color:black;">
</div>
</div>
</div>
<button type="submit" class="btn btn-default" id="ok" >Submit</button>
</form>
Above is my code please give me solution on that
As I've checked you code, client side code is working fine, The only problem I can imagine in this case is you url path.
make sure you are providing correct url path.
You should check if its hitting the that page or not.
Which Framework you are using. Different framework has different syntax to pass the value in URL. Check the path you are getting in the page source page view in URL parameter or you can check the error in console log after the submit. It may be not getting the correct path of your action.
Make sure ajax library loaded successfully, and try to have alert messages to have forward step where you reached, have this test:
$(".btn").click(function(e) {
e.preventDefault();
var form = $("#frm");
$.ajax({
url: '/Form/Index',
data: form.serialize(),
type: 'POST',
success: function(data) {
},
beforeSend: function() {
alert('before send alert')
},
error: function (request, status, error) {
alert(error);
},
});
});
if beforeSend not executed so your issue is related to ajax library.
use this :
$("#ok").click(function(e) {
// your code
}
Refer to id in javascript rather than class attribute.
If you refer class attribute than once it has click javascript perform preventDefault on that class so that if not refresh your page, The button is not working.
Put preventDefault function at last of your function.
Remove the type="submit" from button
You have to get the form submit with id and serialize the form data
`
$("#formid").submit(function(e) {
var url = "urlpathtohandlerequest";
$.ajax({
type: "POST",
url: url,
data: $("#formid").serialize(),
success: function(response)
{
alert(response);
}
});
e.preventDefault(); // stops default submit.
});
`
UPDATE - the contact form is found at this URL.
I am trying to get the following contact form to function, using this tutorial.
I manage to get everything to work as expected on my computer using apache webserver.
After uploading the files to an online website, the ajax function does not kick in.
I seems like the e.preventDefault(); stops working after the upload, and the form is redirected to a new site,and not just being processed on the site without the reload.
I have also been trying to use the return false; instead of e.preventDefault(); without any success.
Her is my code:
.html
<form method="post" action='mail/mail.php'>
<label>Name</label>
<input name="name" id="name" placeholder="Name.." required="true" class="input-field">
<label>Mail</label>
<input type="email" name="email" placeholder="Mail.." required="true" class="input-field">
<label>Msg</label>
<textarea name="message" id="message" class="textarea-field" required="true"></textarea>
<input type="submit" id="submit" name="submit" value="Send">
</form>
<div id="loading">
Sender melding...
</div>
<div id="success">
</div>
.js
$(function(){
$('form').submit(function(e){
var thisForm = $(this);
//Prevent the default form action
//return false;
e.preventDefault();
//Hide the form
$(this).fadeOut(function(){
//Display the "loading" message
$("#loading").fadeIn(function(){
//Post the form to the send script
$.ajax({
type: 'POST',
url: thisForm.attr("action"),
data: thisForm.serialize(),
//Wait for a successful response
success: function(data){
//Hide the "loading" message
$("#loading").fadeOut(function(){
//Display the "success" message
$("#success").text(data).fadeIn();
});
}
});
});
});
})
Please help!
That's because your JS is missing a closing });. Please check this demo to confirm that the default action is indeed prevented and the ajax does kick in. However, I was expecting a POST but instead I am seeing an OPTIONS request.
NOTE: Giving an element a name or id attribute value of submit is bad practice. You cannot for example use JavaScript to submit the form via default form submission -- this.submit() or $('form')[0].submit() without getting the error ...submit() is not a function .....
$(function() {
$('form').submit(function(e) {
var thisForm = $(this);
//Prevent the default form action
//return false;
e.preventDefault();
//Hide the form
$(this).fadeOut(function() {
//Display the "loading" message
$("#loading").fadeIn(function() {
//Post the form to the send script
$.ajax({
type: 'POST',
url: thisForm.attr("action"),
data: thisForm.serialize(),
//Wait for a successful response
success: function(data) {
//Hide the "loading" message
$("#loading").fadeOut(function() {
//Display the "success" message
$("#success").text(data).fadeIn();
});
}
});
});
});
});
}); // <==== MISSING THIS
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form method="post" action='mail/mail.php'>
<label>Name</label>
<input name="name" id="name" placeholder="Name.." required="true" class="input-field">
<label>Mail</label>
<input type="email" name="email" placeholder="Mail.." required="true" class="input-field">
<label>Msg</label>
<textarea name="message" id="message" class="textarea-field" required="true"></textarea>
<input type="submit" id="submit" name="submit" value="Send">
</form>
<div id="loading">
Sender melding...
</div>
<div id="success">
</div>
Since you are submitting via AJAX anyway, you may find it easier to change your input type to button, and bind to click instead of form submit, to avoid the default submit behaviour you are trying to circumvent.
I'm using Ajax to submit the login form without refreshing the page. I've added a function to see whether the data returns 'error' (which comes up when the user enters an incorrect email/password). If it does not return 'error', the user has been logged in and will be transferred to the page within 2 seconds.
The problem is that my button acts like a double-click button and I cannot see why. This is my JS file:
$(function() {
$("#goLogin").click(function() {
$.ajax({
type: "POST",
url: "db-requests/db-login.php",
data: $("#loginForm").serialize(),
success: function(data,textStatus,jqXHR){ finishLogin(data,textStatus,jqXHR); }
});
});
});
function finishLogin( data , textStatus ,jqXHR ) {
if ( data == "error" ) {
$('.errorMsg').fadeIn(500).hide();
$('.succesMsg').fadeOut(300).hide();
} else {
$('.succesMsg').fadeIn(500).show();
$('.errorMsg').fadeOut(300).hide();
setTimeout("location.href = 'protected.php';",2000);
}
}
I've tried placing it between the document_ready tags, but that isn't working either.
Part of the HTML code:
<div class="login form">
<div class="login-header">Please Login</div>
<form method="post" id="loginForm" name="form">
<label for="email" class="short">Email*</label>
<input type="text" name="email" id="email" class="required" placeholder="" />
<label for="password" class="short">Password *</label>
<input type="password" name="password" id="password" class="required" placeholder="" maxlength="15" />
</form>
<div id="login-functions">
<div class="loginbtn-container">
<input type="submit" id="goLogin" name="goLogin" class="button green" value="Login" />
</div>
<div class="login form actions">
<p class="register account">Register an account</p>
<p class="request password">Lost your password?</p>
</div>
</div>
</div>
<div class="errorMsg">Incorrect. Please recheck your details</div>
<div class="succesMsg"><b>You've been logged in!</b> Please wait while we transfer you</div>
$('.errorMsg').fadeIn(500).hide();
$('.succesMsg').fadeOut(300).hide();
did you mean tto hide both? I see the click is working fine, though you should ideally do submit
Take your submit inside the form, and prevent normal form submit using preventDefault()
$("#goLogin").submit(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "db-requests/db-login.php",
data: $("#loginForm").serialize(),
success: function(data,textStatus,jqXHR){ finishLogin(data,textStatus,jqXHR); }
});
});
Please move your submit button inside the form closing tag first
<input type="submit" id="goLogin" name="goLogin" class="button green" value="Inloggen" />
The above button is placed after the </form> tag.
Because you click on input type submit and progress Ajax on it; it cause submit 2 times.
To avoid it, you can use as Zach Leighton said above ; or use as below
$("#goLogin").click(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "db-requests/db-login.php",
data: $("#loginForm").serialize(),
success: function(data,textStatus,jqXHR){ finishLogin(data,textStatus,jqXHR); }
});
});
I'm trying to build a subscribe form.
The problem is that the page gets redirected, and the data doesn't get entered into db,
page gets redirected to
http://localhost/xampp/MY/SUB_FOLDERS/includes/parse.php?subscriber=sid%40patel&subscribe=subscribe
HTML CODE
<div id="subsc">
<form class="navbar-form navbar-right" action="includes/parse.php" mathod="post">
<div class="form-group">
<input type="email" placeholder="Email" class="form-control" name="subs" id="subs" required="required">
</div>
<input type="submit" class="btn btn-success" name="subscribe" id="subscribe" value="subscribe">
</form>
</div>
Ajax code:
<script type="text/javascript">
$(document).ready(function(){
$("#subscribe").click(function(){
username=$("#subs").val();
$.ajax({
type: "POST",
url: "includes/parse.php",
//data:dataString,
success: function(html){
if(html=='true')
{
$("#subsc").fadeOut("normal");
$("#subsc").html("Thank you for subscriping!");
}
else
{
$("#subsc").html("Error in subscribing");
}
},
});
return false;
});
});
</script>
PHP script for inserting data to database:
<?php include("connect.php");
if (#$_POST['subs']) {
$subscriber = mysql_real_escape_string(strip_tags($_POST['subs']));
$sendmessage = mysql_query("INSERT INTO subscriber VALUES('','$subscriber',now())");
echo 'true';
}
?>
PS: Name of rows in subscriber id, email, datetime
I guess there is one simpler approach here using your existing code itself...Instead of these lines:
$("#subscribe").click(function(){
username=$("#subs").val();
Use these lines:
$("#subscribe").click(function(e){
e.preventDefault();
. e.stopPropagation();
username=$("#subs").val();
This should stop the form post back even for submit button.
Hope this helps.
Add an id on your form:
<form id="myform" class="navbar-form navbar-right" action="includes/parse.php" method="post">
Change your Javascript to:
<script type="text/javascript">
$(document).ready(function(){
$("#myform").submit(function(event){
username=$("#subs").val();
$.ajax({
type: "POST",
url: "includes/parse.php",
//data:dataString,
success: function(html){
if(html=='true')
{
$("#subsc").fadeOut("normal");
$("#subsc").html("Thank you for subscriping!");
}
else
{
$("#subsc").html("Error in subscribing");
}
},
});
event.preventDefault();
});
});
</script>
This will prevent the default action of the form to submit the data and the apparent redirect. Also by handling the form's submit event you also handle the situation where the form may be submitted by other means.
First bind your subscribe button to a click event and Remove attribute action="includes/parse.php"
<input type="button" class="btn btn-success" name="subscribe" id="subscribe" value="subscribe">
jQuery('#subscribe').click(function(){
jQuery.ajax({
url:'YOUR URL',
type:'POST',
data:'subsribe=true&email='+jQuery('#subs').val(),
success:function(data){
if(data == 'true')
{
//enter code here
window.location.reload(true);
}else{
//enter code here
alert(data);
}
}
});
});
SERVER SIDE
/* AJAX check */
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) &&strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
if(isset($_POST)){
$subscriber = mysql_real_escape_string(strip_tags($_POST['subscriber']));
$query = "INSERT INTO subscribers('email','timestamp') VALUES('$subscriber',NOW())";
$sendmessage = mysql_query($query) or die(mysql_error());
echo 'true';
}
}
The simplest thing to do would be changing the type of your #subscribe element to button instead of submit.
<div id="subsc">
<form class="navbar-form navbar-right" id="SubsForm">
<div class="form-group">
<input type="email" placeholder="Email" class="form-control" name="subscriber" id="subs" required="required">
</div>
<input type="button" class="btn btn-success" id="subscribe" value="subscribe">
</form>
</div>
And JavaScript -
<script type="text/javascript">
$(document).ready(function(){
$("#subscribe").click(function(){
$.ajax({
type: "POST",
url: "includes/parse.php",
data:$('#SubsForm').serialize(),
success: function(html){
if (html=='true') {
$("#subsc").fadeOut("normal");
$("#subsc").html("Thank you for subscriping!");
} else {
$("#subsc").html("Error in subscribing");
}
},
});
});
});
</script>
More about $().serialize can be found here - http://api.jquery.com/serialize/
The .serialize() method creates a text string in standard URL-encoded
notation. It can act on a jQuery object that has selected individual
form controls....