Swap input button for text while performing AJAX call - javascript

I have a very simple problem. I'm trying to make an ajax call using the following button
<input type="submit" value="My Button" id="get" />
The problem is that I don't want a button, I need plain text to stand in rather than a button that gets clicked.
Full code. It's just from a small script.
$("#load_get").click(function(){
$("#result")
.html(ajax_load)
.load(loadUrl, "language=php&version=5");
});
//$.get()
$("#get").click(function(){
$("#result").html(ajax_load);
$.get(
loadUrl,
{language: "php", version: 5},
function(responseText){
$("#result").html(responseText);
},
"html"
);
});

Here's an example if I understand your question correctly:
<script>
$(function() {
$('.ajaxLink').click(function(evt) { evt.preventDefault(); /*$.get()*/});
});
</script>
<a class="ajaxLink" href="#">text</a>​

May be this can help you
$('#submit').click(function(e){
e.preventDefault();
//e.stopPropagation();
var url=$(this).closest('form').attr('action');
var formData = $(this).closest('form').serialize();
$.ajax({
type: $(this).closest('form').attr('method'),
url: url,
data: formData,
success: function(data){ ...},
error:function (xhr, ajaxOptions, thrownError)
{
alert("Error:"+xhr.status+" "+thrownError);
}
});
});
Your form could be
<form method="post" action="process.php" id="myform">
<input name="one" type="text" value="input one" />
<input name="two" type="text" value="input two" />
Submit
</form>

Related

Form not submitting on ajax request

