Strange javascript (jQuery) behaviour - javascript

I have simple chat that uses ajax to get messages, heres the code:
function get_message_chat() {
$.ajaxSetup({
url: "chat.php",
global: true,
type: "GET",
data: "event=get&id=" + mid + "&t=" + (new Date).getTime()
});
$.ajax({
success: function(msg_j) {
if (msg_j.length > 2) {
var obj = JSON.parse(msg_j);
for (var i = 0; i < obj.length; i++) {
console.log(msg_j.length);
if (mid >= obj[i].id) {
continue;
}
mid = obj[i].id;
name = obj[i].name;
msg = obj[i].msg
$("#msg-box ul").append("<li><b><span class=\"username\" >" + name + "</span></b>:<span id=\"msgid_" + mid + "\" class=\"messsage\" style=\"color:black;\" > " + msg + "</span></li>");
if (msg.indexOf('#' + username) != -1) {
$("#msgid_" + mid).css('font-weight', 'bold');
}
}
$("#msg-box").scrollTop(2000);
}
}
});
setTimeout(get_message_chat, 2000);
}
mid = 0;
It grabs messages from php script "starts from mid ID". Then it shows messages to chat(appends to ul) and sets mid to new message id and then loop repeats. The problem is that it stucks fter mid = 9 for some reason. I still have more messages coming:
[{"id":"10","name":"user1","msg":"messages1234"},
{"id":"11","name":"user2","msg":"messages5678"}]
But they wont display. Everyting looks fine, but I can't understand why is that happening. Thank you for all comments.

Related

How to convert the values in an array to strings and send to php?

I have a javascript file here.What it does is,when a user selects seats accordings to his preference in a theater layout,the selected seats are stored in an array named "seat".This code works fine until function where the selected seats are shown in a window alert.But from there onwards,the code doesn't seem to do anything.
After the above window alert, I've tried to serialize the above array and send it to the "confirm.php" file.But it does not show anything when echoed the seats.
Here is the js code.
<script type="text/javascript">
$(function () {
var settings = {
rows: 6,
cols: 15,
rowCssPrefix: 'row-',
colCssPrefix: 'col-',
seatWidth: 80,
seatHeight: 80,
seatCss: 'seat',
selectedSeatCss: 'selectedSeat',
selectingSeatCss: 'selectingSeat'
};
var init = function (reservedSeat) {
var seat = [], seatNo, className;
for (i = 0; i < settings.rows; i++) {
for (j = 0; j < settings.cols; j++) {
seatNo = (i + j * settings.rows + 1);
className = settings.seatCss + ' ' + settings.rowCssPrefix + i.toString() + ' ' + settings.colCssPrefix + j.toString();
if ($.isArray(reservedSeat) && $.inArray(seatNo, reservedSeat) != -1) {
className += ' ' + settings.selectedSeatCss;
}
seat.push('<li class="' + className + '"' +
'style="top:' + (i * settings.seatHeight).toString() + 'px;left:' + (j * settings.seatWidth).toString() + 'px">' +
'<a title="' + seatNo + '">' + seatNo + '</a>' +
'</li>');
}
}
$('#place').html(seat.join(''));
};
var jArray = <?= json_encode($seats) ?>;
init(jArray);
$('.' + settings.seatCss).click(function () {
if ($(this).hasClass(settings.selectedSeatCss)) {
alert('This seat is already reserved!');
} else {
$(this).toggleClass(settings.selectingSeatCss);
}
});
$('#btnShowNew').click(function () {
var seat = [], item;
$.each($('#place li.' + settings.selectingSeatCss + ' a'), function (index, value) {
item = $(this).attr('title');
seat.push(item);
});
window.alert(seat);
});
$('#btnsubmit').click(function () {
var seat = [], item;
$.each($('#place li.' + settings.selectingSeatCss + ' a'), function (index, value) {
item = $(this).attr('title');
seat.push(item);
var seatar = JSON.stringify(seat);
$.ajax({
method: "POST",
url: "confirm.php",
data: {data: seatar}
});
});
});
});
</script>
Can somebody help me figure it out what's wrong in here?
Please Add content type as json.
$.ajax({
method: "POST",
url: "confirm.php",
contentType: "application/json"
data: {data: seatar}
});
For testing you can print file_get_contents('php://input') as this works regardless of content type.

