Answer the question
In order to leave comments, you need to log in
How to submit an HTML form without pressing the submit key?
I figured out how to send form data using Ajax without reloading the page:
I have several files:
index.php is the main page that hosts the form itself
<form method="post" id="ajax_form" action="" >
<input type="text" name="name" placeholder="NAME" /><br>
<input type="text" name="phonenumber" placeholder="YOUR PHONE" /><br>
<input type="button" id="btn" value="Отправить" />
</form>
$( document ).ready(function() {
$("#btn").click(
function(){
sendAjaxForm('result_form', 'ajax_form', 'action_ajax_form.php');
return false;
}
);
});
function sendAjaxForm(result_form, ajax_form, url) {
$.ajax({
url: url, //url страницы (action_ajax_form.php)
type: "POST", //метод отправки
dataType: "html", //формат данных
data: $("#"+ajax_form).serialize(), // Сеарилизуем объект
success: function(response) { //Данные отправлены успешно
result = $.parseJSON(response);
$('#result_form').html('Имя: '+result.name+'<br>Телефон: '+result.phonenumber);
},
error: function(response) { // Данные не отправлены
$('#result_form').html('Ошибка. Данные не отправлены.');
}
});
}
if (isset($_POST["name"]) && isset($_POST["phonenumber"]) ) {
// Формируем массив для JSON ответа
$result = array(
'name' => $_POST["name"],
'phonenumber' => $_POST["phonenumber"]
);
// Переводим массив в JSON
echo json_encode($result);
}
$("#btn").click(
window.onload
Answer the question
In order to leave comments, you need to log in
Whatever you come up with, the form should be sent only by the event onsubmit
. You must have some concrete arguments to do something differently.
Write a function that checks the phone number field and if it's correct, automatically submits the form. In short, you need a validator.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question