I am building an app with gae, and using the channel api.
String message ="<data><title>newMessage</title><message>Hello</message></data>";
channelService.sendMessage(new ChannelMessage(user,message));
This string is sent from the java servlet, and on the front end i want to parse it with jquery. This is what i did, but it doesn't work.
function onSocketMessage(message) {
var xml = $.parseXML(message.data),
$xml = $( xml ),
$title = $xml.find('title');
if($title == "newMessage"){
alert($xml.find('message'));
}
}
This is the javascript code which actually works fine.
var messageXML = ((new DOMParser()).parseFromString(message.data, "text/xml"));
var title = messageXML.documentElement.getElementsByTagName("title")[0].firstChild.nodeValue;
if(title == "newMessage"){
alert(messageXML.documentElement.getElementsByTagName("message")[0].firstChild.nodeValue);
}
function onSocketMessage(message) {
var xml = $.parseXML(message.data),
$xml = $( xml ),
$title = $xml.find('title');
if($title.text() == "newMessage"){
alert($xml.find('message'));
}
}
You should be giving .text(), I guess you missed that in this line if($title.text() == "newMessage").
Related
I have an HMTL form with 3 fields on it, Firstname, Lastname and image upload file. When submit is pressed it calls the following JS script.
//main function to be called on submit
function processData() {
var firstName = document.querySelector('#first-name'),
lastName = document.querySelector('#last-name'),
imageUser = document.querySelector('#image-user');
var formSubmitData = {
'firstName': firstName.value,
'lastName': lastName.value,
'imageUser': imageUser.value
};
var dataString = JSON.stringify(formSubmitData);
if (navigator.onLine) {
sendDataToServer(dataString);
} else {
saveDataLocally(dataString);
}
firstName.value = '';
lastName.value = '';
imageUser.value = '';
}
//called on submit if device is online from processData()
function sendDataToServer(dataString) {
var myRequest = new XMLHttpRequest();
//new code added so data is sent to server
//displays popup message - data sent to server
myRequest.onreadystatechange = function() {
if (myRequest.readyState == 4 && myRequest.status == 200) {
console.log('Sent to server: ' + dataString + '');
window.localStorage.removeItem(dataString);
} else if (myRequest.readyState == 4 && myRequest.status != 200) {
console.log('Server request could not be completed');
saveDataLocally(dataString);
}
}
myRequest.open("POST", "write_test.php", true);
//Send the proper header information along with the request
myRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
myRequest.send(dataString);
alert('Sent: ' + dataString + ''); //remove this line as only for example
}
As you will see it sends a POST request to the php page. The "datastring" is encoded as JSON.
I use the following PHP code to send the data to the SQL server, but all it does is create a blank record with no data but it does create a new record.
<?php
//TRYING NEW CODE TO EXTRACT DATA FROM dataString
$json = json_decode(file_get_contents("php://input"), true);
$data = json_decode($json, true);
echo '<pre>' . print_r($data, true) . '</pre>';
// INSERT into your contact table.
$sql="INSERT INTO contacts (firstName, lastName)VALUES('$firstName','$lastName')";
How do I get it to create records in SQL with data that has been submitted from the form??
I have no final solution as I don't have the form code. Hope you are ready to learn.
I'm worried about user image - don't send any image for testing, but a string (like path) or nothing, please.
js - change for double quotes:
var formSubmitData = {
"firstName" : firstName.value,
"lastName" : lastName.value,
"imageUser" : imageUser.value
};
php - leave only this
<?php
$data = json_decode(file_get_contents("php://input")); // test only version
print_r($data); // test only version
/*
and close the rest as a comment - SQL is fine, don't worry
$data = json_decode(file_get_contents("php://input",true)); // final ver
echo print_r($data, true); // final ver
...
*/
If you receive the right output, delete the trial version and good luck.
If not - go back to var formSubmitData to the values on the right - they are so naked ... without any quotes
And of course, take care of security (injection) and order, set the required at the inputs - you don't need empty submits
I'm trying to send data to a php file to save in database, but I don't have any response. If a checkbox is check, the [obj][idCheckbox] = 1, else [obj][idCheckbox] = 0.
File that sends
var i=0;
var objetoTodasPermissoes = function(){};
var objTodasPermissoes = new objetoTodasPermissoes();
$.each($(".classePermissoes"), function(){
objTodasPermissoes[$(this)[0].id] = 0
i++;
});
$.each($(".classePermissoes:checked"), function(){
alert('ok');
objTodasPermissoes[$(this)[0].id] = 1;
});
console.log(objTodasPermissoes);
$.each($("#userList tr"),function(){
alert(this.id);
var iduser = this.id;
$.ajax({
url:'../json/usuarioperm/savePermissions.php',
data:({
idusuario:iduser,
objTodasPermissoes:objTodasPermissoes,
}),
success:function(a){
Alert("Saved!");
}
});
});
}
the savePermissions.php file.
$iduser = $_POST["iduser"];
$perm_usuarios = $_POST["objTodasPermissoes"]["perm_usuarios"];
$perm_importar = $_POST["objTodasPermissoes"]["perm_importar"];
$perm_log = $_POST["objTodasPermissoes"]["perm_log"];
$perm_proto = $_POST["objTodasPermissoes"]["perm_proto"];
$perm_limpeza = $_POST["objTodasPermissoes"]["perm_limpeza"];
$perm_lixeira = $_POST["objTodasPermissoes"]["perm_lixeira"];
$perm_relatusuarios = $_POST["objTodasPermissoes"]["perm_relatusuarios"];
$perm_deptos = $_POST["objTodasPermissoes"]["perm_deptos"];
$perm_deptospastas = $_POST["objTodasPermissoes"]["perm_deptospastas"];
$perm_empresas = $_POST["objTodasPermissoes"]["perm_empresas"];
mysql_query("UPDATE hospital.users set
perm_usuarios=".$perm_usuarios.",
perm_importar=".$perm_importar.",
perm_log=".$perm_log.",
perm_proto=".$perm_proto.",
perm_limpeza=".$perm_limpeza.",
perm_lixeira=".$perm_lixeira.",
perm_relatusuarios=".$perm_relatusuarios.",
perm_deptos=".$perm_deptos.",
perm_deptospastas=".$perm_deptospastas.",
perm_empresas=".$perm_empresas." where id=".$iduser) or die (mysql_error());
Thank you.
PHP is kind of interesting in that it doesn't pull from $_POST like other forms when Ajax is involved. You actually will need to read the input from php://input
Here is a tiny example
$data = file_get_contents("php://input");
$response = json_decode($data, true ); // True converts to array; blank converts to object
$emailAddr = $response["email"];
Hopefully you can apply that successfully.
Edit: You can add the filter_var command to strip bad characters and sanitize the input.
$emailAddr = filter_var($response["email"], FILTER_SANITIZE_EMAIL);
$firstName = filter_var($response["firstName"], FILTER_SANITIZE_STRING);
While debugging this I would highly recommend using Chrome's Developer mode with the 'network' tab. Find your ajax call near the bottom and you can view exact header info.
Building a chat app and I am trying to fetch all logged in user into a div with ID name "chat_members". But nothing shows up in the div and I have verified that the xml file structure is correct but the javascript i'm using alongside ajax isn't just working.
I think the problem is around the area of the code where I'm trying to spool out the xml data in the for loop.
XML data sample:
<member>
<user id="1">Ken Sam</user>
<user id="2">Andy James</user>
</member>
Javascript
<script language="javascript">
// JavaScript Document
var getMember = XmlHttpRequestObject();
var lastMsg = 0;
var mTimer;
function startChat() {
getOnlineMembers();
}
// Checking if XMLHttpRequest object exist in user browser
function XmlHttpRequestObject(){
if(window.XMLHttpRequest){
return new XMLHttpRequest();
}
else if(window.ActiveXObject){
return new ActiveXObject("Microsoft.XMLHTTP");
} else{
//alert("Status: Unable to launch Chat Object. Consider upgrading your browser.");
document.getElementById("ajax_status").innerHTML = "Status: Unable to launch Chat Object. Consider upgrading your browser.";
}
}
function getOnlineMembers(){
if(getMember.readyState == 4 || getMember.readyState == 0){
getMember.open("GET", "get_chat.php?get_member", true);
getMember.onreadystatechange = memberReceivedHandler;
getMember.send(null);
}else{
// if the connection is busy, try again after one second
setTimeout('getOnlineMembers()', 1000);
}
}
function memberReceivedHandler(){
if(getMember.readyState == 4){
if(getMember.status == 200){
var chat_members_div = document.getElementById('chat_members');
var xmldoc = getMember.responseXML;
var members_nodes = xmldoc.getElementsByTagName("member");
var n_members = members_nodes.length;
for (i = 0; i < n_members; i++) {
chat_members_div.innerHTML += '<p>' + members_nodes[i].childNodes.nodeValue + '</p>';
chat_members_div.scrollTop = chat_members_div.scrollHeight;
}
mTimer = setTimeout('getOnlineMembers();',2000); //Refresh our chat members in 2 seconds
}
}
}
</script>
HTML page
<body onLoad="javascript:startChat();">
<!--- START: Div displaying all online members --->
<div id="chat_members">
</div>
<!---END: Div displaying all online members --->
</body>
I'm new to ajax and would really appreciate getting help with this.
Thanks!
To troubleshoot this:
-- Use an HTTP analyzer like HTTP Fiddler. Take a look at the communication -- is your page calling the server and getting the code that you want back, correctly, and not some type of HTTP error?
-- Check your IF statements, and make sure they're bracketed correctly. When I see:
if(getMember.readyState == 4 || getMember.readyState == 0){
I see confusion. It should be:
if( (getMember.readyState == 4) || (getMember.readyState == 0)){
It might not make a difference, but it's good to be absolutely sure.
-- Put some kind of check in your javascript clauses after the IF to make sure program flow is executing properly. If you don't have a debugger, just stick an alert box in there.
You must send the xmlhttp request before checking the response status:
function getOnlineMembers(){
getMember.open("GET", "get_chat.php?get_member", true);
getMember.onreadystatechange = memberReceivedHandler;
getMember.timeout = 1000; //set timeout for xmlhttp request
getMember.ontimeout = memberTimeoutHandler;
getMember.send(null);
}
function memberTimeoutHandler(){
getMember.abort(); //abort the timedout xmlhttprequest
setTimeout(function(){getOnlineMembers()}, 2000);
}
function memberReceivedHandler(){
if(getMember.readyState == 4 && getMember.status == 200){
var chat_members_div = document.getElementById('chat_members');
var xmldoc = getMember.responseXML;
var members_nodes = xmldoc.documentElement.getElementsByTagName("member");
var n_members = members_nodes.length;
for (i = 0; i < n_members; i++) {
chat_members_div.innerHTML += '<p>' + members_nodes[i].childNodes.nodeValue + '</p>';
chat_members_div.scrollTop = chat_members_div.scrollHeight;
}
mTimer = setTimeout('getOnlineMembers();',2000); //Refresh our chat members in 2 seconds
}
}
To prevent caching response you can try:
getMember.open("GET", "get_chat.php?get_member&t=" + Math.random(), true);
Check the responseXML is not empty by:
console.log(responseXML);
Also you might need to select the root node of the xml response before selecting childNodes:
var members_nodes = xmldoc.documentElement.getElementsByTagName("member"); //documentElement selects the root node of the xml document
hope this helps
I currently have some script on my page that parses title/artist information from my online radio station. I am displaying it as plain text in html by using
<span id="song_title"></span>
How can I take this dynamic information that is going into the span id and use it for a "post to twitter" link so listeners can share the current song title on Twitter?
I did some research and found a few variations on posting to twitter, but I had no luck with posting this dynamic text.
Here's the script code:
<!-- Begin Now Playing Script -->
<script>
(function () {
// we need a JSON parser, if it does not exist, load it
if (typeof JSON == "undefined") {
var s = document.createElement("script");
// json2.js retrieved from https://github.com/douglascrockford/JSON-js
s.src = "json2.js";
document.getElementsByTagName("head").appendChild(s);
}
})();
var song_ends = 0;
function update_song () {
if ((new Date).getTime() < song_ends) {
// use cached result as the song has not ended yet
return;
}
var req = new XMLHttpRequest();
// IE compatbility:
var textContent = 'textContent' in document ? 'textContent' : 'innerText';
req.onreadystatechange = function () {
if (req.readyState == 4) {
var song = JSON.parse(req.responseText);
if (song.title) {
var img = document.getElementById("song_image");
if(song.image.src){
img.alt = song.image.alt;
img.src = song.image.src;
img.width = 100;
img.height = 100;
}else{
img.src="images/default_art.png";
img.width = 100;
img.height = 100;
}
document.getElementById("song_title")[textContent] = song.title ;
document.getElementById("song_artist")[textContent] = song.artist;
document.getElementById("song_next")[textContent] = song.next ;
// store the end date in javascript date format
song_ends = (new Date).getTime() + song.wait_ms;
}
}
};
req.open('get', 'php/PlayingNow.php', true);
req.send(null);
}
// poll for changes every 20 seconds
setInterval(update_song, 20000);
// and update the song information
update_song();
</script>
<!-- End Now Playing Script -->
I want to be able to post it to Twitter like this: Currently listening to (song_title) by (song_artist)
Here is the code for the PHP file referenced in the script above:
<?php // filename: PlayingNow.php
$json = null;
$cache = 'song.json';
// if there is no usuable cache
if (!$json) {
// retrieve the contents of the URL
$ch = curl_init('http://bigcountry.streamon.fm/card');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$res = curl_exec($ch);
curl_close($ch);
$json = json_decode($res);
// if the title exists, assume the result to be valid
if ($json && $json->title) {
// cache it
$fp = fopen('song.json', 'w');
fwrite($fp, $res);
fclose($fp);
} else {
$json = null;
}
}
if ($json) {
$info = array();
// contains the time in milliseconds
$info['wait_ms'] = $json->interval->ends_at - 1000 * microtime(true);
$info['title'] = $json->title ;
$info['artist'] = $json->artist;
$info['album'] = $json->album ;
$info['next'] = $json->next_song;
$info['image'] = $json->album_art;
// display a JSON response for the HTML page
echo json_encode($info);
}
?>
The "right" way to do this is to use Twitter's Web Intents, which is designed specifically for this scenario. Take a look at the "Tweet or Reply to a Tweet" section. In practice you'll just include the Web Intents script (http://platform.twitter.com/widgets.js) on your page, create a link, and set its href, e.g.:
var link = document.createElement('a');
link.innerHTML = "Link Text";
link.href = 'http://twitter.com/intent/tweet?text=Currently listening to "' + songTitle + '" by ' + songArtist;
var parentElement = document.getElementById('SOME_ELEMENTS_ID');
parentElement.appendChild(link);
You can add the url parameter if you also want the tweet to include your site's URL.
I've been pulling my hair out trying to use jQuery.get() to pull in my dynamically generated RSS feed and I'm having nothing but issues, is my RSS feed the wrong format? If so can I convert it to the correct format using javascript?
Here's my feed: http://dev.chriscurddesign.co.uk/burns/p/rc_rss.php?rcf_id=0
Here's my code:
function get_rss_feed() {
$(".content").empty();
$.get("http://dev.chriscurddesign.co.uk/burns/p/rc_rss.php?rcf_id=0", function(d) {
var i = 0;
$(d).find('item').each(function() {
var $item = $(this);
var title = $item.find('title').text();
var link = $item.find('link').text();
var location = $item.find('location').text();
var pubDate = $item.find('pubDate').text();
var html = '<div class="entry">' + title + '</div>';
$('.content').append(html);
i++;
});
});
};
Any input would be greatly appreciated!!
Thanks
I tried this in IE and it worked ok.
$(document).ready(function() {
$.get('http://dev.chriscurddesign.co.uk/burns/p/rc_rss.php?rcf_id=0',
'xml' , function(data) {
alert(data);
});
});
This wont work in other browsers because of cross site scripting issues. The above code will only work if the page in which its residing is in the same domain.
So, you have many options none of which is standard though.
Best is make an ajax call to a url from your domain and then call the feed url from there ie; from server side.
For more see this
https://stackoverflow.com/search?q=calling+webservice+from+another+domain+using+jquery
Thanks to pokrate for pointing out that it was a cross-domain issue.
For future reference I'm using a php proxy now to grab the rss and then jquery to process it.
Here is the proxy (you need curl turned on in php):
<?php
$session = curl_init($_GET['url']);
curl_setopt($session, CURLOPT_HEADER, false);
curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
$xml = curl_exec($session);
header("Content-Type: text/xml");appropriately
echo $xml;
curl_close($session);
?>
And here's my new javascript:
function get_rss_feed() {
$(".content").empty();
var feed = "http://dev.chriscurddesign.co.uk/burns/p/rc_rss.php?rcf_id=0";
$.get("feedproxy.php?url=" + feed, function(d) {
$(d).find('item').each(function() {
var $item = $(this);
var title = $item.find('title').text();
var link = $item.find('link').text();
var html = '<div class="entry">' + title + '</div>';
$('.content').append(html);
});
});
};
Me = Happy Bunny :)
Just use jFeed instead, this will make you code a lot simpler.