So I'm comparing the value of the input field entered by the user to the value of the mysql DB (using an Ajax request to the checkAnswer.php file). The request itself works fine, it displays the correct "OK" or "WRONG" message, but then it does not submit the form if "OK". Should I put the .submit() somewhere else?
HTML code:
<form id="answerInput" action="index" method="post">
<div id="answer-warning"></div>
<div><input id="answer-input" name="answer" type="text"></div>
<input type="hidden" id="id" name="id" value="<?=$id?>">
<div><button type="submit" id="validate">Valider</button></div>
</form>
</div>
JS code
$("#validate").click(function(e){
e.preventDefault();
$.post(
'includes/checkAnswer.php',
{
answer : $('#answer-input').val(),
id : $('#id').val()
},
function(data){
if(data === '1'){
$("#answer-warning").html("OK");
$("#answerInput").submit();
}
else{
$("#answer-warning").html("WRONG");
}
},
'text'
);
});
I think it is because you set your button type as submit. Why?
When you do $("#validate").click(function(e){, you implicitly replace the default submit behavior of the form.
As you want to interfere in the middle of the process for extra stuff, I suggest you change the button type to button or simply remove the type attribute.
Then the $("#validate").click(function(e){ will alter behavior of click, not the submit of form.
<form id="answerInput" action="index" method="post">
<div id="answer-warning"></div>
<input id="answer-input" name="answer" type="text">
<input type="hidden" id="id" name="id" value="<?=$id?>">
<button onlcick="validate()">Valider</button>
</form>
/******** JS ************/
function validate(){
var post = {};
post['answer'] = $('#answer-input').val();
post['id'] = $('#id').val();
$.ajax({
url: 'includes/checkAnswer.php',
type: 'POST',
data: {data: post},
success:function (data) {
console.log('succsess');
},
error:function (jQXHR, textStatus, errorThrown) {
console.log('failure');
}
});
}

Why can't I clear data after click on submit button?

I make it simple:
I work with google form as my database for now.
After I added reset ability to the submit button, the JS file it sends me again to the response page of google form.
Can you help ? Thanks
<form id="form" action="https://docs.google.com/forms/u/2/d/e/1FAIpQLSeBJHw1Q6YlwO_0s2OgMhuyQEj4PLvToM1N1G5BEYQRiZlCLQ/formResponse">
<label for="">It's FREE</label>
<input type="text" placeholder="Full Name" class="inputs" id="input1" name="entry.1045366435">
<input type="email" placeholder="Email" class="inputs" id="input2" name="entry.1398681060">
<textarea cols="30" rows="10" placeholder="Message" id="input3" name="entry.403219718"></textarea>
<input type="submit" id="submit" value="Send">
</form>
$('#form').submit(function(e) {
alert("Thanks for signing up. We will contact you as soon as we can.");
e.preventDefault();
$.ajax({
url: "https://docs.google.com/forms/u/2/d/e/1FAIpQLSeBJHw1Q6YlwO_0s2OgMhuyQEj4PLvToM1N1G5BEYQRiZlCLQ/formResponse",
data: $(this).serialize(),
type: "POST",
success: function(data) {
$('#form')[0].reset()
},
dataType: "xml",
success: function(data) {
console.log('Submission successful');
},
error: function(xhr, status, error) {
console.log('Submission failed: ' + error);
}
});
});
//Alert + Disable google form response page
First you should not have two different submit handlers, just use one. Second reset is on the form, not the inputs.
success: function(data) {
$('#form')[0].reset()
console.log('Submission successful');
},
reset() is a method against form.
Thus you will need to select the form instead.
document.getElementById("form").reset();

Form submit only one value with AJAX passing form data to PHP in the same page

I need to pass a single value from my form to my php in the same page. It´s probably not an option to create another .php file and take the code there since there´s a lot going on.
This is the part of the code I need to fix, currently it only works when the code is on another file, since the $_POST is not messing around with other parts of the code. Specifically I need to manage to pass the 'client' or the 'empre' from the form alone to the php.
HTML
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/
libs/jquery/1.3.0/jquery.min.js">
</script>
<script type="text/javascript" >
$(function() {
if($(".cliente").click(function() {
var name = $("#client").val();
var dataString = 'client='+ name;
}))else if($(".empresa").click(function() {
var name = $("#empre").val();
var dataString = 'empre='+ name;
}));
$.ajax({
type: "POST",
data: dataString});
});
</script>
</head>
<body>
<form>
<input name="client" type="text"><br>
<input class="cliente" type="submit" value="Buscar cliente"/><br>
<input name="empre" type="text"><br>
<input class="empresa" type="submit" value="Buscar empresa"/><br>
</form>
//PHP HERE
//HTML AGAIN
</body>
</html>
PHP (same page, just separating for readability)
if(isset($_POST['empre'])){
//DB QUERY
}
elseif(isset($_POST['client'])){
//DB QUERY
}
You can combine and send it in same AJAX call as below, and in PHP you can do:
$parameters = json_decode($_POST['params']);
$parameters would have all the variables sent in that AJAX call.
I would recommend, not to use same page for your AJAX. You should keep it in separate file. That would make code much cleaner, lighter, readable and easy-to-tweak.
$(function() {
$(".cliente, .empresa").click(function(e) {
e.preventDefault();
var paramsToSend = {};
if ($(this).hasClass('client'))
paramsToSend['client'] = $('form[name="client"]').serialize();
else
paramsToSend['empre'] = $('form[name="client"]').serialize()
$.ajax({
url: 'index.php' //assuming this is index.php (same page)
type: "POST",
data: {
params: JSON.stringify(paramsToSend)
},
success: function(data) {},
failure: function(error) {}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form name="client">
<input name="client" type="text" value="some value"><br>
<input class="cliente" type="submit" value="Buscar cliente" />
</form>
<form name="empre">
<input name="empre" type="text" value="some value"><br>
<input class="empresa" type="submit" value="Buscar empresa" />
</form>
//PHP HERE //HTML AGAIN
Why not use separate forms to process the data? (Your PHP logic mentioned will work with this proposed solution)
$(function() {
$(".cliente").click(function(e) {
e.preventDefault();
alert('Going to post data for client, check the console log now');
$.ajax({
url: $('form[name="client"]').attr('action'),
type: "POST",
data: $('form[name="client"]').serialize(),
success: function(data){
console.log(data);
},
failure: function(error){}
});
});
$(".empresa").click(function(e) {
e.preventDefault();
alert('Going to post data for empre, check the console log now');
$.ajax({
url: $('form[name="empre"]').attr('action'),
type: "POST",
data: $('form[name="empre"]').serialize(),
success: function(data){
console.log(data);
},
failure: function(error){}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form name="client" action="https://someurl.com/fileto.php">
<input name="client" type="text" value="some value"><br>
<input class="cliente" type="submit" value="Buscar cliente"/>
</form>
<form name="empre" action="https://someurl.com/fileto.php">
<input name="empre" type="text" value="some value"><br>
<input class="empresa" type="submit" value="Buscar empresa"/>
</form>

How to submit an ajax form post that has loaded dynamically in a bootstrap modal window?

I'm going to make this as concise as possible. I'm loading this form dynamically in a modal window in Bootstrap. But when I submit it...instead of posting via ajax, the whole page is submitted. What can I do to submit via AJAX (in the background) while saving the state of the page? Here is the code that loads into the modal div element:
<script>
$(function(){
$('.modal form').on('submit', function(e){
e.preventDefault();
$.ajax({
url: "index2.html",
type: "POST",
data: $("multiform").serialize(),
success: function(data){
alert("Successfully submitted.")
}
});
});
});
</script>
<form name="multiform" id="multiform" action="index2.html" method="POST" >
Name: <input type="text" name="name" value="Ravi"/> <br/>
Age :<input type="text" name="age" value="1" /> <br/>
<input type="submit" value="Save" name="save" class="btn btn-primary" style="margin-top: 2px; height: 27px; width: 89px;" ></input>
</form>
I figured it out. I needed to surround the code with $(document).ready() and I needed to reference the data to serialize via '.modal form'. Once I did that, everything worked well.
$(document).ready( function() {
$('.modal form').on('submit', function(e){
e.preventDefault();
$.ajax({
url: "index2.html",
type: "POST",
data: $('.modal form').serialize(),
success: function(data){
alert(data);
}
});
});
});

ajax on submit no refresh form using php

ok so i know this ajax works, but i cant seem to understand why it's not submitting here.
<script type="text/javascript">
$(function(){
$('input[type=submit]').click(function(){
$.ajax({
type: "POST",
url: "postitem.php",
data: $("#myform").serialize(),
beforeSend: function(){
$('#result').html('<img src="loading.gif" />');
},
success: function(data){
$('#result').html(data);
}
});
});
});
submit form
<form action="" method="post" onsubmit="return false;" id="myform">
submit button
<input type="hidden" value="Post" name="submit" />
<button type="submit" title="Done" style="height:33px; width:50px">
<img src="../../css/images/plus_25.png" />
</button>
i'm pretty something is wrong with the button, but i want to keep the way the button is because alot of my other forms use this same button, thanks if you can explain to me why click this submit button does nothing.
You are selecting an <input> instead of a <button>. I had success by changing your jQuery selector from this:
$('input[type=submit]')
to this:
$('button[type=submit]')
http://jsfiddle.net/H3Bcc/
Not all browsers interpret a click attached to a submit button as submitting the form so you are effectively just negating the click of that button.
Preventing a form submission should preferably be captured by attaching the submit handler to the <form> when you have a <input type="submit"> or <button type="submit> so this is the best way to assure success:
jQuery
$(function(){
$('#myform').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('<img src="loading.gif" />');
},
success: function(data){
$('#result').html(data);
}
});
});
});
HTML
<form action="postitem.php" method="POST" id="myform">
<input type="hidden" value="Post" name="submit" />
<button type="submit" title="Done" style="height:33px; width:50px">
<img src="../../css/images/plus_25.png" />
</button>
</form>
try this :
<script type="text/javascript">
$(function(){
$('input[type=submit]').click(function(e){
e.preventDefault(); // prevent the browser's default action of submitting
$.ajax({
type: "POST",
url: "postitem.php",
data: $("#myform").serialize(),
beforeSend: function(){
$('#result').html('<img src="loading.gif" />');
},
success: function(data){
$('#result').html(data);
}
});
});
});

Categories

Resources