Form "action" using javascript - javascript

html code :
<section class="main">
<form class="form-4" name="form4" id="form4" method="POST">
<p class="submit">
<button type="submit" name="submit" onclick="show()"><i class="icon-thumbs-up icon-large"></i></button>
</p>
</form>
</section>
js code :
function show(){
$.ajax({
type: "POST",
url: "check_login_points.php",
data: {test : JSON.stringify(arr)},
success: function(data) {
if(data == 0)
{
alert(" SORRY :( \n misplaced cue points.");
}
else if(data == 1)
{
document.getElementById("form4").action = "http://localhost/profile_book/login_key.php";
//alert("WELCOME !!!");
//$("#form4").attr('action', 'http://localhost/profile_book/login_key.php');
}
else if(data == 2)
{
alert("enter cue-points");
}
}
});
}
Am trying to put form action in javascript when an ajax function succeeds. But the form action doesn't seem to work. Suggestions are highly appreciated. Thanks in advance !

You can not do what you want to do because Asynchronous nature. It will need to be broken up into multiple parts.
First thing, rename the button to something else. You are going to run into issues.
<button type="submit" name="btnSubmit" />
second bind the form submission with jQuery, not inline events.
$("#form4").on("submit", function(event) {
//cancel the submission
event.preventDefault();
//call your logic
show();
});
Now last thing is to manually trigger the submit after setting the action.
function show (){
$.ajax({
type: "POST",
url: "check_login_points.php",
data: {test : JSON.stringify(arr)},
success: function(data) {
if(data == 0) {
alert("SORRY :( \n misplaced cue points.");
} else if(data == 1) {
$("#form4").attr("action", "http://localhost/profile_book/login_key.php")[0].submit();
} else if(data == 2) {
alert("enter cue-points");
}
}
});
}

Going out on a limb here. Going to assume you're really just asking why the form isn't submitting, in which case it's because you're missing the form-submit:
var form = document.getElementById("form4");
form.action = "http://localhost/profile_book/login_key.php";
form.submit()

Related

PHP validation for Javascript

I have a new problem. My whole website is written in PHP as well as all validations. Is there a way to do validations in php and then execute javascript like the example bellow?
if (#$_POST['submit']) {
if ($txt == "") {
$err = "No comment";
}
else {
echo "<script type='text/javascript'>
function myFunction() {
var txt' = '$txt';
var dataString = 'txt=' + txt;
$.ajax({
type: 'POST',
url: 'ajaxjs.php',
data: dataString,
cache: false,
success: function(php) {
alert(php);
}
});
}
</script>";
}
}
<div id="text">
<form action="" method='POST'>
<textarea maxlength="2000"></textarea>
<input type='button' onclick="myFunction()" name='submit' value='post' />
</form>
</div>
This doesn't work. So I'm wondering how should I do it?
I guess forms don't work with javascript, but how do I do it without a form?
You don't need to use php at all. You can post your textarea data like in the below example.
HTML
<div id="text">
<textarea id="txtArea" maxlength="2000"></textarea>
<button id="btnSubmit" name='submit'>post</button>
</div>
Javascript/jQuery
$("#btnSubmit").on('click',function(e) {
e.preventDefault();
var txtValue = $("#txtArea").val();
if(txtValue.length==0) {
alert("You have not entered any comments");
} else {
$.ajax({
type: 'POST',
url: 'ajaxjs.php',
data: {txt:txtValue},
cache: false
})
.done(function() {
alert( "success" );
})
.fail(function() {
alert( "error" );
});
}
});
The solutions is:
1. add function for submit event.
2. call ajax with form fields values as data.
3. do vildation inside php called with ajax request and return status code (valid/not valid)
4. analyse code in js and output error/success message.
First of all: Your code has a couple of errors.
You are asking if $txt == "" whilst $txt was not visibly set.
Your text area has no name
Your if doesn't ask if empty($_POST["submit"])
Second of all: You mentioned that you want the code to be executed on submit of the form. Therefore you can simple do this:
<form onsubmit="formSubmit();">
...
</form>
<script>
function formSubmit()
{
if(...)
{
return true; // Valid inputs, submit.
}
return false; // Invalid inputs, don't submit.
}
</script>
The return false is important because if it would miss, the form would be submitted as usual.

Ajax code form wont work on submit

