I'm not expert with Jquery. I've built a 4 steps html form like
<form id="msform" enctype="multipart/form-data">
<fieldset id="publish1" data-check-id="1">
//some inputs
</fieldset>
<fieldset id="publish2" data-check-id="2">
//some inputs
</fieldset>
<fieldset id="publish3" data-check-id="3">
//some inputs
</fieldset>
<fieldset id="publish4" data-check-id="4">
<input type="submit" class="submit action-button pull-right top-35" value="Publish"/>
</fieldset>
</form>
and after writing some Jquery validation in my .js file, I've tried to pass my data to a php file through ajax. My formData function looks like this:
<script>
function formData() {
var serializedValues = jQuery("#msform").serialize();
var form_data = {
action: 'ajax_data',
type: 'post',
data: serializedValues,
};
jQuery.post('mypath/insert.php', form_data); //where data should be sent
return true;
}
</script>
Searching around I've tried to build the php file receiving data with this structure:
<?php
if (isset($_POST['data'])) {
post_things();
return true;
}
function post_things() {
$title = trim($_POST['form_title']);
// where form_title is the input[name] of what I want get, serialised into jquery serializedValues variable
//other similar inputs
//do something with $title and other $variables
}
?>
I've initialized validation and ajax functions doing something as following:
<script>
$(document).ready(function () {
msform_init(); //this validate form step by step (it's working!)
$('#msform').submit(function (event) {
if (form_completeCheck() && true) { //This check if something empty
formData();
if (formData() && true) {
window.location.replace("//some redirection to success");
} else {
window.location.replace("//some redirection to failure");
}
} else {
event.preventDefault();
}
})
})
</script>
The problem is that when I click on submit I got redirected to a page where the url is mypath? ALL_MY_DATA_SERIALISED.
Where is my error? I can't see it due to my ignorance. Is in the jquery/ajax functions, in the php file or in my html?
Thank you in advance for your help.
You just need to do event.preventDefault() in the top of your event listener:
$('#msform').submit(function(event){
event.preventDefault();
if(form_completeCheck() && true){ //This check if something empty
formData();
if(formData() && true){
window.location.replace("//some redirection to success");
} else {
window.location.replace("//some redirection to failure");
}
}
})
HTML Script
<form id="msform" enctype="multipart/form-data">
<input type="hidden" name="action" value="do_action"/>
<fieldset id="publish1" data-check-id="1">
//some inputs
</fieldset>
<fieldset id="publish2" data-check-id="2">
//some inputs
</fieldset>
<fieldset id="publish3" data-check-id="3">
//some inputs
</fieldset>
<fieldset id="publish4" data-check-id="4">
<input type="button" id="do_action" class="submit action-button pull-right top-35" value="Publish"/>
</fieldset>
</form>
JavaScript
$("#do_action").click(function(){
$.ajax({
type:'POST',
data:$("#msform").serialize();
url:'<<php script url>>',
success:function(data){
alert(data);
}
});
});
php script
<?php
if(isset($_POST['action'])){
post_things($_POST);
return true;
}
function post_things($request){
echo "<pre>";
print_r($request);
echo "</pre>";
}
?>
The reason you get redirected is because you are submitting the form.
Since in your <form id="msform" enctype="multipart/form-data"> you define no action it is submitted to itself.
You must prevent form from submitting using preventDefault().
$('#msform').submit(function(event){
event.preventDefault(); //Add this line
..............
Related
Tell me please, there is a form for sending data to the database. Without a script it works fine, but nothing happens with the script. In the console — Form Data has all the data, and the 200th code arrives, but is not added to the database.
PHP:
<?php
$data = $_POST;
if (isset($data['add'])) {
$posts = R::dispense('posts');
$posts->head = $data['head'];
$posts->desc = $data['desc'];
R::store($posts);
}
?>
HTML:
<form method="POST" id="FormID">
<input type="text" name="head" required />
<input type="text" name="desc" required />
<button type="submit" name="add">Добавить</button>
JS:
<script>
$("#FormID").submit(function(e)
{
var form = $(this);
var url = form.attr('action');
e.preventDefault();
$.ajax({
type: "POST",
url: url,
data: $("#FormID").serialize(),
success: function(data)
{
c = "hello";
$('#FormStatus').text(c);
}
});
});
</script>
You said:
if (isset($data['add'])) {
So the code only does anything if add in the data.
<button type="submit" name="add">Добавить</button>
add is a submit button. It will be included in the data when you submit the form.
data: $("#FormID").serialize(),
You aren't submitting the form. jQuery serialize does not include submit buttons because they aren't successful controls when you aren't submitting the form.
Use some other mechanism to determine if there is data to process (such as the presence of head and desc.
You have forget the action for your form
Why don't simply use $data['name'] instead of R::dispense?
If you what to do a POST request why don't you use $.post()?
What you need is these:
PHP Code:
<?php
$data = $_POST;
if (isset($data['add'])) {
if(isset($data['head']) AND !empty($data['head']) AND isset($data['desc']) AND !empty($data['desc'])) {
$head = htmlspecialchars($data['head']);
$desc = htmlspecialchars($data['desc']);
echo "Hello from server";
}
else {
echo "Please fill the form";
}
}
?>
HTML:
<form method="POST" id="FormID" action="path_to_php_file.php">
<input type="text" name="head" required />
<input type="text" name="desc" required />
<button type="submit" name="add">Добавить</button>
</form>
JS:
<script>
$("#FormID").submit(function(e)
{
e.preventDefault();
var form = $(this),
url = form.attr('action');
var data = {};
// To have post paramaters like
// { 'head' : 'Head value', 'desc' : 'Desc value' }
$.each(form.serializeArray(), function(i, field) {
data[field.name] = field.value;
});
$.post(url, data, function(Responses) {
// Will write "Hello from server" in your console
console.log(Responses);
});
});
</script>
The problem I've been trying to solve for hours and hours now is following: I cannot stop the redirecting of #myform action after the data has been submitted succesfully to database. I've tried multiple methods but none seem to work. I'm in dire need of help!
The code:
Html(mainview.php):
<div id="submitAccordion">
<form id="myForm" action="userFiles.php" method="post">
Name: <input type="text" name="accordionName" /><br />
<input id="sub" type="submit" name="go" />
</form>
<span id="result"> </span>
</div>
Javascript(mainview_script.js):
$("#sub").click(function () {
var data = $("#myForm :input").serializeArray();
$.post( $("#myForm").attr("action"),
data, function(info) {
$("#result").html(info); } )
});
$("#myForm").submit(function () {
return false;
});
php(userFiles.php):
session_start();
require_once 'database.php';
if ( isset($_SESSION['user_id']) ) {
$sql = "INSERT INTO useraccordion (id, h3) VALUES (:id, :accordion)";
$stmt = $conn->prepare($sql);
$stmt->bindParam(':id', $_SESSION['user_id']);
$stmt->bindParam(':accordion', $_POST['accordionName']);
if ( $stmt->execute() ) {
echo "Succesfully inserted";
} else {
echo "Sorry, there was an error";
}
}
I have tried ajax method, prevent.default etc, but none work!
Either change your input type to button
<input id="sub" type="button" name="go" value="Submit"/>
Or try this:
$("form").submit(function(e){
e.preventDefault();
});
First, move your $("#myForm").submit(... out of the click event so it is it's own thing. Then, pass in e into that function. So it would look like this...
$("#myForm").submit(function(e) {
e.preventDefault();
return false;
});
$("#sub").click(function() {
var data = $("#myForm :input").serializeArray();
$.post( $("#myForm").attr("action"),data, function(info) {
$("#result").html(info);
});
});
That will fix your immediate problem. My thought is... Do not even use a form for this. There is no reason to. You are posting the data via Ajax, so there is no reason to have a form that would submit. I would do something like this...
HTML...
<div id="form">
<div class="form-item">
<label for="name">Name:</label>
<input name="name" id="name" type="text" />
</div>
<button id="sub">Submit Form</button>
</div>
Javascript...
$("#sub").click(function() {
var postData = {};
//this is here to be dynamic incase you want to add more items....
$("#form").find('input').each(function() {
postData[$(this).attr('name')] = $(this).val();
});
$.ajax({
url: "YOUR URL HERE",
type: "POST",
data: postData,
success: function(msg) {
$("#result").html(msg);
}
});
});
It is sufficient to prevent deafult action on sub:
$("#sub").click(function (e) {
e.preventDefault();
var data = $("#myForm :input").serializeArray();
$.post( $("#myForm").attr("action"),
data, function(info) {
$("#result").html(info); } )
});
$("#myForm").submit(function (event) { event.preventDefault(); });
That should stop the submission
If you are submitting your form data via ajax or jquery then you should change your input type form 'submit' to 'button' type
<input id="sub" type="button" name="go" value="go"/>
I am fetching php json encoded data using ajax and then setting values to form input then sending it to other page . But json fetched values does not post to other page while normal input values are posting . Here's the code i am using . Your help will be highly appriciated .
`
if(isset($_POST['send_mail'])){
header('Content-Type: application/json');
$out = array('a'=>"Volvo", 'b'=>"BMW", 'c'=>"Toyota");
echo json_encode($out);
//print_r($out);
exit();
}
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
function send_mail_test(){
var txt = $("#test_txt").val();
if( txt !=""){
$.ajax({
url : "chckvar.php",
type : "POST",
//async : false,
dataType: "JSON",
data : {
send_mail : 1,
txt_val : txt
},
success : function(data){
document.getElementById('code_r').setAttribute('value', data.a);
}
});
//return false;
}
else alert("please enter some text");
//return false;
}
</script>
<form method="post" action="sub.php" name="myform" onSubmit="return send_mail_test()">
<input type="text" name="name" id="test_txt">
<input type="text" name="code_r" id="code_r">
<input type="submit" name="_mail" value="send" >
</form>`
sub.php
<?php
print_r($_POST);
?>
UPDATE
I am using onclick on button in another form and trying to change action page from there and then submitting form to that action is that possible ??
<script>
function action(){
var str = location.href;
var x = "feedback.php?page="+str;
$("#quick_query").attr("action", x);
$('#quick_query').submit();
}
</script>
<form id="myform" method="post" action="">
<input type="button" onclick="action()">
</form>
It is changing the action but doesn't submit the form ? how can i achieve it that will be of great help.
ANSWER UPADTED:
The problem with your code is that the submit event occurs even before ajax is called. The following changes have been done in your code
HTML
<form method="post" action="sub.php" name="myform" id="myform">
<input type="text" name="name" id="test_txt">
<input type="text" name="code_r" id="code_r">
<input type="button" name="_mail" value="send" onclick="return send_mail_test()" >
</form>
<br><hr><br>
<form method="post" action="xyz.php" name="anotherform" id="anotherform">
<input type="button" name="change" value="Change action of above form" onclick="changeformaction();" >
</form>
The onsubmit on the form is removed & the submit button is changed to normal button. The send_mail_test() function is called on the Send button now.
JAVASCRIPT
<script>
function send_mail_test() {
var txt = $("#test_txt").val();
if (txt != "") {
$.ajax({
url : "chckvar.php",
type : "POST",
//async : false,
dataType : "JSON",
data : {
send_mail : 1,
txt_val : txt
},
success : function(data) {
$('#code_r').val(data.a);
$('#myform').submit();
}
});
}else{
alert("please enter some text");
return false;
}
}
function changeformaction(){
$("#myform").prop('action','newaction.php');
$('#myform').submit();
}
</script>
Here a small change is made in ajax success callback , after the response is received and the value is set in the input , the form is made to submit then.
No change is needed in your ajax file.
Try this:
<script>
$(function () {
$('form[name="myform"]').on('submit', function (e) {
e.preventDefault();
var txt = $(this).find("#test_txt").val();
if (txt.length > 0) {
$.ajax({
url: "chckvar.php",
type: "POST",
//async : false,
dataType: "JSON",
data: {
send_mail: 1,
txt_val: txt
},
success: function (data) {
$('#code_r').attr('value', data.a); //$('#code_r').val(data.a);
$(this).submit()
}
});
} else alert("please enter some text");
});
});
</script>
<form method="post" action="sub.php" name="myform">
<input type="text" name="name" id="test_txt">
<input type="text" name="code_r" id="code_r">
<input type="submit" name="_mail" value="send" >
</form>
I want to run ajax to get a value , if value is true ,then submit the form, the code bellow using onsubmit=xxx , but this form will submit immediately , not waiting ajax result. then I want to using an "a" tag with onclick function to submit the form , this can do the job, but when I using "enter" key to submit the form , will not run ajax codes. then I want to bind keypress when the cursor is in input field to submit the form. how to check the cursor is in or out of the form fields?
<?php
if(isset($_POST['act'])){
$rs=array(
'status'=>0
);
echo json_encode($rs);
exit;
}
?>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<div class="filters">
<form onsubmit="return filters.submit()">
<input type="text" name="name" />
<input type="submit" value="submit" />
</form>
</div>
<script type="text/javascript">
var filters={
form: $('.filters').find('form'),
submit: function (){
$.ajax({
url:'index.php',
type:'POST',
data:{
act:'ajax'
},
success:function(rs){
eval('var rs='+rs);
if(rs['status']==1){
return true;
}else{
return false;
}
}
});
}
}
</script>
As #Rajesh Jinaga said document.activeElement return the currently focused element but I want to explain you why it doesn't work.
When you are making your ajax call it won't wait until the ajax return true or false. It will execute. So you need to prevent the form to be submited and submit it with javascript when your ajax call is finished.
HTML
<form>
<input type="text" name="name" />
<input type="submit" value="submit" />
</form>
JAVASCRIPT (jQuery)
$('form').submit(function (e){
$.ajax({
url:'index.php',
type:'POST',
data:{
act:'ajax'
},
success:function(rs){
// No need of EVIL eval('var rs='+rs);
if(rs['status']==1){
$(this).submit(); // Will submit the form.
}else{
alert("FAILED!");
}
}
return false; // Shortcut for e.preventDefault() and e.stopPropagation() so it will prevent the form to be submitted.
});
document.activeElement returns the currently focused element, that is, the element that will get keystroke events if the user types any.
$(this).submit() won't work because you are in different context, and success callback invoker send ajax related object but not form DOM object. Store object into a variable in the form context and use it in success callback.
$(function(){
$('form').submit(function (){
var form = this;
$.ajax({
url:'index.php',
type:'POST',
data:{
act:'ajax',
status: $('[name=status]').val()
},
success:function(rs){
eval('var rs='+rs);
if(rs['status']==1){
$(form).submit(); // or $('form').submit()
}else{
alert('error');
}
}
});
return false;
});
});
#L105, thank you for your answer, I modify my code to match your answer , but the form can not submit using $(this).submit();
<?php
if(isset($_POST['act'])){
$rs=array(
'status'=> $_POST['status']
);
echo json_encode($rs);
exit;
}
?>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<div class="filters">
<form action="index.php" method="post">
<input type="text" name="status" />
<input type="submit" value="submit" />
</form>
</div>
<script type="text/javascript">
$(function(){
$('form').submit(function (){
$.ajax({
url:'index.php',
type:'POST',
data:{
act:'ajax',
status: $('[name=status]').val()
},
success:function(rs){
eval('var rs='+rs);
if(rs['status']==1){
$(this).submit(); // can't submit
}else{
alert('error');
}
}
});
return false;
});
});
</script>
I have a form that looks as following:
<form accept-charset="UTF-8" action="{{ path("fos_user_resetting_send_email") }}" method="post">
<div class="field">
<label for="username">Email:</label>
<input class="text" id="passwordEmail" name="username" required="required" size="30" type="text">
<div class="field-meta">Put in your email, and we send you instructions for changing your password.</div>
</div>
<div class="field">
<input id="submitPasswordRequest" class="full-width button" name="commit" tabindex="3" type="submit" value="Get Password">
</div>
<div class="field center">
Nevermind, I Remembered
</div>
I am trying to do the post via AJAX, so I did a simple test like this:
$("#submitPasswordRequest").click(function() {
var username = $('#passwordEmail').value();
console.log(username);
/*
$.ajax({
type: "POST",
url: "/resetting/send-email",
data: { username: username}, // serializes the form's elements.
success: function( data ) {
console.log(data); // show response from the php script.
}
});
*/
return false;
});
However it seems that the click function is not triggered and it goes to posting the form via the regular form action. What am I doing wrong here? I want to handle this via AJAX.
When you click upon the button, you simply submit the form to the back-end. To override this behavior you should override submit action on the form. Old style:
<form onsubmit="javascript: return false;">
New style:
$('form').submit(function() { return false; });
And on submit you want to perform an ajax query:
$('form').submit(function() {
$.ajax({ }); // here we perform ajax query
return false; // we don't want our form to be submitted
});
Use jQuery's preventDefault() method. Also, value() should be val().
$("#submitPasswordRequest").click(function (e) {
e.preventDefault();
var username = $('#passwordEmail').val();
...
});
Full code: http://jsfiddle.net/HXfwK/1/
You can also listen for the form's submit event:
$("form").submit(function (e) {
e.preventDefault();
var username = $('#passwordEmail').val();
...
});
Full code: http://jsfiddle.net/HXfwK/2/
jquery and ajax
$('form id goes here).submit(function(e){
e.preventDefault();
var assign_variable_name_to_field = $("#field_id").val();
...
if(assign_variable_name_to_field =="")
{
handle error here
}
(don't forget to handle errors also in the server side with php)
after everyting is good then here comes ajax
datastring = $("form_id").serialize();
$.ajax({
type:'post',
url:'url_of_your_php_file'
data: datastring,
datatype:'json',
...
success: function(msg){
if(msg.error==true)
{
show errors from server side without refreshing page
alert(msg.message)
//this will alert error message from php
}
else
{
show success message or redirect
alert(msg.message);
//this will alert success message from php
}
})
});
on php page
$variable = $_POST['field_name']; //don't use field_id if the field_id is different than field name
...
then use server side validation
if(!$variable)
{
$data['error']= true;
$data['message'] = "this field is required...blah";
echo json_encode($data);
}
else
{
after everything is good
do any crud or email sending
and then
$data['error'] = "false";
$data['message'] = "thank you ....blah";
echo json_encode($data);
}
You should use the form's submit handler instead of the click handler. Like this:
$("#formID").submit(function() {
// ajax stuff here...
return false;
});
And in the HTML, add the ID formID to your form element:
<form id="formID" accept-charset="UTF-8" action="{{ path("fos_user_resetting_send_email") }}" method="post">
You need to prevent the form from submitting and refreshing the page, and then run your AJAX code:
$('form').on('submit',function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: "/resetting/send-email",
data: $('form').serialize(), // serializes the form's elements.
success: function( data ) {
console.log(data); // show response from the php script.
}
});
return false;
});