0

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?

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

2 Comments

In the php case POST echo is supposed to run javascript. It works onload for the case "GET" and in general if I just put echo <script></script> Are you saying that if I echo during a $.post() call it won't add javascript, but instead send the response back to $.post()?
The $.post call from jQuery sends the response to the website in an asynchronous manner, and doesn't redirect the browser to the page. It does it in the background, and then reads the response from the server and passes it into the callback function for processing. It's the way that jQuery is handling its processing, not the way the server is handling it. If you sent a POST request using normal HTML you would get the javascript response back the same as a GET request. In this instance, you get a response back inside the function and can write additional javascript in there.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.