[okay, i am sorry if i posted a duplicate question but i am just new to ajax so i somehow misused the words while searching. ]
- Jquery Form Submit Keeps Refreshing
I cant find the what is wrong with my code.
This is my form code:
<form id="UploadExcel" enctype="multipart/form-data" >
<input name="file" type="file" />
<input id="submit" type="submit" value="Submit" />
</form>
then this is my ajax form
$('#UploadExcel').submit(function(){
$.ajax({
url:'UploadServlet',
type:'POST',
dataType:'json',
data: $('#UploadExcel').serialize(),
success: function(data){
if(data.isValid){
$("#ShowSheets").modal("show");
}else{
alert('Please Put a Valid Excel Sheet');
}
}
});
return false;
});
everything is just reloading which i think is not supposed to happen since i am using ajax. There is no error or anything in the console, so i dont think I have any problem with my servlet...
use preventDefault()
$('#UploadExcel').submit(function(e){
e.preventDefault();
$.ajax({
url:'UploadServlet',
type:'POST',
dataType:'json',
data: $('#UploadExcel').serialize(),
success: function(data){
if(data.isValid){
$("#ShowSheets").modal("show");
}else{
alert('Please Put a Valid Excel Sheet');
}
}
});
return false;
});
You need to cancel the default action (form submit) first:
$('#UploadExcel').submit(function(e){
// Prevent default action
e.preventDefault()
$.ajax({
url:'UploadServlet',
type:'POST',
dataType:'json',
data: $('#UploadExcel').serialize(),
success: function(data){
if(data.isValid){
$("#ShowSheets").modal("show");
}else{
alert('Please Put a Valid Excel Sheet');
}
}
});
return false;
});

php-ajax: how to use two submit button on form every one work for different purpose

Before posting to this question i checked below links.
How do I use two submit buttons, and differentiate between which one was used to submit the form?
Two submit buttons in one form
but i am still facing issue.
Below are the codes.
html code
<form name="posting" id="posting" method="post" action="posting_bk.php" role="form">
<input class="btn btn-home" type="submit" name="publish" id="publish" alt="Publish" value="Preview and Post" />
<input class="btn btn-home" type="submit" name="save" id="save" onclick="return confirm('Are you sure you want to Submit.')" alt="Save" value="Save as Draft" /></center>
</form>
Here is the php code on posting_bk.php
if (isset($_POST['publish'])) {
# Publish-button was clicked
array_push($res['errors'], 'Publish button');
echo json_encode($res);
}
elseif (isset($_POST['save'])) {
# Save-button was clicked
array_push($res['errors'], 'Save button.');
echo json_encode($res);
}
Issue is i am not getting any output. i was suppose to get test publish or test save.
i am planning to use ajax and below is the code i have written for ajax.
<script type="text/javascript">
$('document').ready(function() {
$("#posting").on("submit", function(e) {
e.preventDefault;
var btn = $('#publish');
$.ajax({
type: 'post',
url: $('form#posting').attr('action'),
cache: false,
dataType: 'json',
data: $('form#posting').serialize(),
beforeSend: function() {
$("#validation-errors").hide().empty();
},
success: function(data) {
if (data.success == false) {
var arr = data.errors;
$.each(arr, function(index, value) {
if (value.length != 0) {
$("#validation-errors").append('<div class="alert alert-danger"><strong>' + value + '</strong><div>');
}
});
$("#validation-errors").show();
btn.button('reset');
} else {
$("#success").html('<div class="alert alert-success">Basic details saved successfully. <br> If you want to edit then please goto Edit. <div>');
$('#title').val('');
}
},
error: function(xhr, textStatus, thrownError) {
alert('Something went to wrong.Please Try again later...');
btn.button('reset');
}
});
return false;
});
});
</script>
If i didn't use ajax then it is working fine. It seems like issue with Ajax
I will go with a click submit, take the id of the clicked button and pass it to the php :
$('#posting input[type="submit"]').on("click", function(e) {
e.preventDefault;
var btn = $('#publish');
var el = $(this).attr('id');
$.ajax({
type: 'post',
url:$('form#posting').attr('action'),
cache: false,
dataType: 'json',
data: {data:$('form#posting').serialize(),action:el},
beforeSend: function() {
$("#validation-errors").hide().empty();
},
success: function(data) {
if(data.success == false)
{
var arr = data.errors;
$.each(arr, function(index, value)
{
if (value.length != 0)
{
$("#validation-errors").append('<div class="alert alert-danger"><strong>'+ value +'</strong><div>');
}
});
$("#validation-errors").show();
btn.button('reset');
} else {
$("#success").html('<div class="alert alert-success">Basic details saved successfully. <br> If you want to edit then please goto Edit. <div>');
$('#title').val('');
}
},
error: function(xhr, textStatus, thrownError) {
alert('Something went to wrong.Please Try again later...');
btn.button('reset');
}
});
return false;
});
});
php:
if ($_POST['action'] == 'publish') {
# Publish-button was clicked
echo 'test publish';
}
elseif ($_POST['action'] == 'save') {
# Save-button was clicked
echo 'test save';
}
You can't do it the way you're trying to do it because publish and save will both always be set no matter which button you click on.
You need to do it on the client side. Bind an event listener to each button and that listener will pass whatever "action" variable you want.
If you were using jQuery for example:
$('#publish').on('click', function(e){
e.preventDefault();
// Set some hidden form variable called action to a value of publish
// submit form or make an ajax call.
});
$('#save').on('click', function(e){
e.preventDefault();
// Set some hidden form variable called action to a value of save
// submit form or make an ajax call.
});
Now your PHP can check if $_POST['action'] == 'save'|'publish' and act accordingly.

input form does not work when call it from jquery ajax

