leota leota - 2 months ago 13
Javascript Question

Pusher not correctly posting to server

I'm using Pusher to create realtime notifications in HTML5. The code I'm using let an user write some text in a box and when the button "Go!" is checked, other active users will receive that text message.
Pusher also has a Debug console to check all the connections and the data transferred.

The problem I'm having is that when I click on the button the notification is sent, I can see it in the Debug console, but it doesn't contain any text, it's an empty JSON, and nothing shows up to other users.
This is the JSON which gets sent:

{
"message": null
}


I've to main files. An index.html situated in: mywebsite.com/notifications/index.html
Here it is:

<html>
<head>
<title>Realtime Notifications</title>
<script src="//js.pusher.com/2.2/pusher.min.js" type="text/javascript"></script>
<script src="//code.jquery.com/jquery-2.1.3.min.js" type="text/javascript"></script>
</head>
<body>

<div class="notification"></div>
<input class="create-notification" placeholder="Send a notification :)"></input>
<button class="submit-notification">Go!</button>

<script>

var pusher = new Pusher('MY APP KEY');

var notificationsChannel = pusher.subscribe('notifications');

notificationsChannel.bind('new_notification', function(notification){
var message = notification.message;
$('div.notification').text(message);
});

var sendNotification = function(){

// get the contents of the input
var text = $('input.create-notification').val();

// POST to our server
$.post('http://mywebsite.com/notifications/notification', {message: text}).success(function(){
console.log('Notification sent!');
});
};

$('button.submit-notification').on('click', sendNotification);

</script>

</body>
</html>


and an index.php in: mywebsite.com/notifications/notification/index.php
here's the code:

<html>
<head>
<title> notification index </title>
</head>
<body>

<?php

require(dirname(__FILE__).'/../vendor/autoload.php');

$pusher = new Pusher('MY APP KEY', 'MY APP SECRET', 'MY APP ID'');

// trigger on 'notifications' an event called 'new_notification' with this payload:

$text = $_POST['message'];

$data['message'] = $text;

$pusher->trigger('notifications', 'new_notification', $data);

?>

</body>
</html>


The code was working before adding the sendNotification function. So it's definitely not a problem related to missing libraries, dependency,etc.
Could it be a permission related problem?
Thanks in advance for your help.

Answer

Problem found. It's in the index.html when I try to post to server:

// POST to our server
    $.post('http://mywebsite.com/notifications/notification'

I needed to specify the index.php:

// POST to our server
    $.post('http://mywebsite.com/notifications/notification/index.php'

Thought it was going to find it automatically :)

Comments