JQuery append is not doing as intended - php

I have a problem with my JQuery script. I am making a 2d chat where people have their own figure like Habbo hotel, but the JQuery script that is suppose to move the figures is bugging.
I think it is easier to show the problem:
Click here to see the problem
I am using the following script to update the figures:
function UpdateRoom() {
var data = 'roomId='+roomId;
$.ajax({
type: "GET",
url: "chatfunctions/updateroom.php",
dataType: 'json',
data: data,
success: function(data){
$.each(data, function(i, data) {
var temp = parseInt(data.field);
$('#f' + temp).append('<div class="user" id="'+charId+'" />');
});
}
});
}
The #f+temp is the id of the field that the figure should be places at. The charId is the id of the figure.
And then I am calling the script every 500 miliseconds:
window.setInterval(function() {
UpdateRoom();
}, 500 );
Im not sure if this is enough code and example for you guys to help me. If not please tell me if I need to provide more for you to help me. My guess is that it is the .append(); function that is used wrong, but I'm no expert in JQuery.

You are only continuing to append but not replacing anything.
Try to either use .html() or .empty().
$.each(data, function(i, data) {
var temp = parseInt(data.field);
$('#f' + temp).html('<div class="user" id="'+charId+'" />');
});
or
$.each(data, function(i, data) {
var temp = parseInt(data.field);
$('#f' + temp).empty(); // clear out all content
$('#f' + temp).append('<div class="user" id="'+charId+'" />');
});
not knowing your code you might need to move the call to .empty() outside your each loop.

Related

How can I get information from MySQL with Ajax?

