S
S
Sandwich212020-04-27 17:51:55
PHP
Sandwich21, 2020-04-27 17:51:55

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>

ajax.js is a javascript file that contains the ajax algorithm to process the 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('Ошибка. Данные не отправлены.');
    	}
 	});
}

action_ajax_form.php is the server part that is responsible for processing the data received from the form and returns a JSON response to the client.
if (isset($_POST["name"]) && isset($_POST["phonenumber"]) ) { 

  // Формируем массив для JSON ответа
    $result = array(
    	'name' => $_POST["name"],
    	'phonenumber' => $_POST["phonenumber"]
    ); 

    // Переводим массив в JSON
    echo json_encode($result); 
}

But I need to implement this file submission without pressing the "Submit" button in the form.
those instead Should be something like But I'm not able to implement it. Could you help? $("#btn").click(
window.onload

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Alex, 2020-04-27
@Kozack

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.

N
Nadim Zakirov, 2020-04-27
@zkrvndm

Write a function that checks the phone number field and if it's correct, automatically submits the form. In short, you need a validator.

M
Mark, 2020-04-27
@yourbatya

As mentioned above, the form should be submitted on the onsubmit event, but if you are still trying to do what you came up with there, then try submitting the form on the onkeyup event in the last field of the form. Although this is a very strange decision.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question