How to add dynamic a javascript variable in jquery? - javascript

I add variable length list in a view with jquery.
$("#addItemday").click(function() {
$.get("/Course/AddDayNewRow", function(data) {
$("#DayEditorRows").append(data);
}).fail(function(xhr, err) {
alert("readyState: " + xhr.readyState + "\nstatus: " + xhr.status);
alert("responseText: " + xhr.responseText);
});
});
for every partialview, set a index value.for example
<input name="Days.index" autocomplete="off" value="96633b1d-9c0c-4760-9ca8-474ac28bd52a" type="hidden">
I want to add a script for every partialview.
var objCal1 = new AMIB.persianCalendar("objCal1", "dateid");
After append PartialView, i want to get last item added.
$("input[id*='Date']").last(function () {
var ??? = new AMIB.persianCalendar(???, $(this).attr('id'));});
How do i get last item addes, and set name for this variable?

Two questions, two answer:
1) To get the id of the last item that you added:
var last_id = $("input").last().attr("id");
Remember that you have to wait for your AJAX call to return before firing that, so add it within your AJAX function.
2) Name the variable whatever you like.
Here's an example of the total code:
$("#addItemday").click(function() {
$.get("/Course/AddDayNewRow", function(data) {
$("#DayEditorRows").append(data);
var last_id = $("input").last().attr("id");
var amib_var = new AMIB.persianCalendar(last_id);
// DO SOMETHING WITH THE AMIB_VAR
}).fail(function(xhr, err) {
alert("readyState: " + xhr.readyState + "\nstatus: " + xhr.status);
alert("responseText: " + xhr.responseText);
});
});

Related

Updating rows in parse with javascript

I'm trying to update a specific field in a row in my parse table when clicking a button. The button gets the object id, and it sets an alert with the object id just to make sure we get the right objectId, but the updating line doesn't seem to work. Any ideas?
button.onclick = function () {
var MyItems = Parse.Object.extend("MyItems");
var query = new Parse.Query(MyItems);
query.equalTo("objectId", this.id);
query.first({
success: function(object) {
alert(object.get('objectId'));
object.set("status", "ok");
object.save();
},
error: function(error) {
alert("Error: " + error.code + " " + error.message);
}
});
}
Solved!
ACl was not set to write.
Changed it to public write and everything works out fine.

TypeError: a is undefined in jquery at the first line?

So, in my code, when I press my #jsonclick button, it activates my script which populates a table with information from a JSON page. The problem I am having is that I am getting a TypeError: a is undefined, and I have no idea why.
Here is my code:
jQuery function
$("#clickjson").click(function () {
$.getJSON("gmessagegroup.php?gid=" + $('#gbox').val(), function (data) {
$.each(data.messages, function (key, val) {
if (data.messages[key].clientmessageid != undefined) {
console.log(data.messages[key].clientmessageid + ":" + data.messages[key].from + " - " + data.messages[key].content);
$("#messages tbody tr:last").after('<tr><td>' + data.messages[key].clientmessageid + '</td><td>' + escapeHtml(data.messages[key].from).replace("https://bn1-client-s.gateway.messenger.live.com/v1/users/ME/contacts/8:", "") + '</td><td id=' + data.messages[key].clientmessageid + ' contenteditable="true">' + escapeHtml(data.messages[key].content) + '</td></tr>');
}
});
});
setTimeout(function () {
var message_status = $("#status");
$("td[contenteditable=true]").blur(function () {
var field_userid = $(this).attr("id");
var value = $(this).text();
$.post('groupedit.php', field_userid + "=" + value, function (data) {});
});
}, 1000);
});
The code is getting the value of the selected item in a dropdown select. I tried putting and alert in and it is putting out the correct value that is being pushed out to the PHP. I am unsure of where the TypeError comes into play, all I know is that when I remove ?gid=" + $('#gbox').val() from the end of the php, the error goes away. Problem is, I need that for the php to work. Can somebody please tell me why this is happening?
Thanks.
Actually in your json response messages is not found thats why it is responding as a is undefined check if you json data has messages or not like,
if(data && data.messages.length) // check for messages
$.each(data.messages, function (key, val) {
if (data.messages[key].clientmessageid != undefined) {
...
}
});
}
Snapshop

jQuery temporary alert messages

