Hello to all! Tell me how you can implement this on JS:

There is a form, after pressing a key of which, JavaScript should execute a php script that is located in includes / check.php without reloading the page and get the execution result from it ( true or false ). Accordingly, if it is true , we deduce that everything is fine, if false - the alert window with the text of the error (say, just the "Error") and all this should be without reloading the page.

UPD. As I understand it, I just do not send an Ajax request. I cite my code:

JS and form:

 <script> //Check Invite $("#reg").click(function() { // получаем то, что ввёл пользователь var checkString = $(".invite").val(); // формируем строку запроса var data = 'invite='+ checkString; // если checkString не пуста $.ajax({ type: "POST", url: 'includes/checkInvite.php', data: data, success: function(data){ if(data === true){ alert("good"); } else { alert("false"); } }); }); </script> <form method="POST"> <input type="hidden" name="posted2" /> <input type="text" name="invite" title="Что бы стать участником, нужно иметь инвайт (приглашение)" class="text_box invite" placeholder="Ваш инвайт"/> <input type="submit" value="Регистрация" class="button" style="margin: 0 auto; display: block" id="reg"/> </form> 

As well as the file checkInvite.php:

 <?php session_start(); if(isset($_GET[invite]) && strlen($_GET[invite]) == 30){ //проверяем длину инвайта require_once 'classes/class.DB.php'; require_once 'classes/class.glob.php'; $objDB = new DB(); $objGlob = new Glob(); $query = $objDB->QuerySelect('*', 'invites', "invite = '$_POST[invite]'"); $myrow = mysql_fetch_assoc($query); //фетчим массив if($myrow[status] == 'active'){ //проверяем статус инвайта echo "true"; } else { //если инвайт уже использовался echo "false"; } } else { //если инвайт-строка не равна 30! echo "false"; } ?> 

    3 answers 3

    Using jQuery:


     $(function() { $('#button').click(function() { //посылаем запрос на страницу includes/check.php $.ajax({ type: "POST", //путь к скрипту url: 'includes/check.php', dataType: "text", success: function(data) { //в перменной data мы получим ответ от скрипта if (data) { //true alert ("Все ОК!"); } else { //false alert ("Не все ОК!"); } }, error:function (xhr, ajaxOptions, thrownError){ //если ошибка аякса, то выведем ее alert(xhr.status); alert(thrownError); } }); }); }); 


     <button type="button" id="button">Отправить запрос</button> 

    From the PHP script you need to display true or false, i.e. if successful, echo("true"); (for the test, write there just echo("true"); )

    Check whether the click is processed, if the request is sent:

     $(function() { $("#reg").click(function() { alert ("clicked - ok!"); $.ajax({ type: "POST", url: 'includes/checkInvite.php', success: function(data){ alert("ajax - ok! Returned data = " + data); }, error:function (xhr, ajaxOptions, thrownError){ alert("ajax error:" + xhr.status); alert(thrownError); } }); }); }); 
    • He completed his question)) - ka5itoshka
    • I suspect that you just haven't connected the jQuery library. Add the html code <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js" type="text/javascript"></script> - to the very beginning. Vitalii Maslianok
    • Everything is connected :) - ka5itoshka
    • added a handler to the response ... what kind of alerts does it output? - Vitalii Maslianok
    • one
      As always, you don’t notice the most elementary ... Wrap the handler in a function, as shown in the last example $(function() {.....}); - Vitalii Maslianok

    Ajax, look, and if you are too lazy to learn this amazing technology, then use the jQuery plugin: jQuery Form Plugin .

    • I will learn, thank you;) - ka5itoshka

    For general development: the === operator checks not only equality, but also data type compliance. Those. we get a string from the server, and try to compare it with a boolean data type. I recommend using something like:


     $.ajax({ url: 'bla-bla-bla.php', type: 'POST', dataType: 'json', success: function(data) { alert(data.message); } }); 


     if (_ОТЛИЧНО_) { echo json_encode(array('message'=>'Тут всё хорошо')); } else { echo json_encode(array('message'=>'Тут всё плохо')); } .... 

    Well, or just compare like this:

     if (data == "true") { alert('All right'); } else { alert('All bad'); } 
    • The answer has long been found. But thanks anyway for your reply :) - ka5itoshka