OpenWeather API - Pulling JSON data out - javascript

I'm writing a little JavaScript to pull information from JSON that contains name, longitude, latitude and openweather API call. What I need is to get the API information out of the API call into the HTML page so you can get the weather forecast for each information. I have the two elements working separately but can't work out how to get them working together.
Help please? :-)
Sample API Weather from d.weather
api.openweathermap.org/data/2.5/forecase?lat=50.8609&lon=-0.08014&&units=metric
HTML page for pulling the openweather JSON data
<html>
<head>
<title>Weather</title>
<meta charset="utf-8">
<script src="http://code.jquery.com/jquery-1.7.min.js" ></script>
<script src="http://code.jquery.com/ui/1.7.0/jquery-ui.js" ></script>
<script>
function getWeather(callback) {
var weather = 'http://api.openweathermap.org/data/2.5/forecast?lat=51.5072&lon=0.1275&units=metric';
$.ajax({
dataType: "jsonp",
url: weather,
success: callback
});
}
// get data:
getWeather(function (data) {
console.log('weather data received');
console.log(data.list[0].weather[0].description);
console.log(data.list[0].weather[0].main);
});
getWeather(function (data) {
document.write('weather data received');
document.write('<br>');
document.write(data.list[0].weather[0].description);
document.write('<br>');
document.write(data.list[0].weather[0].main);
document.write('<br>');
document.write(data.list[0].main.temp);
document.write('<br>');
document.write(data.list[0].main[0].dt_txt);
document.write('<br>');
});
</script>
</body>
</html>
Html page for pulling the JSON data
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.0.min.js"></script>
<!-- Javascript -->
<script type="text/javascript">
function loadUrl(newLocation){
window.location = newLocation;
return false;
}
</script>
<script type="text/javascript">
$(document).ready(function (){
$("#btn382").click(function(){
/* set no cache */
$.ajaxSetup({ cache: false });
$.getJSON("weather.json", function(data){
var html = [];
/* loop through array */
$.each(data, function(index, d){
html.push("Team : ", d.Teams, ", ",
"Long : ", d.Long, ", ",
"Lat : ", d.Lat, ", ",
"Weather : ", d.Weather, "<br>");
});
$("#div381").html(html.join('')).css("background-color", "orange");
}).error(function(jqXHR, textStatus, errorThrown){ /* assign handler */
/* alert(jqXHR.responseText) */
alert("error occurred!");
});
});
});
</script>
<!-- HTML -->
<a name="#ajax-getjson-example"></a>
<div id="example-section38">
<div>Football weather</div>
<div id="div381"></div>
<button id="btn382" type="button">Team location</button>
</div>
weather.json
{
"Teams":"Wycombe Wanderers",
"Long":-0.800299,
"Lat":51.6306,
"Weather":" api.openweathermap.org/data/2.5/weather?lat=51.6306&lon=-0.800299&mode=html"
},
{
"Teams":"Livingston",
"Long":-3.52207,
"Lat":55.8864,
"Weather":" api.openweathermap.org/data/2.5/weather?lat=55.8864&lon=-3.52207&mode=html"
},
{
"Teams":"Brighton and Hove Albion",
"Long":-0.08014,
"Lat":50.8609,
"Weather":" api.openweathermap.org/data/2.5/weather?lat=50.8609&lon=-0.08014&mode=html"
},

I have the basics that should help you on your way. It's a mashup of your two pages.
First I amended your getWeather function to call for the weather rather than the forecast. It accepts a city parameter and appends that parameter to the data before the callback is called.
function getWeather(city, callback) {
var url = 'http://api.openweathermap.org/data/2.5/weather';
$.ajax({
dataType: "jsonp",
url: url,
jsonCallback: 'jsonp',
data: { q: city },
cache: false,
success: function (data) {
data.city = city;
callback(data);
}
});
}
Here, in lieu of your teams JSON I made one up in the form of a JS object, with Arsenal and Liverpool and their corresponding cities as the data. The function loops over the object, extracts the city name and passes it to getWeather. The data is returned and appended to the div.
$(document).ready(function () {
$("#btn382").click(function () {
var teams = {
arsenal: { city: 'london' },
liverpool: { city: 'liverpool' }
};
for (var team in teams) {
var city = teams[team].city;
getWeather(city, function(data) {
var html = [];
html.push('<div>')
html.push('City: ', data.city, ', ');
html.push('Lat: ', data.coord.lat, ', ');
html.push('Lon: ', data.coord.lon, ', ');
html.push('Weather: ', data.weather[0].description);
html.push('</div>')
$("#div381").append(html.join('')).css("background-color", "orange");
});
}
});
});
Hopefully this will give you a few ideas about how to tackle this project.
See it working here.