Im trying to create some sort of temporary alert messages using jQuery so a alert message appears (a div with some style and a message ) and then after X seconds dissapear.
If the user clicks again the alert will appear again...
Currently my script is not even removing the alerts. Removing the temp_alert_X name to temp_alert will make them dissapear after X seconds but then if the user clicks again on the button the alert wont come out again until refresh..
function createFarm(){
$.ajax({
url: "ajax/new_farm.php",
context: document.body
}).done(function(data) {
data = jQuery.parseJSON(data);
if(data.error == 1){
$('.sidebar_frame').append("<p><div id='alert_error' class='temp_alert_" + new_farm_error + "'> " + data.log + "</div></p>")
setTimeout(function() {
$('.temp_alert_' + new_farm_error + '').remove()
}, 200)
new_farm_error++;
}else{}
}).fail(function() {
alert( "Error while creating new farm 404." );
});
}
Note:
new_Farm_error = 0
Try to change these lines:
$('.sidebar_frame').append("<p><div id='alert_error' class='temp_alert_" + new_farm_error + "'> " + data.log + "</div></p>")
setTimeout(function() {
$('.temp_alert_' + new_farm_error + '').remove()
}, 200)
with, these:
var $errorMsg = $("<p><div id='alert_error' class='temp_alert_" + new_farm_error + "'> " + data.log + "</div></p>");
$('.sidebar_frame').append($errorMsg);
setTimeout(function() {
$errorMsg.remove();
}, 200)
note. 200 millisecond is a very short time.
You don't need to parse JSON if you use dataType : "json"
$.ajax({
dataType : "json"
//...
});

JavaScript .load does not show correct page results after .click

The below code allows the user to click as button and reject a friend request. Even though multiple results are shown on a page, it functions correctly as it uses wrapper.children('.decline').click(function() { to target the correct result.
After this happens the following $( "#containerFriends" ).load("friends.html #containerFriends" ); should refresh the page so that the latest results are displayed. However a completely blank page is shown, even when results should still exist. If I manually refresh the page, the correct results are shown.
I'm not sure what is wrong with the below and what is causing such an issue?
mainQuery.find({
success: function(results) {
var friends = [];
for (var i = 0; i < results.length; i++) {
friends.push({
imageURL: results[i].get('toUser').get('pic'),
username: results[i].get('toUser').get('username'),
userId: results[i].get('toUser').id,
status: results[i].get('status'),
// Saves the object so that it can be used below to change the status//
fetchedObject: results[i]
});
}
var select = document.getElementById("FriendsConnected");
$.each(friends, function(i, v) {
var opt = v.username;
var el = document.createElement("option");
el.textContent = opt;
el.value = opt;
select.appendChild(el);
})
$('#containerFriends').empty();
$('#containerFriendsConnected').empty();
_.each(friends, function(item) {
var wrapper = $('<div class="portfolio-item-thumb one-third"></div>');
wrapper.append('<img class="responsive-image friendImgOutline" src="' + item.imageURL + '" />' + '<br>');
wrapper.append('<div class="tag">' + item.username + '</div>');
wrapper.append('<div type="button" class="btn btn-danger mrs decline">' + 'Unfriend' + '</div>');
$('#containerFriends').append(wrapper);
//The following lets the user accept or decline a friend request by changing the status the status from Pending to Declined/////
wrapper.children('.decline').click(function() {
$(".decline").click(function() {
item.fetchedObject.set("status", "Rejected");
$( "#containerFriends" ).load("friends.html #containerFriends" );
item.fetchedObject.save(null, {
success: function(results) {
console.log("REJECTED");
},
error: function(contact, error) {
// The save failed.
// error is a Parse.Error with an error code and description.
alert("Error: " + error.code + " " + error.message);
}
});
});
});
});
},
error: function(error) {
alert("Error: " + error.code + " " + error.message);
}
});
I actually resolved this by calling the function again, this then ensured the data was upto date and refreshed the page. I believe the issue was that $('#containerFriends').append(wrapper); did'nt contain the updated data after the user .click

converting Parse.com object to string

What I have is when a user enters a name into a textbox and clicks a button, the value in the textbox is saved to the Parse database.
What iI'm trying to do is get the name that was added and add it to a div.
On this Live Example, it's basically what I want, except it alerts [object Object] and not thomas in this case.
You need to use the specific part of the result you need. In your case, replace
query.first({
success: function (results) {
alert("Successfully retrieved " + results + " ");
divTag.innerHTML = results.toString();
},
error: function (error) {
alert("Error: " + error.code + " " + error.message);
}
});
with
query.first({
success: function (results) {
alert("Successfully retrieved " + results.attributes.FirstName + " ");
divTag.innerHTML = results.attributes.FirstName.toString();
},
error: function (error) {
alert("Error: " + error.code + " " + error.message);
}
});
Use this:
alert("Successfully retrieved " + results.get("FirstName") + " ");

Categories

Resources