Sorry but i am totally newbie for ajax and jQuery if i am asking ridiculous question.
Basically i've a form like below;
<form id="login_form" >
<input type="text" id="inputEmail" name="username">
<input type="password" id="inputPassword" name="password">
<div id="MyDynamicDiv"></div>
<button id="signin" name="signin" type="submit">button</button>
</form>
<script>
$("#login_form").submit(function() {
if ($("#login_form").valid()) {
$('.messagebox').slideUp('slow');
var data1 = $('#login_form').serialize();
$("button").button('loading');
$.ajax({
type: "POST",
url: "login/login.php",
data: data1,
dataType: 'json',
success: function(msg) {
if (msg.result == 12) {
$('#MyDynamicDiv').load('captcha.php');
}
if (msg.result == 1) {
$('.messagebox').addClass("success-message");
$('.message').slideDown('slow');
$('#alert-message').text("....");
$('#login_form').fadeOut(5000);
window.location = "members.php"
} else { return false;}
</script>
and my captcha.php is
<input type="text" name="captcha_code">
<img id="captcha" src="/test/securimage/securimage_show.php">
[ Different Image]
also login/login.php includes
echo json_encode( array('result'=>12));
I am ok to call captcha.php and show up on the page however, form does not work for captcha input. Should i call it in different way that i could not find out anywhere what i should do exactly.
Edit:
it seems input value of captcha_code does not send/post correctly. If i use the captcha.php code embedded into login form, than it works.
Thanks in advance,
It appears your captcha input is outside of the <form> element, therefore it will not be included in the POST data when you serialize() the form. Move the input inside the form element.
You seem to be missing some closing parenthesis and braces.
Doing return false from the success function does nothing because of the async nature. Instead you should return false from the submit event, or prevent default.
Corrected code with commented changes (assuming you've moved the captcha input):
$("#login_form").submit(function (e) { // capture event
e.preventDefault(); // always prevent the form from submitting
if ($("#login_form").valid()) {
$('.messagebox').slideUp('slow');
var data1 = $('#login_form').serialize();
$("button").button('loading');
$.ajax({
type: "POST",
url: "login/login.php",
data: data1,
dataType: 'json',
success: function (msg) {
if (msg.result == 12) {
$('#MyDynamicDiv').load('captcha.php');
}
if (msg.result == 1) {
$('.messagebox').addClass("success-message");
$('.message').slideDown('slow');
$('#alert-message').text("....");
$('#login_form').fadeOut(5000);
window.location = "members.php"
}
} // was missing
}); // was missing
} // was missing
}); // was missing
For future debugging, remember to check the console (F12) for errors, and indent your code because it makes missing braces more obvious. You can use the TidyUp feature of JSFiddle to auto indent it.

sending by post php ajax

Good morning, I want to send to an external site to my two variables by post are username and password and the page I create a cache in the browser when I go to another url already be logged in code what I do is check for through PHP if the data is correct or not, if they are correct returned if, but returns no, if they are correct what I want to do is force the form to send the submit the url, the problem is that everything works fine to the point the submit the form no longer do anything, can you help me?
Thank You
My code:
<script language="javascript" type="text/javascript">
$(document).ready(function () {
$("#submit").click(function () {
var user = $("#user").val();
var pass = $("#pass").val();
// Returns successful data submission message when the entered information is stored in database.
var dataString = 'user=' + user + '&pass=' + pass;
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "index.php",
data: dataString,
cache: false,
success: function (result) {
if (result == 'si') {
$("form").attr('action', 'http://xzc.tv/login');
$("form").submit();
//window.open('http://xzc.tv');
alert('entro if');
return true;
} else {
alert('entro else');
}
}
});
return false;
});
});
</script>
</head>
<body>
<form action="" method="post" id="formoid">
<div><label>Usuario:</label><input name="user" placeholder="Usuario" type="text" id="user"></div>
<div><label>Contraseña:</label><input name="pass" placeholder="Contraseña" type="text" id="pass"></div>
<div><input name="enviar" type="submit" value="Enviar" id="submit"></div>
<div><input name="btnPass" type="submit" value="¿Olvidaste tu contraseña?"></div>
</form>
</body>
Just declare the event parameter in the click handler, and then do event.preventDefault(). Doing so, the default submit action is ignored and your code will be executed instead:
$(document).ready(function () {
$("#submit").click(function (e) {
e.preventDefault();
var user = $("#user").val();
var pass = $("#pass").val();
// Returns successful data submission message when the entered information is stored in database.
var dataString = 'user=' + user + '&pass=' + pass;
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "index.php",
data: dataString,
cache: false,
success: function (result) {
if (result == 'si') {
$("form").attr('action', 'http://xzc.tv/login');
$("form").submit();
//window.open('http://xzc.tv');
alert('entro if');
return true;
} else {
alert('entro else');
}
}
});
return false;
});
});
checkout the result whether its returning "si" if its correct
try
changing code
from
$("form").attr('action', 'http://xzc.tv/login');
$("form").submit();
to
$("#formoid").attr('action', 'http://xzc.tv/login');
$("#form").submit();
try using id of form
To submit try the following
$("form#formoid").submit();
$("form#formoid")[0].submit();
$("form#formoid").submit(function(e) {});

Categories

Resources