I have made a complete example. For me this worked:
HTML file:
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-2.1.0.min.js"></script>
<meta charset="utf-8">
<title>jQuery Ajax</title>
<link rel="stylesheet" href="css/ajx-json-styles.css">
<script>
function displayParsedData(data){
/* Working with the 'data' object (not string) here, now we can access the different properties available.*/
text = '<b>Name: </b>' + data.list[0].name + '<br/>';
text += '<b>message: </b>' + data.message + '<br/>';
text += '<b>Current Temperature: </b>' + data.list[0].main.temp + ' F<br/>';
text += '<b>Weather Conditions: </b>' + data.list[0].weather[0].description + '<br/>';
$('#parsed_json').append(text);
}
</script>
<script>
function test1() {
getWeather(function (data) {
$("#raw_json").html('<h2>callback</h2><pre>' + JSON.stringify(data, null, 2) + '</pre>');
displayParsedData(data);
});
}
function getWeather(callback) {
var weather = 'http://openweathermap.org/data/2.1/find/city?lat=8.2924495&lon=-62.7373258';
$.ajax({
dataType: "jsonp",
url: weather,
success: callback
});
}
</script>
<script>
function test2() {
$.ajax({
url: 'http://openweathermap.org/data/2.1/find/city?lat=8.2924495&lon=-62.7373258',
type: 'GET',
dataType:"jsonp",
success: function(data) {
$("#raw_json").html('<h2>$.ajax</h2><pre>' + JSON.stringify(data, null, 2) + '</pre>');
displayParsedData(data);
},
error: function(jqXHR, textStatus, error) {
alert( "error: " + jqXHR.responseText);
}
});
}
</script>
<script>
function test3() {
$.getJSON('http://openweathermap.org/data/2.1/find/city?lat=8.2924495&lon=-62.7373258&callback=?', function(data) {
$("#raw_json").html('<h2>getJSON</h2><pre>' + JSON.stringify(data, null, 2) + '</pre>');
displayParsedData(data);
})
.done(function() {
alert( "second success" );
})
.fail(function() {
alert( "error" );
});
}
/*$.getJSON('http://openweathermap.org/data/2.1/find/city?lat=13.3428&lon=-6.2661&cnt=10&callback=?', function(data) { console.log(data); });*/
</script>
<script>
$(document).ready(function (){
$("#btn382").click(function(){
/* set no cache */
$.ajaxSetup({ cache: false });
$.getJSON("weather.json", function(data){
for (var team in data) {
var html = [];
html = '<div class="item"><b>Team: </b>' + data[team].Teams + '<br/>';
html += '<b>Lat: </b>' +data[team].Lat + '<br/>';
html += '<b>Lon: </b>' + data[team].Lon + '<br/>';
html += '<b>Weather: </b>' + data[team].Weather + '<br/></div>';
$("#div381").append(html);
}
})
.error(function(jqXHR, textStatus, errorThrown){ /* assign handler */
/* alert(jqXHR.responseText) */
alert("error occurred!");
});
});
});
</script>
</head>
<body>
<div id="example-section38">
<div>Otra fuente</div>
<div id="div381"></div>
<button id="btn382" type="button">Team location</button>
</div>
<div id="raw_json"></div>
<div id="parsed_json"></div>
<button onclick="test1();">callback</button>
<button onclick="test2();">$.ajax</button>
<button onclick="test3();">getJSON</button>
</body>
</html>
weather.json
[
{
"Teams":"Wycombe Wanderers",
"Lon":-0.800299,
"Lat":51.6306,
"Weather":" api.openweathermap.org/data/2.5/weather?lat=51.6306&lon=-0.800299&mode=html"
},
{
"Teams":"Livingston",
"Lon":-3.52207,
"Lat":55.8864,
"Weather":" api.openweathermap.org/data/2.5/weather?lat=55.8864&lon=-3.52207&mode=html"
},
{
"Teams":"Brighton and Hove Albion",
"Lon":-0.08014,
"Lat":50.8609,
"Weather":" api.openweathermap.org/data/2.5/weather?lat=50.8609&lon=-0.08014&mode=html"
}
]
ajx-json-styles.css
#raw_json {
border:1px solid #333;
background-color:#ccc;
padding: 2em;
word-wrap: break-word;
margin-bottom: 2em;
width: 40%;
float: left;
}
#parsed_json {
padding:2em;
border: 1px solid blue;
width: 40%;
float: right;
}
h2 {
margin:0;
padding:0;
}
.item{
padding-bottom: 0.25em;
padding-top: 0.25em;
background-color: #E9BB18;
border: 1px solid white;
}

