Ajax code form wont work on submit - javascript

[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;
});

Related

assign php output (ajax) to javascript variable

This is my first time using javascript please be respectful. I have a form which is submitting data via ajax. Everything works as intended, however I'm trying to assign what recd.php is echoing to recresponse so the correct error code is displayed in an alert. Any help or examples would be appreciated.
Form:
<form action="recd.php" method="post" id="GAMEAPPID">
<input type="text" name="GAMEAPPID" id="GAMEAPPID" />
<input type="submit">
</form>
Javascript:
<script>
$(function(){
$("#GAMEAPPID").on("submit", function(e){
// prevent native form submission here
e.preventDefault();
// now do whatever you want here
$.ajax({
type: $(this).attr("method"), // <-- get method of form
url: $(this).attr("action"), // <-- get action of form
data: $(this).serialize(), // <-- serialize all fields into a string that is ready to be posted to your PHP file
beforeSend: function(){
$("#result").html("");
},
success: function(data){
$("#result").html(data);
if(recresponse === "0") {
alert("Incomplete.");
}
if(recresponse === "1") {
alert("Duplicate.");
}
if(recresponse === "2") {
alert("Failed");
}
if(recresponse === "3") {
alert("Thanks");
}
document.getElementById("GAMEAPPID").reset();
refreshMyDiv();
}
});
});
});
</script>
I try to answer. in your "recd.php", you should assign the recresponse to a element like <input type="hidden" id="myRS" value="<?= $myRS ?>" />
and then you can access the element in your javascript.

Passing data through ajax

I was following a tutorial to pass text to search through ajax, and it works good. Now I want to pass also checkboxes values. Can someone point me to the right direction? Right now I have:
function search(){
var term=$("#search").val();
if(term!=""){
$("#result").html("<img src='/img/spin.gif'/ style='margin-top: 30px;'>");
$.ajax({
type:"post",
url:"file.php",
data:"q="+encodeURIComponent(term), /* encodeURI is used to escape things such as plus sign */
success:function(data){
$("#result").html(data);
$("#search").val("");
}
});
}
So, basically I figure the text is sent through the post variable "q". Let's say I have an array of checkboxes, how can I add that to the same post request?
you could use jQuery's serialize.
$('#form').submit(function(e) {
var data = $('#form').serialize();
$.post('form.php',data, function(status) {
if(status == 'success') {
// success
} else {
// error
}
});
e.preventDefault();
});
form.php
<?php
$search = $_POST['search'];
etc...
$.ajax({
type:"post",
url:"file.php",
data: {
q: encodeURIComponent(term), /* encodeURI is used to escape things such as plus sign */
checkboxes: $('input[type=checkbox]').serialize()
}
success:function(data){
$("#result").html(data);
$("#search").val("");
}
});
It will be simpler for you, if you try to serialize your data.
You didn't write how your html looks like, so let's say you have a form like this:
<form id="form">
Search text: <input type="text" name="data[text]"/>
<input type="checkbox" name="data[option]" /> Option 1
<input type="submit" value="Search"/>
</form>
To send this form with ajax request, all you have to do is to serialize your form
$('#form input[type="submit"]').click(function(e) {
e.preventDefault();
$.post("file.php", $("#form").serialize(), function(){
console.log('success');
});
});
Then in your php script you can retrieve data from $_POST variable, for example $_POST['data']['text']

Form "action" using 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()

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) {});

Have to click submit twice for AJAX request to fire on form submission

My Form HTML looks like this.
<form novalidate action="register.php" method="post" >
<label for="username">Username</label>
<input type="text" name="username" required placeholder="Your username" autofocus/>
<input type="submit" name="register" value="Register" cid="submit" />
</form>
And My jQuery looks like this
$("form").submit(function(e) {
var $form = $(this);
var serializedData = $form.serialize();
request = $.ajax({
url: "check.php",
type: "post",
data: { formData: serializedData },
datetype: "JSON"
});
request.done(function(response, textStatus, jqXHR) {
console.log("HELLO");
$('form').unbind();
$('form').submit();
});
e.preventDefault();
});
The sad thing is that it logs hello to the console but it never submits the form with one click on the submit button. I need to press two times to submit button.
Can anyone tell me the problem and how can I fix it so that 1 click is sufficient for form submission.
NOTE: The data of form is send for validation not actually for submission . If data like email , username etc are valid i want the form to be submitted with one click.
Try separating the validation from the form submit.
Simply changing this line:
$("form").submit(function(e) {
to
$("input[name='register']").click(function(e) {
First of all I think it would be cleaner to use a success function instead of a .done() function. For example:
$("form").submit(function(e) {
e.preventDefault();
var $form = $(this);
var serializedData = $form.serialize();
request = $.ajax({
// Merge the check.php and register.php into one file so you don't have to 'send' the data twice.
url: "register.php",
type: "post",
data: { formData: serializedData },
datetype: "JSON",
success: function() {
console.log("This form has been submitted via AJAX");
}
});
});
Notice that I removed the .unbind() function, as I suspect it might be the reason your code is acting up. It removes the event handlers from the form, regardless of their type (see: http://api.jquery.com/unbind/). Also, I put the e.preventDefault() at the start. I suggest you try this edited piece of code, and let us know if it does or does not work.
EDIT: Oh, and yeah, you don't need to submit it when you're sending the data via AJAX.
Try this one.
$("form").submit(function(e) {
var $form = $(this);
var serializedData = $form.serialize();
request = $.ajax({
url: "check.php",
type: "post",
data: { formData: serializedData },
datetype: "JSON"
});
request.done(function(response, textStatus, jqXHR) {
console.log("HELLO");
$('form').unbind();
$('form').submit();
});
});
$("form").submit(function(e) {
e.preventDefault();
var $form = $(this);
var serializedData = $form.serialize();
$.ajax({
url: "check.php",
type: "post",
data: { formData: serializedData },
datatype: "JSON",
success: function(data) {
return data;
}
});
});
So, to break it down.
Stop the form submission with the preventDefault().
Get the form data and submit it to your validator script.
The return value, I assume, is a boolean value. If it validated, it'll be true, or false.
Return the value which will continue the form submission or end it.
NB.: This is a horrible way to validate your forms. I'd be validating my forms on the server with the form submission, because javascript can be terribly easily monkeyed with. Everything from forcing a true response from the server to turning the submission event listener off.
Once I have the same issue
What I found is I have some bug in my url xxx.php
it may return error message like "Notice: Undefined variable: j in xxx.php on line ....."
It may let ajax run unexpected way.
Just for your info.
Instead of doing prevent default when clicking a submit button, you can create a normal button and fire a function when you click it, at the end of that function, submit the form using $('#form').submit();. No more confusing prevent default anymore.
You don't need to call submit() since you are posting your data via ajax.
EDIT You may need to adjust the contentType and/or other ajax params based on your needs. PHP example is very basic. Your form is most likely much more complex. Also, you will want to sanitize any php data - don't rely on just the $_POST
jQuery:
$("form").submit(function(e) {
$.ajax({
'type': 'post',
'contentType': 'application/json',
'url': 'post.php',
'dataType': 'json',
'data': { formData: $(this).serialize},
'timeout': 50000
).done(function(data) {
// Response from your validation script
if (data === true)
{
// SUCCESS!
}
else
{
// Something happened.
}
).fail(function(error) {
console.log(error);
});
e.preventDefault();
});
PHP
$is_valid = FALSE;
$name = $_POST['name'];
if ($name !== '')
{
$is_valid = TRUE;
}
else
{
return FALSE;
}
if ($is_valid)
{
// insert into db or email or whatver
return TRUE;
}

Categories

Resources