Scripy
Scripy

Reputation: 143

Function is not working when called with AJAX

I have:

call.php:

function ajaxnotify(){
   notify('hello');
}
function notify($a){
echo "
    <script src=\"/js/jquery.min.js\"></script>
    <script src=\"//cdn.socket.io/socket.io-1.4.5.js\"></script>
    <script>
    $(function(){
        socket = io.connect(\"MY IP AND PORT\",{secure: true});
        socket.emit('say', {'msg': '$a'})
    });
    </script>
    ";
}
switch($_GET["do"]){
case "1":
     ajaxnotify();
     break;
case "2":
     notify();
     break;
}

and this code absolutely works when I directly go to mysite/call.php. But when I use:

$.ajax({
            type: "POST",
            url: "call.php?do=1",
            data: "",
            success: function(html){

            }
        });

It just doesn't work. it works when I'm directly going to page, but it doesn't work when I call ajax function from html.
Where is my mistake, guys?

Upvotes: 1

Views: 46

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337560

You're sending the request using POST, yet using $_GET to retrieve the variable in PHP.

Change the type: "POST" in jQuery, to type: 'GET'. Here's a complete example:

$.ajax({
  type: 'GET',
  url: 'call.php',
  data: { do = 1 },
  success: function(html) {
    console.log(html); // to at least verify the response
  }
});

Upvotes: 6

Related Questions