A
A
Alexander2015-10-29 23:05:07
PHP
Alexander, 2015-10-29 23:05:07

Simple ajax request not working?

Hello comrades! I’ve been struggling for 2 days and I can’t understand why it doesn’t work ...
I tried to do authorization using AJAX in one project (without ajax everything works great on sessions, databases and cookies), but for some reason the result is displayed incorrectly ...
I decided to do it on a simple example and here the same doesn't work and I can't figure out why...
Thank you all for your help!
Here is an example of the form itself:

<form method="post" id="form">
    <input type="text" name="login" id="login">
    <button type="submit" name="submit" id="submit">Отправить</button>
</form>


php:
<?php
if(isset($_POST['submit'])){
    if($_POST['login'] == "Admin"){
       echo "Неправильно";
    }
    else {
        echo $_POST['login'];
    }
}
?>

AJAX:
$('#form').submit(function(){
        var str = $(this).serialize();
        $.ajax({
            type: "POST",
            data: str,
            success: function(data){
                if(data =='Неправильно'){
                    alert('Неправильно');
                }
                else {
                    alert("Правильно");
                }
            }
        });
        return false;
    });

Answer the question

In order to leave comments, you need to log in

2 answer(s)
P
petyagrill, 2015-10-29
@alex_p95

It should always show correctly with this approach
. After all, in addition to the result of processing php, in response you get the entire generated html page
, if you want to quickly solve the problem, then change the php code to

<?php
if(isset($_POST['submit'])){
    if($_POST['login'] == "Admin"){
       echo "Неправильно";
return;
    }
    else {
        echo $_POST['login'];
return;
    }
}
?>

But it will work if php is at the very beginning of the page, and the main thing is to check if there are extra spaces.
Well, it's better to transfer the ajax processing to a separate script

D
Dmitry Skogorev, 2015-10-29
@EnterSandman

So what do you write in the console?
did you forget to add jQuery?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question