Ajax callback not working

I can't get a callback to work from this, but it gets the answer to its simple test. does anyone know why dosnt do this how i want

<script type="text/javascript"> $(document).ready(function(e) { $("button").click(function() { var msg = $("#txt").val(); $.post( "http://localhost/bot.php", {msg: msg}, function(data,status) { $("p").text(data); } ); }); }); </script> 

PHP, and can anyone suggest a good JavaScript tool to help me find bugs?

 <?php class ai { private $msg; public function __construct($msg) { $this->msg = $msg; } public function respond() { switch($this->msg) { case "hi": echo "Hello Mr Brown How are You"; break; case "fine": echo "Good to hear Did you know Zanda hard Coded me?"; break; case "im fine": echo "Good to hear Did you know Zanda hard Coded me?"; break; default: echo "??????????????????????????????" . "That means i was extra rush prototype.......i cant answer that"; } } } $talk = new ai($_POST['msg']); $talk->respond(); ?> <div class="box"> <p>text</p> <textarea id="txt"></textarea> <button>click</button> </div> 

there is html that makes it as short as it can be

+4
source share
2 answers

This seems to be related to a policy of the same origin and from the MDN documentation

The port number is stored separately by the browser. Any setter call, including document.domain = document.domain, causes the port number to be overwritten with zero. Therefore, you cannot talk company.com:8080 with company.com only by setting document.domain = "company.com" in the first place. It must be set so that the port numbers are empty.

That's why you get a null value, as you said in your answers

Try adding datatype:"jsonp" . It works like that.

 $ (document) .ready (function (e) {
     $ ("button"). click (function () {
         var msg = $ ("# txt"). val ();
         $ .post (
             "http: //localhost/bot.php",
             {msg: msg},
             function (data, status) {
                 $ ("p"). text (data);
             },
             dataType: "jsonp"
         );
     });
 });

Further reading here .

Hope this helps.

0
source

Something to try here is to change $.post for $.ajax so that you can specify an error callback. $.get , $.post , etc. - these are just transcripts for $.ajax . Try something like this:

 ("button").click(function() { var msg = $("#txt").val(); $.ajax( url: "http://localhost/bot.php", data: {msg: msg}, dataType: 'jsonp', success: function(data,status) { console.log(data, "returned with status:", status); }, error: function(obj, status, error){ console.log("Error!", obj, status, error); } ); }); 

Just because you get a 200 response does not mean that everything is working correctly. All this suggests that POST was successful. You need to check the response text to see if any errors are returned.

EDIT: added to dataType: 'jsonp' for the request.

+1
source

Source: https://habr.com/ru/post/1496757/


All Articles