I am using PUSHER into my site for notification.
I successfully added the codes and its working.
But the problem is when the alert is getting triggered I am receiving messages but its not what I am looking for.
I am receiving this message from Javascript alert();
{"message":"A new appointment arrived"}
alert message from pusher
And my code is
var channel = pusher.subscribe('my-channel');
channel.bind('my-event', function(data) {
document.getElementById('audio').play();
alert(JSON.stringify(data));
$.ajax({url: "notification", success: function(result){
$("#notification").html(result);
}})
});
And this is where I am getting this.
$data['message'] = 'A new appointment arrived';
$pusher->trigger('my-channel', 'my-event', $data);
I am getting the message from
JSON.stringify(data)
My question is, is there a way I can remove everything except A new appointment arrived from the alert message?
Thanks in advance.
I am a beginner and I have very little knowledge about Javascript.
If I'm understanding your question correctly, what you're asking is how you change the output that gets shown in the alert from
{"message":"A new appointment arrived"}
to just A new appointment arrived. Is that right?
What JSON.stringify() does is convert a JavaScript object into a string of text in the JSON format. Since you're not actually interested in the object, just the message it contains, there really isn't any need to use JSON.stringify here. Assuming that the data you're receiving always has the format
{ message: "Some type of message" }
you can just write alert(data.message) (or alert(data["message"]) if you don't like JavaScript dot notation).
Remove the line: alert(JSON.stringify(data)); in your JS code. That's triggering the alert with the message received from your Event.
You can read more about alert() method here: https://developer.mozilla.org/en-US/docs/Web/API/Window/alert
Related
I am successfully Posting to a PHP file, and getting a good response. The part I cannot seem to get is parsing it out then displaying it on my page. Here is my javascript in a validate handler:
submitHandler: function(form) {
var formData = $(form).serialize();
$.post('http://test.php', formData, function(data) {
if(data.success) {
$('#load').show();
var response = i;
$('#load').hide();
//var msg = '';
for(var i = 0; i < x.flights.length; i++) {
msg += '<span>';
msg += '<p>Flight Number: ' + x.flights[i].flight_number + '</p>';
msg += '<p>Cost: ' + x.flights[i].cost + '</p>';
msg += '</span>';
}
//this is were I think it should display. but It's not working
$('#load').html(msg);
Here is my json response:
success
true
message
"Success"
flights
[Object { flight_number="334", cost="983.40", departure_city="Kearney Regional Airpor...arney, Nebraska - (EAR)", more...}]
0
Object { flight_number="334", cost="983.40", departure_city="Kearney Regional Airpor...arney, Nebraska - (EAR)", more...}
flight_number
"334"
cost
"983.40"
departure_city
"Kearney Regional Airport, Kearney, Nebraska - (EAR)"
arrival_city
"Chadron Muni Airport, Chadron, Nebraska - (CDR)"
departs
"2014-03-19 04:33:00"
arrives
"2014-03-19 08:12:00"
duration
"219"
adult_seats_available
"2"
senior_seats_available
"1"
I know you you are not seeing the JSON response, but I can see it in FF firebug. I'm new to jQuery/JSON, and I just want to print the response to my page. Thanks in advance.
Look into JSON.stringify(data) doc I don't know where you want to display your JSON but if you just want to see what it is open up the debugger and console.log(JSON.stringify(data)); should do it.
You are using post method and it may default return xml, json, script, text, html. So you are getting the data from post method.
Try looking at https://api.jquery.com/jQuery.post/
And if you want to access it, then you can use JSON.stringify(data) to show json as a string. And to access data from json you can use dot(.) notation.
There's a couple of things to look at here.
First you're adding your html (ie msg) to the #load element ($('#load').html(msg);) but earlier in the code you're hiding it ($('#load').hide();). So I think this will answer your main question; i.e. remove the the line $('#load').hide(); or add $('#load').show(); after the line $('#load').html(msg);.
Still not seeing anything? Then perhaps the response isn't as corrent as you're claiming so perhaps an easier way to check what's been assigned to msg is to alert the html alert(msg); <- make this call after you've built your html.
So aside from this is the use of the #load element you seem to be using it to hold a loading gif but also assigning it the response via the content of msg. Perhaps you need to separate the use of the elements so that the #load element is for the loading gif and you add another element for the response. so you're code is more like this.
html
<div id="load" class="hide"><img src="loading-animation.gif">...</div>
<div id="post-response" class="hide alert"><div>
where the hide class is display none and alert class represents an style for a response alert.
js
submitHandler: function(form) {
// show the loading gif before we make the
// post data and wait for an async response
$('#load').show();
...
$.post('http://test.php', formData, function(data) {
if(data.success) {
// post-back has completed so lets hide the animation
$('#load').hide();
// your code to build html msg
// assign and show the response element
$('post-response').html(msg);
$('post-response').show();
...
I managed to get the JSON array into (look http://yrs2013.bugs3.com/mpapp/getSTORY.php?url=http%3A%2F%2Fcontent.guardianapis.com%2Fsearch%3Fq%3DJohn%20Stevenson%20mp%26page-size%3D3%26format%3Djson there for the array details), Javascript as a JS object - however now when i try and call a piece of data from the array it comes back as 'undefined'.. Any tips? :)
JS Code:
$.getJSON('getSTORY.php?url='+ url2, function(response)
console.log(response);
//logs the response, comes up as object in the log;
var e = response.status;
//when e is logged it just says 'undefined'
console.log(e);
In the log the object looks like drop down menus, which is different to my previous attempts of similar things as they came back from the PHP as text. I have tried JSON.parse but however that came back with the undefined o error! :l any help gratefully accepted! Thanks!
By looking at your JSON structure, I believe you need response.response.status. The first response is a variable holding your whole object, which contains a single response property with status inside (as well as results, etc).
The Program I'm writing and the functionality I'm trying to achieve
Okay. So what I'm writing at the moment is a very simple forum, in Javascript using AJAX. Part of my task is to add a new post, using an API that my lecturer wrote for us in PHP. Just to note, the API and the SQL database are completely local.
The function I am using to add this post is:
function addPosts()
{
// Add the new thread to the SQLlite database.
var treq = new Request({
url:'guestbook/control.php?action=insertPost',
'method':'post',
onSuccess: function() {
alert('win');
},
onFailure: function() {
alert('fail');
}
}).send(Object.toQueryString({
// Had to convert it to a query string because it wouldn't work as a normal object.
// These are the required values to send, to store a "post" in the database.
'name':'This is a name',
'comment':'This is a comment!'
}));
}
I am aware this will add the same data every single time. I'm just trying to get the damn thing working!
The problem
What is happening is, when this function is called, I am getting an SQL syntax error. I was confused, because that would imply that my lecturer's code is wrong. After speaking with my lecturer, he explained that this happens when the post data isn't sent correctly to the PHP code. So I went about using Google Chrome's developer tools to see what was going on, and this is what I discovered:
Now to me, this means that the data is successfully being loaded into the request, and is being passed to the PHP files fine. Obviously I'm wrong. I've been racking my brains trying to make this work.
I know that the API works fine, because everyone else in my class isn't having any problem with it, and the code I am using is practically a rip off of the code in the notes, so I'm about 90% sure that's correct to.
One thing to note is that the code in the onSuccess key runs, so I know it's not a problem on the AJAX side.
Another thing is that this code worked in University on those computers, and it's since I've got it home that it's decided not to work.
Stack Trace
Fatal error: Uncaught exception 'PDOException' with message
'SQLSTATE[HY000]: General error: 1 near ")": syntax error' in G:\Ajax
Coursework\guestbook\php\database.php:134Stack trace:#0 G:\Ajax
Coursework\guestbook\php\database.php(134): PDO->prepare('INSERT INTO
pos...')#1 G:\Ajax Coursework\guestbook\php\class.GuestBook.php(44):
DatabaseHandler->insert(Array)#2 G:\Ajax
Coursework\guestbook\control.php(8): GuestBook->insert(Array)#3
G:\Ajax Coursework\guestbook\control.php(56): insertPost()#4 {main}
thrown in G:\Ajax Coursework\guestbook\php\database.php on line 134
Object.toQueryString is used in convert an object to a query string. So if the server is requiring both $_POST['name'] and $_POST['comment'] to be set, it wont be.
Frankly because you are posting it, I dont think $_GET['name'] or $_GET['comment'] would be set either.
Request.send expects an opject. You are sending it a string. So it should be
Request.send({prop: 'value'}), not Request.send(value).
Do yourself a favor and make a PHP with the following php code, and see what it returns. It may clear this up for you right away. I have a feeling nothing is being sent except for $_GET['action']
<?php
echo '<pre>';
print_r($_GET);
print_r($_POST);
echo '</pre>';
?>
Just in-case anyone stumbles upon this thread looking for an answer:
function addPosts()
{
// Add the new thread to the SQLlite database.
var treq = new Request({
url:'guestbook/control.php?action=insertPost',
onSuccess: function() {
alert('win');
},
onFailure: function() {
alert('fail');
}
}).post('name=This is a name&comment=This is a comment!');
}
Here I'm using the .post method to POST data.
I'm sure there is a simple explanation to this. I am having problems understanding why the following alert does not display in my javascript:
<script>
theURL = "gb.json?callback=?";
$.getJSON(theURL, null, function(data) {
alert('in json proc');
});
</script>
the file gb.json is in the same folder as the html containing the script. When I run it in Firebug it gets a return code of 200 OK and I see the contents of gb.json.
This must be something very simple that I'm missing. The alert should display, shouldn't it?
It seems your server is returning regular JSON, not JSONP. Just pass the URL directly, without the added callback query string:
$.getJSON('gb.json', function(data) {
alert('in json proc');
});
How to read event.data completely from a WebSocket using JavaScript?
onMessage: function(event) {
var msg = event.data;
alert(msg);
}
In the above code, the variable msg shows only the partial data. How to receive the complete data from the WebSocket server?
event.data contains the full information; it just depends on your output how much you'll see. An alert box can only contain up to a specific amount of characters, because more characters simply wouldn't fit in the alert box. alerting is not a good practice for displaying large data.
A more convenient way is to save the length and check that, e.g.:
onMessage: function(event) {
var msg = event.data;
alert(msg.length);
}
The length should just be the correct length, i.e. the length of the characters you sent.
WebSockets is a message based transport. If the server has broken the "stream" into several message chunks then you will receive several message events and the first message event won't have all the data that you are expecting.
Also, the WebSocket definition requires that the onmessage handler is called for full messages. You can't get partial messages (unless the browser's WebSocket implementation is broken).
I would try something asynchronous instead of alert() to log the messages you receive. For example, try console.log() if you have Firebug or the Chrome Javascript console. Are you accumulating your message data in the HTML text box or just overwriting it as you receive messages?