How to sort data of json object and display accordingly in html?

This is my ajax:
$("form").on("submit", function () {
var data = {
"action": "test"
};
data = $(this).serialize() + "&" + $.param(data);
$.ajax({
type: "POST",
dataType: "json",
url: "ajax2.php",
data: data,
success: function (data) {
$("#main_content").slideUp("normal",function(){
//$(".the-return").html("<br />JSON: " + data+"<br/>");
for (i = 0; i < data.length; i++) {
$(".the-return").append("<div class='inside_return'>Name:" + data[i].name + "<br/>Id:" + data[i].id + "<br/>Pricing:" + data[i].rate + "<br/>Postcode:" + data[i].postcode+ "<br/>Reputation:" + data[i].reputation+"<br/>Review Plus:" + data[i].plus+"<br/>Review Negative:" + data[i].neg+"<br/><h1>Availability</h1>Week Morning:" + data[i].weekM+"<br/>Week Afternoon:" + data[i].weekA+"<br/>Week Evening:" + data[i].weekE+"<br/>Weekend Morning:" + data[i].endM+"<br/>Weekend Afternoon:" + data[i].endA+"<br/>Week Evening:" + data[i].endE+"</div>");
//alert(data[i].name)
}
});
}
});
return false;
});
Above is my ajax. Now this is returning result from query that sorts by postcode by default.
Now when the result displayed, I want to let the user to sort it out by reputation, review and so on..How do I do that.
Put it in a simple way, I just need to alter the order by clause in the query so that it can sort by user selection. What's the easiest way to do it please?
How can I manipulate below part where it appends the result to a div called -the-return so that it sorts by whatever key user use?: Note-> I'm presenting the result in <div> block and not in table.
$(".the-return").append("<div class='inside_return'>Name:" + data[i].name + "<br/>Id:" + data[i].id + "<br/>Pricing:" + data[i].rate + "<br/>Postcode:" + data[i].postcode+ "<br/>Reputation:" + data[i].reputation+"<br/>Review Plus:" + data[i].plus+"<br/>Review Negative:" + data[i].neg+"<br/><h1>Availability</h1>Week Morning:" + data[i].weekM+"<br/>Week Afternoon:" + data[i].weekA+"<br/>Week Evening:" + data[i].weekE+"<br/>Weekend Morning:" + data[i].endM+"<br/>Weekend Afternoon:" + data[i].endA+"<br/>Week Evening:" + data[i].endE+"</div>");
WHat I tried:
success: function (data) {
//I used a function to sort//
data.sort(function (a, b) {
var retVal = 0;
switch (sortOption) {
case 1:
retVal = a.property > b.property ? 1 : (a.property < b.property ? -1 : 0);
break;
// .... many cases here
}
return retVal;
});
//sort function ends here//
$("#main_content").slideUp("normal", function () {
for (i = 0; i < data.length; i++) {
$(".the-return").append("<div class='inside_return'>Name:" + data[i].name + "<br/>Id:" + data[i].id + "<br/>Pricing:" + data[i].rate + "<br/>Postcode:" + data[i].postcode + "<br/>Reputation:" + data[i].reputation + "<br/>Review Plus:" + data[i].plus + "<br/>Review Negative:" + data[i].neg + "<br/><h1>Availability</h1>Week Morning:" + data[i].weekM + "<br/>Week Afternoon:" + data[i].weekA + "<br/>Week Evening:" + data[i].weekE + "<br/>Weekend Morning:" + data[i].endM + "<br/>Weekend Afternoon:" + data[i].endA + "<br/>Week Evening:" + data[i].endE + "</div>");
}
});
}
so when a user clicks a button, it fire the sorting function..Sadly it doesn't work..Placing the function within success, doesn't perform search function it was doing earlier without any sort. Even if I placed it outside the function , still doesn't work.
To sort an array, you can use Array.prototype.sort.
Without any arguments, it attempts to sort elements alphabetically, but you can pass in a comparing function instead.
The function will receive two arguments and should return less than 0, 0 or greater than 0 to define where argument 1 should be in relation to argument 2.
Your sorting function should look something like this:
data.responseData.sort(function (a, b) {
switch (sortOption) {
case 1:
a = a.name,
b = b.name;
type = "string";
case 2:
a = a.reputation,
b = b.reputation;
type = "numeric";
// etc
}
if (type == "numeric")
{
// numeric comparison
return a > b ? 1 : (a < b ? -1 : 0);
} else if (type == "string") {
// string comparison
return a.localeCompare(b);
}
// etc
return;
});
localeCompare will compare the strings for you :)

