$. ajax does not answer

Asked

Viewed 684 times

2

Code:

<script>
$(document).ready(function () {
    $("#submitbuy").click(function () {
        alert("clicou no submitbuy");
        var emailc = $("#emailc").val();
        alert("variavel emailc atribuida: " + emailc);
        $.ajax({
            url: 'https://meusite.com/cadastro.php',
            type: 'POST',
            data: $("#forms").serialize(),
            success: function () {
                alert("entrou no success ajax");
                if (data.length == 0) {
                    alert("forms foi submit");
                    $("#forms").submit();
                } // if
                else {
                    alert("forms não foi submit, alert data");
                    alert(data);
                } // else
            } // success
        }); // ajax
    }); // submitbuy.click
}); // document.ready
</script>

What happens to you: Displayed the first two alerts,(I used them as debug) ps: firebug does not point any error in this code above. But I did not display the third alert (the one inside the $.ajax Success).

What seems to be the problem? I have another ajax code on that same page, and it fulfills its role, I’ve gone through every possible mistake, but I found nothing..

EDIT: Form code, to make something more concrete: Form code is like this, it’s pretty simple, just to capture the email:

<form action="https://www.meusite.com/paginax" method="POST" id="forms" name="forms">
   <input name="emailc" id="emailc" placeholder="seu melhor email!" id="emailc" type="text">
</form>

