M
M
misha9797972018-03-24 14:53:58
PHP
misha979797, 2018-03-24 14:53:58

How can I check if the name input field is empty?

How to check if the name input field is empty? I tried if empty but I don't understand how to embed it in the query

<html lang="en">
<head>
  <meta charset="utf-8">

  <title>.</title>

  <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
  <script src="ajax.js"></script>

</head>

<body>
    <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>

    <br>

    <div id="result_form"><div> 
</body>
</html>


$( 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('Ошибка. Данные не отправлены.');
    	}
 	});
}


<?php

if (isset($_POST["name"]) && isset($_POST["phonenumber"]) ) { 

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

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

?>

Answer the question

In order to leave comments, you need to log in

4 answer(s)
A
Alexander, 2018-03-24
@misha979797

if($_POST["name"]!="")
{
// Формируем массив для JSON ответа
....
 echo json_encode($result); 
}

S
Sergey_8888, 2018-03-24
@Sergey_8888

just name == ""

V
Vladimir Borisyuk, 2018-03-25
@Flight404

if(!is_null($_POST["name"]))
{
// Form an array for the JSON response
....
echo json_encode($result);
}
Or
if(!empty($_POST["name"]))
{
// Form an array for the JSON response
....
echo json_encode($result);
}

V
vitalykostak, 2019-03-05
@vitalykostak

if (strlen(trim($_POST['name'])) == 0){
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question