pagination with AJAX url

Im beginner in AJAX & JS so please bear with me.
I use this AJAX for the pagination :
$(function () {
var keyword = window.localStorage.getItem("keyword");
//pagination
var limit = 3;
var page = 0;
var offset = 0;
$("#btnLoad").on('click', function () {
page++;
if (page != 0)
offset = (page - 1) * limit;
$.ajax({
url: "http://localhost/jwmws/index.php/jwm/search/msmall/" + keyword + "/" + limit + "/" + offset, //This is the current doc
type: "GET",
error: function (jq, st, err) {
alert(st + " : " + err);
},
success: function (result) {
alert("offset=" + offset + " page =" + page);
//generate search result
$('#search').append('<p style="float:left;">Search for : ' + keyword + '</p>' + '<br/>' + '<p>Found ' + result.length + ' results</p>');
if (result.length == 0) {
//temp
alert("not found");
} else {
for (var i = 0; i < result.length; i++) {
//generate <li>
$('#list').append('<li class="box"><img class="picture" src="images/HotPromo/tagPhoto1.png"/><p class="name"><b>Name</b></p><p class="address">Address</p><p class="hidden"></p></li>');
}
var i = 0;
$(".box").each(function () {
var name, address, picture, id = "";
if (i < result.length) {
name = result[i].name;
address = result[i].address;
picture = result[i].boxpicture;
id = result[i].mallid;
}
$(this).find(".name").html(name);
$(this).find(".address").html(address);
$(this).find(".picture").attr("src", picture);
$(this).find(".hidden").html(id);
i++;
});
$(".box").click(function () {
//alert($('.hidden', this).html());
window.localStorage.setItem("id", $('.hidden', this).html());
$("#pagePort").load("pages/MallDetail.html", function () {});
});
}
}
});
}).trigger('click');
});
Please notice that i use the variables for pagination in the url:. I tried to alert the page and offset variable, and its working fine.
However, the AJAX only working for the first page (when page load). The rest is not working even though the page and offset variable's value is true.
Theres no warning/error in console. The data just not shown.
Any help is appreciated, Thanks :D
It is a bit hard to debug your code when the whole HTML is missing.
Could you put your code into JSFiddle, both HTML and JS.

Parsing the json data from google and twitter differences