the input is out of the form, type button, only to open the function to be later submitted in AJAX.

  • 3

    I think you’re missing an argument here: success: function(){... should be success: function(data){. But this if(data.length==0){ makes a mistake.

  • 1

    Indenting the code would help read it...

  • 1

    #submitbuy is a button <input type="submit"...> or a link?

  • Sergio, I was missing, I put it again, but it didn’t solve, it must be because I didn’t even get to the Success and that’s why he didn’t point out the bug in the firebug. Guilherme, is a button input, <input type="button"> and it’s out of the form, because the idea is that the form should not be submitted, but that it should go through this code above when someone clicks on submitbuy, yes later to be submitted using ajax.

  • 1

    @Alexandrec.Caus I know it should not be submitted, the question is that it could be a flaw and so I asked such a question. See my answer.

  • 1

    @Alexandrec.Caus receives some of the Alerts within the success?

  • Sergio, I don’t get paid, so I suspect you’re not entering the Cess, the mistake must be before, but I don’t see..

  • Form code, to make something more concrete: Form code is like this, it’s quite simple, just to capture the email: <form action="https://www.meusite.com/paginax" method="POST" id="forms" name="forms">&#xA;<input name="emailc" id="emailc" placeholder="seu melhor email!" id="emailc" type="text">&#xA;</form>

  • 1

    you know if ajax is coming to PHP? ('https://meusite.com/cadastro.php')

  • 1

    @Alexandrec.Caus As I said in the answer, may be a problem or another, as it is not a problem with type=submit, so it’s a problem with the requisition and how you didn’t use it error: if an error occurs in the request you will not know, so use erro: or .fail() as in the examples I have passed :)

  • I looked at the console (All tab) of Firebug, and came across this, when I clicked on the button #submitbuy: Blocked source request: Same source policy prohibits reading remote resources in meusite.com.br/action.php. This can be fixed by moving the resource to the same domain or by activating CORS.&#A; I soon realized that my website URL was with www.meusite.com.br and I was ordering for meusite.com.br/action.php.

  • Yes, the www. missing, made the source and destination of the request different, and with that, by default, the server blocked the request giving that error right above. @Guilherme, thank you for the suggestion of error: function(err) { alert(err) }, I had not thought of this possibility of catching the error, if it occurred. I also thank the rest who was willing to help me, but as you saw, the error went beyond the code, the server blocked by default this request.

  • 1

    @Alexandrec.Caus then, I should have seen this but also passed me. Instead of https://meusite.com/cadastro.php you need to use relative paths. Switch to /cadastro.php.

  • @Sergio, true, since if the site is not configured to rewrite the url (I believe it is possible for .htaccess), the user can enter both www., and www, so the best alternative, for both cases, is to use /register.php.

Show 9 more comments

1 answer

1


From the comments in the code, I’ve come to assume that you’re using something like

<form>
    <input type="submit" id="submitbuy">
</form>

May be occurring three problems:

  1. By clicking the button the page may be giving refresh and this aborts the ajax request.
  2. If you are not using button "submit", there may be a problem in ajax, so you should use callback error:
  3. (As the question author himself found @Alexandrec.Caus) You’re probably using the whole url, when only the PATH would be the most recommended. You can use it like this: url: '/cadastro.php' absolute path. Or relative path: url: 'cadastro.php' The advantage is that if the domain name changes its codes will still work without having to make modifications, this also helps with differences between https and http
  4. As @bfavaretto reported, the date argument was not set

To try to skip both problems, try something like:

$(document).ready(function () {
    $("#submitbuy").click(function () {
        alert("clicou no submitbuy");
        var emailc = $("#emailc").val();
        alert("variavel emailc atribuida: " + emailc);
        $.ajax({
            url: 'cadastro.php',
            type: 'POST',
            data: $("#forms").serialize(),
            success: function (data) {//Adicionado o argumento data
                alert("entrou no success ajax");
                if (data.length == 0) {
                    alert("forms foi submit");
                    $("#forms").submit();
                }
                else {
                    alert("forms não foi submit, alert data");
                    alert(data);
                }
            },
            error: function (err) {//Detecta erros na requisição
                alert(err);
            }
        });
        return false;//Bloqueia redirecionar em caso de type=submit
    });
});

The error: (or fail) is mandatory, because if there is a communication problem with the server or with the internet (ISP), only it will be able to report it to you.

Note that the most current version of ajax is encouraging the use of Deferred, This has nothing to do with your problem is only a tip, so if you want you can start using it like this:

$.ajax({
    url: 'https://meusite.com/cadastro.php',
    type: 'POST',
    data: $("#forms").serialize()
}).done(function (data) {//Equivalente ao success (Adicionado o argumento data)
    alert("entrou no success ajax");
    if (data.length == 0) {
        alert("forms foi submit");
        $("#forms").submit();
    } else {
        alert("forms não foi submit, alert data");
        alert(data);
    }
}).fail(function (err) {//Equivalente ao error
    alert(err);
});
  • Good, but the button is <input type="button"> and it is out of the form, the idea is that when you click this button, the form is not submitted, but goes through AJAX, and later is submitted there. Form code is like this, it is quite simple, just to capture the email: <form action="https://www.meusite.com/paginax" method="POST" id="forms" name="forms">&#xA;<input name="emailc" id="emailc" placeholder="seu melhor email!" id="emailc" type="text">&#xA;</form>

  • 1

    @Alexandrec.Caus It does not matter, this was only a theory, as I answered that before your comment, see that the answer says like this: "There may be two problems" ie is one or is another, since it is not a problem with type=submit then test the second problem. :)

  • 1

    For that you are talking about not submitting the form, you can leave your button inside the form with the value Submit, just that in the event of click() button you add the function Event.preventDefault(); So the form will not be sent...

  • 2

    It may also be a mistake because data is not set inside the callback.

  • I looked at the console (All tab) of Firebug, and came across this, when I clicked on the button #submitbuy: Blocked source request: Same source policy prohibits reading remote resources in meusite.com.br/action.php. This can be fixed by moving the resource to the same domain or by activating CORS.&#A; I soon realized that my website URL was with www.meusite.com.br and I was ordering for meusite.com.br/action.php.

  • Yes, the www. missing, made the source and destination of the request different, and with that, by default, the server blocked the request giving that error right above. @Guilherme, thank you for the suggestion of error: function(err) { alert(err) }, I had not thought of this possibility of catching the error, if it occurred. I also thank the rest who was willing to help me, but as you saw, the error went beyond the code, the server blocked by default this request.

  • 1

    @Alexandrec.Caus Formulate an answer then. With something like this. "I used meusite.com, but the right thing would be www.meusite", or so if you want to consider my answer, I’ve added some details. Note: You can yes answer your own questions, this may come to help other users.

  • @waghcwb Thank you, the return false; of the example should already amount to this.

Show 3 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.