Matthew Ciaramitaro
Matthew Ciaramitaro

Reputation: 1179

PHP Handling Jquery $.post()

I am trying to make a chat program, but am stuck on probably the most simple aspect of php. I have the following code in app.js

var msg = "123";
$.post('index.php', {send: msg});

and the following in index.php

<?php
switch($_SERVER['REQUEST_METHOD'])
{
  case 'GET':
      echo "<script type='text/javascript'>alert('GET');</script>";
      break;

  case 'POST':
    $msg = $_POST['send'];
    echo "<script type='text/javascript'>alert('POST');</script>";

}
?>

The code only alerts me about the 'GET' request I receive when loading the page. Whenever I call the $.post function in app.js nothing happens. I don't know if there's an issue with the server or if I linked to my index.php file wrong in the request?

Upvotes: 0

Views: 79

Answers (1)

Matt Davis
Matt Davis

Reputation: 470

The issue is that the jquery $.post function will send the request to the website, but then won't magically display the website output - if you don't tell it to do something with the output from the call it won't do anything.

To get it to output the response from the site, try doing something like this:

var msg = "123";

$.post('index.php', {send: msg}, function(response) {
    alert(response);
});

This provides a callback function to the jQuery POST request to instruct it on how to handle the response from the website.

jQuery post documentation

Example

Upvotes: 2

Related Questions