I am new to javascript. I have worked on twitter API. In twitter API i used jQuery.ajax function to get json data from twitter servers. But when i use the same option with google maps server, my app isn't giving any response the moment it enters the jQuery.ajax. I tried to debug it using jslint, but it came out clean. I used debugging using alert, and it stops when it enters jQuery.ajax function. Is meathod to retrieve data varies with the source ?
If not why isn't my code responding ?
Twitter running function ::
var twitterapi = "http://search.twitter.com/search.json?";
jQuery.ajax(
{
type: "GET",
url: twitterapi,
data:
{
"q": hashtag,
"rpp": 1000
},
dataType: 'jsonp'
}).done(function (response)
{
var results = response.results;
for (var i = 0; i < results.length; i++)
{
$("#tweet").prepend("<li class='tweet'>" +
"<img src='" +
results[i].profile_image_url +
"'/>" +
"<span class='username'>" +
results[i].from_user +
"</span> <span class='tweet_content'> " +
results[i].text +
"</span></li>");
}
});
My google maps API(not working)
var j = 2;
var friends = [];
var distance =[];
$(document).ready(function () {
alert("function started");
$('#button').click(function () {
if (j < 11) {
$('#friends').append('Friend' + j + ':<input type="text" id="friend' + j + '"/><br/><br/>');
j++;
}
else {
alert("Limit reached");
}
});
$('button').click(function(){
var a =[];
alert("button clickede");
for(i=1;i<=j;i++)
{
a[i] = $("#friend" + i).val();
}
var gurl = "http://maps.googleapis.com/maps/api/distancematrix/json?"+
"origins=" +
a.join('|').replace(/ /g,'+') +
"&destinations=" +
a.join('|').replace(/ /g,'+') +
"&sensor=false";
alert("making request to" +gurl);
jQuery.ajax(
{
type: "GET",
url: gurl,
dataType: 'jsonp'
}).done(function (response)
{
alert("request made to"+gurl);
var rows = response.rows;
alert(row[0].elements[0].value);
for(var i=0;i<rows.length;i++)
{
for(var j=0;j<elements.length;j++)
{
distance[i][j] = row[i].elements[j].distance.value;
}
}
alert(distance[0][0]);
});
});
});
I don't know what error are you getting so i can't be of much help.
But the code you posted has three issues:
1- Since a is undefined, i couldn't get past the first two lines.
2- Removing the a calls in the code, then it threw a Syntax Error. I fixed this by removing the last }); line.
3- It made the request, but it threw another error (probably because the URL was malformed).

How to move jquery function/callback into document ready

How can I change this code so that I can add it to the standard document ready for jquery so that all my scripts are together.
/*
* Fetch RSS feed once page has finished loading.
*/
(function(url, callback) {
jQuery.ajax({
url: document.location.protocol + '//ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=10&callback=?&q=' + encodeURIComponent(url),
dataType: 'json',
success: function(data) {
callback(data.responseData.feed);
}
});
})('http://www.bet365.com/news/en/betting/sports/rss', function(feed){
var entries = feed.entries, content, publishDate;
for (var i = 0; i < entries.length; i++) {
publishDate = new Date(entries[i].publishedDate);
date = publishDate.getDate() + '/' + publishDate.getMonth() + '/' + publishDate.getFullYear();
content = truncateText((entries[i].contentSnippet) ? entries[i].contentSnippet : entries[i].content, 100);
jQuery('#rss > ul').append('<li><span> ' + date + '</span>' + entries[i].title + '</li>');
}
});
separate the functions.. it will good to use and understand
var my_callback = function(feed){ // Change to desired URL
var entries = feed.entries, content, publishDate;
for (var i = 0; i < entries.length; i++) {
publishDate = new Date(entries[i].publishedDate);
date = publishDate.getDate() + '/' + publishDate.getMonth() + '/' + publishDate.getFullYear();
content = truncateText((entries[i].contentSnippet) ? entries[i].contentSnippet : entries[i].content, 100);
jQuery('#rss > ul').append('<li><span> ' + date + '</span>' + entries[i].title + '</li>');
}
function make_ajax_call(url, callback) {
jQuery.ajax({
url: document.location.protocol + '//ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=10&callback=?&q=' + encodeURIComponent(url),
dataType: 'json',
success: function(data) {
callback(data.responseData.feed);
}
});
}
then
$(document).ready(function(){
make_ajax_call('http://www.bet365.com/news/en/betting/sports/rss',my_callback);
});
Just wrap it with:
$(function(){
// Your code here
});
Actually $ is an alias for $.ready (and it's the same as $(document).ready) if function is passed as argument

Categories