I have a simple form and I want to give an user the ability to select previously posted data using autocomplete="on". I am submitting form with AJAX. I am using Google Chrome 87.0.4280.88 64 bit. Here is the code that I have:
<form action="/Debug" method="POST" id="myForm">
Brand: <input type="text" name="brand" autocomplete="on" /><br />
Model: <input type="text" name="model" autocomplete="on" /><br />
<button type="submit">Submit</button>
</form>
<script>
$(document).ready(function () {
$('#myForm').on('submit', function (e) {
e.preventDefault();
$.ajax({
url: '/Debug',
type: 'POST',
cache: false,
success: function (data) {
console.log('data', data);
}
});
});
});
</script>
LIVE DEMO: https://jsfiddle.net/jcuzfo69/
When I submit the form for the first time, posted data is saved and displayed in autocomplete dropdown. But, when I enter new data and submit the form again, data is not saved by the browser.
Data for first submit:
Autocomplete after first submit:
Data for second submit:
Autocomplete after second submit:
I would expect to see Volkswagen listed as a brand after second submit has ocurred. Why is it not saved by the browser?
Try this one using run snipets button:
$(document).ready(function () {
$('#myForm').on('submit', function (e) {
e.preventDefault();
$.ajax({
url: '/Debug',
type: 'POST',
cache: false,
success: function (data) {
console.log('data', data);
}
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="/Debug" method="POST" id="myForm">
Brand: <input type="text" name="brand" autocomplete="on" /><br />
Model: <input type="text" name="model" autocomplete="on" /><br />
<button type="submit">Submit</button>
</form>
Related
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.
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');
}
});
}
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>
I have my form and my ajax laid out but I am not sure how to submit the form using the ajax. I've tried $('#testform').submit() but it didn't call my ajax when I wrapped it with the submit. I might of been doing it wrong. How do I get my form to submit through the ajax and not submit regularly?
<form id="testform" action="https://example.com/api/payments/" method="post">
Name<input type="text" name="name" id="name">
Card Number <input type="text" name="card_number" id="card_number" maxlength="16">
Exp Month <input type="text" name="exp_month" id="exp_month">
Exp Year <input type="text" name="exp_year" id="exp_year">
CVC <input type="text" name="cvc" id="cvc" maxlength="3">
Amount <input type="text" name="amount" id="amount">
<input type="submit" id="submit">
frm = $('#testform');
frm.submit(function(ev)
{
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
dataType: "html",
//Set the HTTP headers for authentication
beforeSend: function (xhr) {
xhr.setRequestHeader('api_key', 'tiyndhinzrkzti5ody0');
xhr.setRequestHeader('email', 'example#example.com');
},
//Serialize the data sent from the form inputs
data: frm.serialize(),
success: function(data) {
$('#return').append(data);
}
});
ev.preventDefault();
});
Instead of frm.submit(function(ev) try the following code
$("#testform").on('submit', function(ev) {
ev.preventDefault();
...
});
After clicking on the submit button you should see the ajax being posted in the console. The "magic" is to attach a handler to the submit event instead of invoking the event itself. Additionally, you had a typo in your previous code ($('testform') instead of $("#testform"))
Javascript doesn't send any post data to php file
$(document).ready(function(){
function showComment(){
$.ajax({
type:"post",
url:"process.php",
data:"action=showcomment",
success:function(data){
$("#comment").html(data);
}
});
}
showComment();
$("#button").click(function(){
var name = $("#name").val();
var message = $("#message").val();
var dataString = "name="+name+"&message="+message+"&action=addcomment";
$.ajax({
type:"post",
url:"process.php",
data:dataString,
success:function(data){
showComment();
}
});
});
});
form:
<form action="" method="POST" enctype="multipart/form-data">
name : <input type="text" name="name" id="name"/>
</br>
message : <input type="text" name="message" id="message" />
</br>
<input type="submit" value="Post" name="submit" id="button">
<div id="info" />
<ul id="comment"></ul>
</form>
php
$action=$_POST["action"];
if($action=="addcomment"){
echo "Add comment WORKS!";
}
if($action=="showcomment"){
echo "default";
}
Tried to add such lines as if post addcomment than show some words, just for a test since sql request didn't but php doesn't show any response at all, like there was no post action at all.
ps. I'm really new ajax so if possible show me a solution to solve it.
You're using a submit button so it will be making the form submit and reload which will bypass your ajax, you can change your jQuery to listen for the form submit event instead like this:
$("form").on('submit', function(e){
// Stop form from submitting
e.preventDefault();
var name = $("#name").val();
var message = $("#message").val();
var dataString = "name="+name+"&message="+message+"&action=addcomment";
$.ajax({
type:"post",
url:"process.php",
data:dataString,
success:function(data){
showComment();
}
});
});
Or simply change the button from type="submit" to type="button" or replace it with a element.
You are using submit button as Dontfeedthecode mentioned. Your form does not have any action so it is self posting. I have added action and id to the html form and a hidden field to pass the action. Now javascript serialize the form and send it to the process.php.
$(function () {
$("#my-form").on("submit", function (e) {
$("#action").val("addcomment");
$.ajax(
{
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (data) {
showComment();
}
});
return false;
});
});
<form action="process.php" method="POST" id="my-form" enctype="multipart/form-data">
<input type="hidden" id="action" name="action" value="" />
name : <input type="text" name="name" id="name" />
</br>
message : <input type="text" name="message" id="message" />
</br>
<input type="submit" value="Post" name="submit" id="button">
<div id="info" />
<ul id="comment"></ul>
</form>