So i am trying to learn Ajax with jQuery, to retrieve some information. At the moment, I have problem to get the information. My code is very simple at the moment, just because I want to learn how it works. This is my HTML code.
<h2>Hello world</h2>
<p id="response"></p>
My jQuery code:
$(function(){
$('h2').on('click', function() {
$.ajax({
url: "ajax.php",
type: "get",
datatype: "json",
success: function(data){
$.each(data, function(i, key){
$("#response").html(key['name'])
});
},
error: function(data){
console.log("tjohejsan");
}
})
});
});
So when I click on h2 it should retrieve data. What I want is to make a call from my database to get information about the users.
So my php code looks like this:
$sql = "SELECT * FROM moment2";
$result = mysqli_query($db,$sql) or die("Fel vid SQL-fråga");
$array = array();
while($row = $result->fetch_assoc())
{
$array[] = $row;
}
echo json_encode($array);
At this point, this is where it fails. I don't know really where the problem is. Because I want an associative array.
I would appreciate it if you could assist me, because as I mentioned, I don't really know how to solve it from here.
Thanks in advance!
EDIT: I realised I had a typo while writing this. changing data['name'] to key['name']
You have issue in the jquery each function. Replace the success function as
success: function(data){
$.each(data, function(i, key){
$("#response").html(key['name'])
});
},
It is because jquery each function has key and value as argument, so only replace "data" by "key" in your this line: $("#response").html(data['name'])
There are a couple places that you are going to run into trouble with this. Here is a JSFiddle for you to reference with my tips below:
https://jsfiddle.net/MrProvolone/zgw9ymv3/2/
There are a few things to consider...
1). Your returned data needs to be converted using parseJSON(), which is a built in jQuery function. This will convert your JSON string into a JavaScript object.
2). When you are looping through your object, you need to include the number (i) that you are trying to access
3). Because we are making a new object variable, we don't need the "key" designator in your $.each() function call... so it becomes $.each(data, function(i){}); instead of $.each(data, function(i, key){});
3). When you are trying to write out your html, you must grab what is already in the container, then add your new html to it, and finally write it all back out to the container.
Here is a step by step:
Instead of:
success: function(data){
$.each(data, function(i, key){
$("#response").html(key['name'])
});
}
We need to add the parsing (and remove the "key" variable per #3 above) so it becomes this:
success: function(data){
var parsed = jQuery.parseJSON(data);
$.each(data, function(i){
$("#response").html(key['name']);
});
}
Now we have a new variable to work off of (parsed) so we need to change both the $.each line, and the .html() line to make sure it uses that new variable....
So this:
$.each(data, function(i, key){
$("#response").html(key['name']);
});
Becomes this:
$.each(parsed, function(i){
$("#response").html(parsed['name']);
});
But that still won't work. We are looping through the object, so when we try to access a value, we have to specify which element in the object we are trying to get to. So anywhere in your loop that looks like this:
parsed['keyname']
becomes this:
parsed[i]['keyname']
So now we have:
$.each(parsed, function(i){
$("#response").html(parsed[i]['name']);
});
At this point you should be getting some html in your container. However, you will notice that you are only getting the value of the last row of your data. That is because you are overwriting ALL of your html in the container in each loop, instead of adding to what is already there. We need to make a new variable to fix this. So this:
$.each(parsed, function(i){
$("#response").html(parsed[i]['name']);
});
Becomes this:
$.each(parsed, function(i){
var oldhtml = $("#response").html();
$("#response").html(oldhtml + '<br>' + parsed[i]['name']);
});
Now you will see each result, with a html line break between each one.
Hope this helps!
In your js, on the success callback, you are using the wrong data, and not appending the data retrieved to the html Tag
Here is an essai
success: function(data){
if(typeof data != "object"){
data = JSON.parse(data);
}
$.each(data, function(i, key){
$("#response").append(key['name'])
});
}

Multiple Arrays returned by json from PHP

To begin with I am building a complete CRM running Ajax and there is a lot to this, so please be patient and read the whole thing.
I have an ajax script returning several json arrays. When I display the return value from my php script I get this:
[{"packages":{"id":"1","name":"Land Line"}},{"packages":{"id":"2","name":"Cellular w\/Alarm.com"}},{"packages":{"id":"3","name":"Home Automation"}}]
What I am trying to do is separate the arrays so I can make a select drop down from it. Before anyone says anything, yes I know how to do that my itself, but I am needing the form this script is populating to be a select dropdown or a complete filled in form based off of the id going into another script. It is a bit confusing, so don't ding me for it please.
Here is the PHP script alliance_form.php:
$equip = "SELECT * FROM packages WHERE brand='$brand'";
if($db->query($equip) === false) {
trigger_error('Wrong SQL: ' . $query . ' Error: ' . $db->error, E_USER_ERROR);
} else {
$result = $db->query($equip);
$array = array();
foreach($result as $r) {
$array[] = array(
"packages" => array(
"id" => $r['id'],
"name" => $r['name']
)
);
}
echo json_encode($array);
}
Here is the jquery going to the PHP form and coming back to input the information:
$.ajax({
type: "POST",
url: "/crm/alliance_form.php",
data: dataString,
success: function(msg)
{
$("#package-form").html(msg);
$.each(msg.packages, function(i, object) {
$.each(object, function(index, value) {
alert(value);
});
});
},
error: function(error)
{
$(".error").html(error);
}
});
This is part of an ordering system of a CRM, so this script is checking the database for existing orders under the id. If the id is there then it is supposed to come back with the order information and I populate the form. If not it will give a select dropdown to select a package which then populates an empty form. That is the gist of what I am on right now.
Here is the question: Why can't I get a response from JQuery on the each() loop on this. One return comes back with a regular array, and this one is a nested array.
I'm not quite clear on what you're asking, but here are my thoughts on this:
You've got .packages in the wrong place. Instead of this:
$.each(msg.packages, function(i, object) {
$.each(object, function(index, value) {
...
You should have written this:
$.each(msg, function(i, object) {
$.each(object.packages, function(index, value) {
...
Better yet, you could just get rid of packages altogether. It's an unnecessary level in the JSON structure.
Also, I don't think jQuery knows that the response is JSON. For this to work, you need either dataType: 'json' in the list of arguments to $.ajax, or something on the server to set the MIME type appropriately.
I'm also concerned about $("#package-form").html(msg);, because msg is not an HTML string.
You should try something like this (Example)
msg = $.parseJSON(msg); // parse JS to object
$.each(msg, function(i, object) {
$.each(object.packages, function(index, value) {
console.log(value);
});
});
Instead of $.each(msg.packages, function(i, object){...}) because msg is an array of objects and in your given example there are three objects right now and each object has a packages item (nested object) which contains id and name.
Update : You can also use, just one loop (Example)
msg = $.parseJSON(msg); // parse JS to object
$.each(msg, function(i, object) {
console.log(object.packages.id);
console.log(object.packages.name);
});
Sorry guys, I threw out my back and couldn't get to my code from home.
Anyways I tried both solutions you provided, and I have been looking at this for a while but neither worked. I have this updated to:
$("#brand").click(function () {
var brand = $(this).attr('rel');
$("#order-form").empty();
var contact_id = $("#contact_id").val();
var dataString = "contact_id=" + contact_id +"&brand=" + brand + "";
//alert("test");
$.ajax({
type: "POST",
url: "/crm/alliance_form.php",
data: dataString,
//dataType: "json",
success: function(msg)
{
//$("#package-form").html(msg);
$.each(msg, function(i, object) {
if(msg.packages) {
$("#package-form").append("<select>");
$.each(object.packages, function(index, value) {
$("#package-form").append('<option value="'+value+'">'+index+'</option>');
});
$("#package-form").append('</select>');
}
});
},
error: function(error)
{
$(".error").html(error);
}
});
});
This just returns nothing not even a blank select box. The $("#package-form").html(msg); is just so I can see the output how the php script is sending it back. The if statement is just to run a verification to see if the array has a nested array with packages in it. I need the return function to do a certain action if it does. Very Important!
As for the dataType: 'json', line in the ajax, it doesn't give me a return value if I have that placed in it. But when I remove it, it will display the array.
Nothing has been changed in the PHP file besides moving the query like suggested.
Ok guys. I got the answer! I have it like this:
$("#brand").click(function () {
$("#order-form").empty();
$("#package-form").empty();
var msg = '[{"packages":{"1":"Land Line"}},{"packages":{"2":"Cellular w\/Alarm.com"}},{"packages":{"3":"Home Automation"}}]';
var newData = JSON.parse(msg);
var newSelect = "<select>";
$.each(newData, function(i, ob) {
$.each(ob.packages, function(index, value) {
newSelect += '<option value="'+index+'">'+value+'</option>';
});
});
newSelect += "</select>";
$("#package-form").append(""+newSelect+"");
});
Here is the fiddle: http://jsfiddle.net/M78vE/

.each() makes the page Freeze

The idea is to fetch the content from an external PHP file on Page load using jQuery .each() function. The problem is the page freezes or keeps on loading and never ends. What would be the issue?
PHP Page
<div class='caller-div-holder'>
<div class='calling-div' id='calling-div-1'></div>
<div class='calling-div' id='calling-div-2'></div>
<div class='calling-div' id='calling-div-3'></div>
</div>
In the .js file
$('.calling-div').each(function()
{
var fetch_id=$(this).attr('data-id');
$.ajax(
{
type: "POST",
url: "page-url",
data: {var1: fetch_id},
dataType:"html",
success: function(data)
{
$('#calling-div-'+fetch_id).html(data);
}
}); // Ajax
}); // Each function
Note:
Instead of $.ajax() on using document.write I found that the function is called for 3 times correctly with the variable fetch_id getting the data properly.
The external PHP page is checked with sample data just changing the POST to GET and passing the data through GET method. It works.
Edit 1:
Adding async:"false", reduces the problem intensity. But still the page is considerably slow.
The following will solve the issue by adding all the html at once, this will be faster than the other method...it will still lock the DOM at the end when it adds the html variable to the html of the parent element.
var html = '';
$('.calling-div').each(function()
{
var fetch_id=$(this).attr('data-id');
$.ajax(
{
type: "POST",
url: "page-url",
data: {var1: fetch_id},
dataType:"html",
success: function(data)
{
html += "<div class='calling-div' id='calling-div-" + fetch_id + "'>" + data + "</div>"
}
}); // Ajax
}); // Each function
$('.caller-div-holder').html(html);
Special Note I highly recommend using the following to solve this problem:
jQuery append() for multiple elements after for loop without flattening to HTML
http://jsperf.com/fn-append-apply

Comparing HTML with Javascript

So I was wondering something.
In a IM/chat website I'm making, I have it check the database every 10 seconds or so to see if any new data has come in. And also, when the user posts a new comment, it automatically sends it to the database and adds it to the comment list without reloading. But it loads all the comments each time.
I was wondering if its possible to add an effect to the new comment (such as fading in) without doing that to all the old comments as well.
function update(){
oldhtml = $('#listposts');
$.ajax({
type: "POST",
data: "",
url: "update.php",
success: function(msg){
$("#listposts").html(msg);
$('.comment_date').each(function(){
$(this).text('[' + prettyDate($(this).text())+']');
if(oldhtml == )
});
}
});
}
var intervalID = window.setInterval(update, 10000);
That's my update code. Here's my post code:
$("#postbutton").click(function () {
if(!$('#post').val()==""){
$.ajax({
type: "POST",
data: "data=" + $("#post").val(),
url: "post.php",
success: function(msg){
$("#listposts").html(msg);
$('.comment_date').each(function(){
$(this).text('[' + prettyDate($(this).text())+']');
});
}
});
$("#post").val("");
}
});
I'm also using prettyDate, as you can see. But that has nothing to do with this problem.
So as the title states, I was gonna try to save the current html in a variable (oldhtml) and then load the new stuff. Then I would compare the two and just use the new comment to fade in. Am I way out there? Am I missing the point?
Oh and please don't down vote me just cause I missed an obvious solution. I thought you're supposed to use it if I don't explain well, which I think I did.
You can do this in your success handler:
var $dv = $('<div />').css('display', 'none').html(msg);
$("#listposts").append($dv);
$dv.fadeIn();
Of course you can use a <span> instead of <div> depending on your needs.
Similar to Blaster's...
$('<div />').html(msg).appendTo('#posts').hide().fadeIn();

ajax and javascript issue - functions not firing or firing mutiple times

I have put together an ajax powered chat/social network with jquery, PHP - but am having problems with the javascript.
I have a js file in the main page which loads the php in a div container, the js file is underneath the div. But only one function for posting a msg seems to work but the others do not.
I have tried including the js file with the dynamically loaded php at the end of the ajax load the functions work fine but am getting mutiple entries of the same message/comment.
I am pretty sure its not the PHP as it seems to work fine with no ajax involvment. Is there a way to solve this?
this is the function that works fine:
$("#newmsgsend").click(function(){
var username = $("#loggedin").html();
var userid = $("#loggedin").attr("uid");
var message = $("#newmsgcontent").val();
if(message == "" || message == "Enter Message..."){
return false;
}
var datastring = 'username=' + username + '&message=' + message + '&uid=' + userid;
//alert(datastring);
$.ajax({
type: "POST",
url: "uploadmsgimage.php",
data: datastring,
success: function(data){
document.newmessage.newmsgcontent.value="";
//need to clear browse value too
$('.msgimage').hide('slow');
$('#addmsgimage').show('slow');
$(".usermsg").html(data);
$("#control").replaceWith('<input type="file" name="file"/>');
$(".msgimage").remove();
}
});
});
And this is one of them that does not work:
//like btn
$(".like").click(function(){
var postid = $(this).attr("pid");
var datastring = 'likeid=' + postid;
$.ajax({
type: "POST",
url: "addlike.php",
data: datastring,
success: function(data){
$(".usermsg").html(data);
}
});
});
From your post, I'm guessing that each message has a "Like" button, but you have 1 main submit button. When messages load dynamically, you have to assign the .like to each one when they come in, otherwise it will only be assigned to the existing messages.
The problem, from what I gather (and this is a guess) would probably be fixed using live so jQuery will automatically assign the click function to all messages including dynamically loaded messages; so instead of:
$(".like").click(function(){
Try this:
$(".like").live('click', function(){
If that doesn't solve the problem, then I'm probably not understanding what it is.

Categories