javascript - Ajax simple example not working -
i haven't used ajax in while , can't simple program work, doing wrong ?
<script type = "text/javascript" src = "jquery-1.9.1.min.js"></script> <script type = "text/javascript"> alert(""); var count = 0; $.ajax({ url: 'get.php', datatype: 'json', success: function () { alert(""); } }); alert(""); </script> <?php echo "yay"; ?>
thanks
setting datatype
"json" means response get.php
parsed json. if it's not valid json or response empty, request fail.
if url incorrect (can't found...http 404 error), request fail.
the default type
of request "get", if get.php
doesn't allow "get" (for reason), return http error, , request fail.
if there's error on server, return http 500 error, , request fail.
something debug add error
option $.ajax
call , see if that's called. instead, use .fail()
method...it same thing.
of course, more direct way of debugging opening browser's console , viewing ajax request. should show multiple details it, can determine problems.
it might seem if ajax request never executed/sent, because don't see alert
in middle. well, because request wasn't successful, doesn't mean skipped. there plenty of reasons (i named several above) why request may fail. , .fail()
method determine cause.
also, universal convention handling deferred objects in jquery use done
, fail
methods, option. of course, $.ajax
has specific options can specify (success
, error
, , complete
- else), option. can use special methods (.success()
, .error()
, .complete()
) part of object returned $.ajax
, deprecated of version 1.8 - take @ .ajax
docs towards bottom - http://api.jquery.com/jquery.ajax/ . here's how i'd set up, shouldn't different yours, catch errors:
$.ajax({ url: 'get.php', datatype: 'json' }).done(data) { console.log("successful response"); }).fail(jqxhr, textstatus, errorthrown) { console.log("error: " + textstatus + ", " + errorthrown); });
Comments
Post a Comment