JQuery multiple POSTs on form submission - javascript

I am trying to submit my form to 2 different scripts on form submission. ScriptA that the form is submitted to redirects on submission. ScriptB doesnt give response of any kind, just writes the given info down.
I can't get the submission to work and I am not very experienced with JQuery and it is my first time so I was hoping someone could point out why my form isn't properly submitting with JQUERY.
Body of Html:
<script type="text/javascript">
$(document).ready( function(){
$('#submit').click(function(){
//Send data to the email script
$.post( 'authenticate.php', $('Auth').serialize(), function(data, textStatus) {
//data is the result from the script
alert(data);
});
//Send data to the other script
$.post( 'http://Service3.com/j_security_check', $('Auth').serialize(), function(data, textStatus) {
//data is the result from the script
alert(data);
});
});
});
</script>
Body of html Form:
<form action=authenticate.php method=post name=Auth id="form" class="appnitro">
<div class="form_description"><h2>Login</h2></div>
<ul>
<li id="li_1" >
<label class="description" for="element_1">Username </label>
<div>
<input id="element_1" name="j_username" class="element text medium" type="text" maxlength="255" value=""/>
</div>
</li>
<li id="li_2" >
<label class="description" for="element_2">Password </label>
<div>
<input id="element_2" name="j_password" class="element text medium" type="password" maxlength="255" value=""/>
</div>
</li>
<li class="buttons">
<input id="saveForm" class="button_text" type="submit" name="submit" id="submit" value="Log In" />
</li>
</ul>
</form>
One off topic question I have is how do I fix the formatting of my code? whenever I post my code here I always get huge indentation.

$(document).ready( function(){
$('#form').submit(function(){
$.ajax({
type: 'POST',
async: false,
url: "your_url_1",
data: $(this).serialize(),
success: function(data, status, xhr){
alert('ok');
},
error: function(xhr, status, err) {
alert(status + ": " + err);
}
});
$.ajax({
type: 'POST',
async: false,
url: "your_url_2",
data: $(this).serialize(),
success: function(data, status, xhr){
alert('ok');
},
error: function(xhr, status, err) {
alert(status + ": " + err);
}
});
});
});

You have some issues with your code. Instead of binding to the click event for the submit button, why not bind to the submit event for the form. Also when you serialize the form you want to target the form and you were selecting $('Auth') which will try to select any Auth tags (which don't exist).
$('#form').submit(function(){
//Send data to the email script
$.post( 'authenticate.php', $(this).serialize(), function(data, textStatus) {
//data is the result from the script
alert(data);
});
return false;//this stops the form from submitting normally
});
Your second $.post() looks like it's sending the form submission to a different domain that the one the user is currently on. You can only do this with JSONP: http://api.jquery.com/jquery.ajax (do a search for JSONP and you will find excellent information on how to do this)

Related

How to send a photo using telegram bot with js/jquery in html form?

Previously I have some code like this to send a message to the user
<button class="notif btn btn-success"
href="https://api.telegram.org/bot{{ config('app.token') }}/sendMessage?chat_id={{ $rp->report_idsender }}&text=Halo%20{{ $rp->sender_name }}%20permintaan%20anda%20dengan%20id%20{{ $rp->id }}%20sudah%20di%20close%20">Notif</button>
and I am using jquery & js to get URL from href and execute HTTPS post request it works perfectly for me
<script type="text/javascript">
$(".notif").unbind().click(function() {
var url = $(this).attr("href");
console.log(url);
var exe = $.post(url, function() {
alert('Success');
})
});
</script>
But now I want to send a photo to a group on Telegram with reply id and the codes looks like this:
<form method="POST"
action="https://api.telegram.org/bot{{ config('app.token') }}/sendPhoto" enctype="multipart/form-data">
<input type="text" name="chat_id" value="{{ config('app.idgroup') }}" hidden />
<input type="text" name="reply_to_message_id" value="{{ $rp->msg_id }}" hidden />
<input type="text" name="allow_sending_without_reply" value="true" hidden />
<br />
<label for="caption"> Caption</label>
<input type="text" name="caption" placeholder="caption" />
<br />
<input type="file" name="photo" />
<br />
<input type="submit" value="sendPhoto" />
</form>
The problem with this code is that after I submit the form it's opening a page that contains the JSON response whereas I just want to alert it as I did in the previous code.
json response tab picture
The question is, how can I send a photo with the form with telegram bot using js/jquery with reply id in the URL ??
Your code is working fine, but redirecting to page as set in action, you can use following code to prevent default submit button behavior and ajax to stay on the same page and display success message.
<script type="text/javascript">
$(document).on("submit", "form", function (event) {
event.preventDefault();
$.ajax({
url: $(this).attr("action"),
type: $(this).attr("method"),
dataType: "JSON",
data: new FormData(this),
processData: false,
contentType: false,
success: function (data, status) {
alert('Success');
},
error: function (xhr, desc, err) {
alert('Error');
}
});
});
</script>
Add this code on head section of your page.

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();

Serialize checkboxs within Ajax call using jQuery

i need to serialize form input to send an Ajax call using jQuery to php script and each time i tried to print out the values of the form it gives empty array .
HTML Form
<form class="form-horizontal" id="generateCompression" method="post">
<fieldset>
<div class="control-group"><label class="control-label">Checkboxes</label>
<div class="controls">
<input type="checkbox" name="names[]" value="Jan-2011"> Jan-2013</label>
<input type="checkbox" name="names[]" value="Jan-2012"> Jan-2013</label>
<input type="checkbox" name="names[]" value="Jan-2013"> Jan-2013</label>
</div>
</div>
<div class="form-actions">
<button type="submit" class="btn btn-primary">Generate</button>
<button type="reset" class="btn">Cancel</button>
</div>
</fieldset>
</form>
Javascript
$(document).ready(function(){
$("#result").hide();
$("#generateCompression").submit(function(){
$.ajax({
url: "compare-action.php",
type: "POST",
data: $("#generateCompression").serialize(),
async: true,
beforeSend : function (){
$("#loading").show();
$("#reportFilecreate").fadeOut();
},
success: function(response) {
$("#loading").hide();
$("#error").show();
$("#error").html(response);
}
});
return false;
});
});
this is the PHP file
<?php
$inputs = $_POST;
print_r($inputs);
?>
Checkboxes do not send anything to the server if at least one checkbox is not checked.
Your script needs to check for the existence of your form field, if the formfield doesnt exist then you know nothing has been checked.
To test simply add a text box to your form and then run your script again.
Try this.
Send serialized data in one variable like
$.ajax({
url: "compare-action.php",
type: "POST",
traditional: true,
data: {
"test_data" : $("#generateCompression").serialize()
},
async: true,
beforeSend : function (){
$("#loading").show();
$("#reportFilecreate").fadeOut();
},
success: function(response) {
$("#loading").hide();
$("#error").show();
$("#error").html(response);
}
});
And in the compare-action.php file
print_r($_POST("test_data"));

Swap input button for text while performing AJAX call

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>

Categories

Resources