why don't you use xml instead of json it's easy to parse, i use it in my website weathercase , try api provider yr.no

Related

Chosen plug-in is not working when i create the element dynamically

Chosen plug-in is not working when i create the element dynamically
i created Select list dynamically from ajax response and the problem is Chosen plug-in not working with it , Please help me to solve it
here is my code:
function GetSubCategories(ID) {
$.ajax({
cache: false,
url: '/Home/GetSubCategoriesByAjax',
type: 'GET',
datatype: 'Json',
data: { id: ID },
success: function (data) {
if (data.length > 0) {
console.log(data)
$("#SubListSelect").empty();
var $SubListSelect = $('<select id ="SubListSelect" class = "form-control"></select>');
$SubListSelect.append('<option>Select Sub Category</option>');
$.each(data, function (i, value) {
$SubListSelect.append('<option value=' + value.SubCategoryId + '>' + value.SubCategoryName + '</option>');
});
$("#Div1").empty();
$("#Div1").append($SubListSelect);
}
else {
}
},
error: function (r) {
alert('Error! Please try again.');
console.log(r);
}
});
}
and and plugin code:
$(document).ready(function ($) {
$(function () {
$("#SubListSelect").chosen();
});
Thank you
My proposal:
in my demo I used a different url for the ajax and I figured out a possible HTML.
function GetSubCategories(ID) {
$.ajax({
cache: false,
url: "https://api.github.com/users",
type: 'GET',
dataType: "json",
data: { id: ID },
success: function (data) {
if (data.length > 0) {
var SubListSelect = $('<select id ="SubListSelect" class = "form-control"></select>')
.append('<option>Select Sub Category</option>');
$.each(data, function (i, value) {
SubListSelect.append('<option value=' + value.id + '>' + value.login + '</option>');
});
$("#Div1").empty().append(SubListSelect);
$("#Div1").find(SubListSelect).chosen()
} else {
}
},
error: function (r) {
alert('Error! Please try again.');
console.log(r);
}
});
}
$(document).ready(function ($) {
$("#SubListSelect").chosen();
$('#btn').on('click', function(e) {
GetSubCategories('1');
});
});
<script src="https://code.jquery.com/jquery-1.12.3.min.js"></script>
<!--
The next two lines are the include files for chosen plugin
-->
<link rel="stylesheet" type="text/css" href="//cdnjs.cloudflare.com/ajax/libs/chosen/1.1.0/chosen.min.css">
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/chosen/1.1.0/chosen.jquery.min.js"></script>
<div id="Div1">
This is the starting div:
</div>
<button id="btn">Click Me To Create New chosen object into DIV</button>
I assume the select is in #Div1 which you are emptying, then re-appending.
in that case you need to re-initialize it:-
$("#Div1").empty();
$("#Div1").append($SubListSelect);
$("#SubListSelect").chosen();
A better option though would be to only empty the select and re-append the options to the select without emptying the #Div1. then call:-
$("#SubListSelect").trigger("chosen:updated");
also, this
$(document).ready(function ($) {
and this
$(function () {
mean the same thing, with the latter being short hand. Therefore you only need one.

JSON to HTML not rendering into HTML via ID

I am using PHPstorm IDE and i'm trying to render the following JSON and it gets stuck showing only the <ul></ul> without spitting the <li>'s into HTML the each function. Any idea what could be the issue?
thanks.
Script.js:
$(function(){
$('#clickme').click(function (){
//fetch json file
$.ajax({
url:'data.json',
dataType: 'json',
success: function(data){
var items = [];
$.each(data, function (key, val) {
items.push('<li id=" ' + key + '">' + val + '</li>');
});
$('<ul/>', {
'class': 'tasks',
html: items.join('')
}).appendTo('body');
},
statusCode: {
404: function(){
alert('there was a problem with the server. try again in a few secs');
}
}
});
});
});
And the JSON:
{"id":"1","mesi":"mesima 0","done_bool":"1"},{"id":"2","mesi":"mesima 1","done_bool":"0"},{"id":"3","mesi":"mesima 2 ","done_bool":"1"},{"id":"4","mesi":"mesima 3","done_bool":"1"}
My HTML is just an a href that spits out the click ID:
Get JSON
<script>
$(document).ready(function(){
$("button").click(function(){
$.getJSON("demo_ajax_json.js", function(result){
$.each(result, function(i, field){
$("div").append(field + " ");
});
});
});
});
</script>
<button>Get JSON data</button>
By Using this Method You can Easily get Your JSON value In HTML
Try this one :)
$.ajax({
url: 'data.json',
dataType: 'json',
success: function(data){
var html = "<ul>";
items = data.map(function(obj){
html += "<li id='" + obj.id + "'>" + obj.mesi + "</li";
});
html += "</ul>";
$('body').append(html);
I would try with some like this
$(function(){
$('#clickme').click(function (){
//fetch json file
$.ajax({
url:'data.json',
dataType: 'json',
success: function(data){
// uncomment line below if data is a single JSON
// data = [data]
var items = [];
// we create a list where we will append the items
var list = document.createElement("ul");
data.forEach(function(item){
// we create a list item
var listItem = document.createElement("li");
// we set the attributes
listItem.setAttribute("id", item.id ); // item.id or the property that you need
// we add text to the item
listItem.textContent = item.mesi;
// We append the list item to the list
list.appendChild(listItem);
});
// we append the list to the body
$("body").html(list);
},
statusCode: {
404: function(){
alert('there was a problem with the server. try again in a few secs');
}
}
});
});
});
Try like this:
success: function(data){
var items = '';
$.each(data, function (key, val) {
items += '<li id=" ' + key + '">' + val + '</li>';
});
ul = $('<ul/>').html(items);
$('body').append(ul);
}
for multiple objects
success: function(datas){
var items = '';
$.each(datas, function (i,data) {
$.each(data, function (key, val) {
items += '<li id=" ' + key + '">' + val + '</li>';
});
});
ul = $('<ul/>').html(items);
$('body').append(ul);
}
output
<ul>
<li id=" id">1</li>
<li id=" mesi">mesima 0</li>
<li id=" done_bool">1</li>
<li id=" id">2</li>
<li id=" mesi">mesima 1</li>
.
.
</ul>
Try like this:
$(function() {
$('#clickme').click(function() {
// fetch json file
$.ajax({
url : 'data.json',
dataType : 'json',
// please confirm request type is GET/POST
type : 'GET',
success : function(data) {
// please check logs in browser console
console.log(data);
var ulHtml = "<ul>";
$.each(data, function(key, obj) {
ulHtml += '<li id="' + obj.id + '">' + obj.mesi + '</li>';
});
ulHtml += "</ul>";
// please check logs in browser console
console.log(ulHtml);
$('body').append(ulHtml);
},
error : function(jqXhr, textStatus, errorThrown) {
console.log(errorThrown);
alert(textStatus);
}
});
});
});
<button id="clickme">Get JSON data</button>
I log json data and created ul html, Please check logs in browser console
I'm not sure how you want to output each item, so I made a simple suggestion, you can easily change the HTML to what you need. Here is working code:
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
</head>
<body>
Get JSON
<script>
$(function() {
$('#clickme').click(function() {
//fetch json file
$.ajax({
url: 'data.json',
dataType: 'json',
success: function(data) {
var items = [];
$.each(data, function(key, val) {
// the HTML output for each item
var done = (val.done_bool === '1') ? 'true' : 'false';
items.push('<li id=" ' + val.id + '">' + val.mesi + ': ' + done + '</li>');
});
$('<ul/>', {
'class': 'tasks',
html: items.join('')
}).appendTo('body');
},
statusCode: {
404: function() {
alert('there was a problem with the server. try again in a few secs');
}
}
});
});
});
</script>
</body>
</html>
data.json
[{"id":"1","mesi":"mesima 0","done_bool":"1"},{"id":"2","mesi":"mesima 1","done_bool":"0"},{"id":"3","mesi":"mesima 2 ","done_bool":"1"},{"id":"4","mesi":"mesima 3","done_bool":"1"}]
I also created a __jsfiddle__ so you can test it directly. (The AJAX call is simulated with the Mockjax library): https://jsfiddle.net/dh60nn5g/
Good to know:
If you are trying to load the JSON from another domain, you may need to configure CORS (Cross-origin resource sharing):
https://en.wikipedia.org/wiki/Cross-origin_resource_sharing
Isn't this supposed to be a GET request? i think you are missing the method on your Ajax request. You should add
method: 'GET'
to your ajax request. I think this is a big deal in making ajax request.

How do I write the AJAX to post data

Fiddle
I am trying to learn AJAX from a tutorial.
I am able to grab the data I want and populate it in the DOM pretty easily.
What I'm struggling with is using 'POST' to edit it.
I created a simple page that lists 'friends' and 'ages' that pulls that data from here
http://rest.learncode.academy/api/learncode/friends
The names and ages populate correctly, but the code I'm writing to 'POST' to it is not.
Here is my javascript
<script>
$(function () {
var $friends = $('#friends');
var $name = $('#name');
var $age = $('#age');
$.ajax({
type: 'GET',
url: 'http://rest.learncode.academy/api/learncode/friends',
success: function (data) {
console.log("I have friends!", data);
$.each(data, function(i, name){
$friends.append('<li>name: '+ name.name + '<br />' + ' age:' + name.age +' </li>');
})
},
error: function () {
alert("error loading data");
}
});
$('#add-order').on('click', function () {
});
});
</script>
HTML
<div class="large-12 columns" id="ajaxContainer">
<h1>
AJAX Container
</h1>
<h3>
Friends
</h3>
<ul id="friends">
</ul>
<h3>Add a friend</h3>
<p>
Name:
<input type="text" id="name" />
</p>
<p>
Age:
<input type="text" id="age" />
</p>
<button id="add-order"> submit</button>
</div>
I am guessing as to what you actually want, but it seems that you want the page to populate with whatever friends are currently in the database on first load, and then when you click add-order button, it adds new friends and updates your list. The first thing is that you are trying to POST to the learncode name, which you can't do. Change where it says "yourname" in the URLs below to something else. Here is what you should do:
<script>
$(function () {
var $friends = $('#friends');
var $name = $('#name');
var $age = $('#age');
$.ajax({
type: 'GET',
url: 'http://rest.learncode.academy/api/yourname/friends',
success: function (data) {
console.log("I have friends!", data);
$.each(data, function(i, name){
$friends.append('<li>name: '+ name.name + '<br />' + ' age:' + name.age +' </li>');
})
},
error: function () {
alert("error loading data");
}
});
$('#add-order').on('click', function () {
$.ajax({
type: 'POST',
data: {"id":3, "age": $age.val(), "name":$name.val()},
url: 'http://rest.learncode.academy/api/yourname/friends',
success: function () {
$.ajax({
type: 'GET',
url: 'http://rest.learncode.academy/api/yourname/friends',
success: function (data) {
$friends.html("");
console.log("I have friends!", data);
$.each(data, function(i, name){
$friends.append('<li>name: '+ name.name + '<br />' + ' age:' + name.age +'
</li>');
})
},
error: function () {
alert("error loading data");
}
});
},
error: function () {
alert("error loading data");
}
});
});
});
</script>
See the part that says
type : "GET"
-?-
change it to
type : "POST"
Then, the url parameter is what you are POSTing to-
And you are not actually sending any data -!
So, try this:
$(function () {
var $friends = $('#friends');
var $name = $('#name');
var $age = $('#age');
$.ajax({
type: 'POST',
url: 'http://yourWebsite.com/someScriptToHandleThePost.php',
data: [{"id":1,"name":"Will","age":33},{"id":2,"name":"Laura","age":27}],
success: function (data) {
console.log("I have friends!", data);
$.each(data, function(i, name){
$friends.append('<li>name: '+ name.name + '<br />' + ' age:' + name.age +' </li>');
})
},
error: function () {
alert("error loading data");
}
});
$('#add-order').on('click', function () {
});
});
Then, you're going to need a PHP script to handle the POSTed data and return a response, which gets passed in the data param in success:function(data){}
start out with something simple, like this:
<?php
print_r($_POST);
?>
and change your success function to:
success: function(data) {
$("body").append("<pre>"+data+"</pre>");
}
and that should get you on the right track....

webservice jquery function

In below code I tries to read book details form A url, but it does not display the output.In output screen while clicking ajax button, it will not enter in to the $(data).find("Book").each(function(){});
My code html:
<html>
<head>
<script src="http://ajax.microsoft.com/ajax/jQuery/jquery-1.4.2.js" type="text/javascript" charset="utf-8"></script>
<script src="http://ajax.microsoft.com/ajax/jQuery/jquery-1.4.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
function bodyload() {
alert("We are calling jquery's ajax function and on success callback xml parsing are done");
$.ajax({
url: 'http://www.edumobile.org/blog/uploads/XML-parsing-data/Data.xml',
dataType: 'application/xml',
timeout: 10000,
type: 'GET',
success: function(data) {
alert("inside success function");
$("#bookInFo").html("");
$("#bookInFo").append("<hr>"); * * // my code work until here after that i will not receive any book details in my web page.**
$(data).find("Book").each(function() {
$("#bookInFo").append("<br> Name: " + $(this).find("name").text());
$("#bookInFo").append("<br> Address: " + $(this).find("address").text());
$("#bookInFo").append("<br> Country: " + $(this).find("country").text());
$("#bookInFo").append("<br><hr>");
});
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Error status :" + textStatus);
alert("Error type :" + errorThrown);
alert("Error message :" + XMLHttpRequest.responseXML);
$("#bookInFo").append(XMLHttpRequest.responseXML);
}
});
}​
</script>
</head>
<body>
<center><button onclick="bodyload()">Ajax call</button></center>
<p id="bookInFo"></p>
</body>
</html>
Please tell me why am not getting output.
I think that data parameter of success function is a js object parsed from xml, not the html\dom. You can't apply $() to it. Try
for(var i = 0; i < data.length; i++) {var name = data[i].name; etc...}
or
for(var prop in data){var name = data[prop].name; etc...}

Long polling will keep the page loading (javascript issue)

I've build a chat script with long-polling but I don't understand why it keeps loading. The long-polling should start after submitting a text but it looks like it starts automatically.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<title>Helpdesk Longpolling Test</title>
<script type="text/javascript" src="jquery-1.3.2.min.js"></script>
<link rel="stylesheet" href="css/style.css" type="text/css" />
<script type="text/javascript" charset="utf-8">
var timestamp = null;
var name = "Guest: ";
function sendReply(message, myAsync) {
$.ajax({
type: "GET",
url: "putData.php?text=" + message,
async: myAsync,
cache: false,
success: function(data) {
var json=eval('('+data +')');
//alert(json["code"]);
if (json["code"] == "500") {
$('div#chatbox').append('Error<br />');
} else if (json["code"] == "200") {
$("#textToChat").val("");
}
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
$('div#chatbox').append('<p>Error: ' + textStatus + ' (' + errorThrown + ')</p>');
//alert("error: " + textStatus + " ("+errorThrown + ")");
}
});
}
function waitForMsg() {
$.ajax({
type: "GET",
url: "getData.php?timestamp=" + timestamp,
async: true,
cache: false,
success: function(data) {
var json=eval('('+data +')');
if (json["msg"] != "") {
//alert(json["msg"]);
$('div#chatbox').append(' ' + json["msg"] + '<br />');
}
timestamp = json["timestamp"];
setTimeout('waitForMsg()', 1000);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
$('div#chatbox').append('<p>Error: ' + textStatus + ' (' + errorThrown + ')</p>');
alert("error: " + textStatus + " ("+errorThrown + ")");
//setTimeout('waitForMsg()', 1000);
}
});
}
$(window).load(function() {
$('#sendMessage').submit(function() {
sendReply(name+" is connected.", true);
setTimeout(function() {
waitForMsg();
openConnection = true;
}, 500);
var text = $("#textToChat").val();
sendReply(name+": "+text, true);
return false;
});
});
$(window).bind('beforeunload', function(){
sendReply(name+" has left the conversation.", false);
});
</script>
</head>
<body>
<div id="chatbox">
<h3>Live Support!</h3>
</div>
<form method="get" id="sendMessage">
<input id="textToChat" name="text" type="text" value="Type your question..." size="63" />
<input name="submitmsg" type="submit" id="submitmsg" value="Verzenden" />
</form>
<input type="button" id="actie" name="actie" value="Actie_in_CMS" />
</body>
</html>
Someone who has an idea? I guess I've made a stupid mistake but can't figure it out myself after 2 days trying to debug the script. After the page is loaded , the script is working fine.

Categories

Resources