Updating rows in parse with javascript - 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.

Related

Ajax error function not working 2

Basically what I'm trying to do is have a search bar. The user should input the state and city. Once I get the state and city, update the html with the result. The problem is once i enter an invalid state or city, it gives me an error in the console. What i want is an alert telling the user that they have made a mistake in entering the city or state. I tried using a try and catch/ ajax error function but it doesn't seem to work. Need some help thanks !
$(document).ready(function() {
setTimeout(function(){
$('body').addClass('loaded');
$('h1').css('color','#222222');
}, 3000);
var search= $('#search');
var searchsubmit= $('#searchsubmit');
searchsubmit.on('click', function(e){
console.log(search.val());
var searchresult= search.val();
try {
$.ajax({
url:"http://api.wunderground.com/api/69e8e728a8f8536f/geolookup/conditions/q/"+ searchresult +"/Cedar_Rapids.json",
dataType : "jsonp",
success : function(parsed_json) {
var location = parsed_json['location']['city'];
var temp_f = parsed_json['current_observation']['temp_f'];
alert("Current temperature in " + location + " is: " + temp_f);
}
});
}catch(err){
alert(err.message);
}
});
});
I think that adding the error callback should work, here is a jsbin:
https://jsbin.com/ciwosoqeye/edit?html,js,output
var searchresult = '';
$.ajax({
url:"http://api.wunderground.com/api/69e8e728a8f8536f/geolookup/conditions/q/" +
searchresult +"/Cedar_Rapids.json",
dataType : "jsonp",
success : function(parsed_json) {
var location = parsed_json['location']['city'];
var temp_f = parsed_json['current_observation']['temp_f'];
alert("Current temperature in " + location + " is: " + temp_f);
},
error: function(jqxhr, errorString, ex) {
alert(ex);
}
});
as defined in the doc
Without knowing what error message you are getting or what parsed_json looks like with a bad request, this is only a guess but parsed_json probably doesn't have a location property and/or a city property when bad data is passed in. I'm guessing that is causing the error. If this is the case, you can check for the existence of parsed_json.location and parsed_json.location.city before trying to access them and display the error if they don't exist.
$(document).ready(function() {
setTimeout(function() {
$('body').addClass('loaded');
$('h1').css('color','#222222');
}, 3000);
var search = $('#search');
var searchsubmit = $('#searchsubmit');
searchsubmit.on('click', function(e){
console.log(search.val());
var searchresult= search.val();
$.ajax({
url:"http://api.wunderground.com/api/69e8e728a8f8536f/geolookup/conditions/q/"+ searchresult +"/Cedar_Rapids.json",
dataType : "jsonp",
success : function(parsed_json) {
if (parsed_json.location && parsed_json.location.city) {
var location = parsed_json.location.city;
var temp_f = parsed_json.current_observation.temp_f;
alert("Current temperature in " + location + " is: " + temp_f);
} else {
alert(err.message);
}
}
});
});
});
Setting a break-point at the beginning of the success callback and inspecting parsed_data would help in debugging this sort of thing.

jQuery.inArray not working?

So I'm using an ajax call to retrieve a user's messages. Then cross referencing them with existing messages by creating an array of their id's. I have two messages that already exists with ID of 157 and 159. Both messages are being correctly listed in the array but when I use jQuery.inArray it only seems to be able to find one of them.
function checkForNewMessages() {
$CurrentMessages = [];
$('.Message').each(function () {
$CurrentMessages.push($(this).attr('message-id'));
});
console.log('Messages found');
console.log($CurrentMessages);
console.log('Getting Messages');
$.ajax({url: "<?php echo $GLOBALS['SubDirectory']; ?>api/get/messenger/messagesfromfeed?feed_id=" + urlget('ID'), success: function(result){
$Result = decodeURI_array(JSON.parse(result));
$.each($Result, function(index) {
if(!jQuery.inArray($Result[index]['ID'], $CurrentMessages)) {
console.log("New Message, ID of '" + $Result[index]['ID'] + "'");
} else {
console.log("Old Message, ID of '" + $Result[index]['ID'] + "'");
}
});
}});
}
console result
Messages found
["157", "159"]
Getting Messages
New Message, ID of '157'
Message, ID of '159'
URI decoded JSON
[{"ID":"157","CompanyID":"13","Receiver":"13","Sender":"","Message":"test line 1\r\n& test line 2\r\n\r\n","VirtualAttachments":"[{\"Type\":\"Client\",\"ID\":\"128\",\"DisplayName\":\"\"},{\"Type\":\"Quote\",\"ID\":\"20\",\"DisplayName\":\"\"}]","FileAttachments":"[{\"Name\":\"IMG_1300.JPG\",\"Location\":\"\"}]","FeedID":"23","Seen":"TRUE","CreatedOn":"1474635298"},{"ID":"159","CompanyID":"13","Receiver":"13","Sender":"15","Message":"reply test\r\n","VirtualAttachments":"[]","FileAttachments":"[]","FeedID":"23","Seen":"TRUE","CreatedOn":"1474635960"}]

ajax postback method for refreshing dropdown list

Scoop...
I have a drop down list that might not display a particular option you're looking for. I added a button with pop up modal to type in a field you want to add to the drop down list. It functions perfectly, but I need to add an ajax postback method to refresh the list after the user hits enter. I don't want to refresh the whole page, just the list. any help?
Controller:
public ActionResult AddLeadSource()
{
return View();
}
[HttpPost]
public ActionResult AddLeadSource(string name)
{
LeadSource ls = new LeadSource();
ls.Name = name;
db.LeadSources.Add(ls);
db.SaveChanges();
return Json(new { success = true });
}
JS
<script>
$("#AddNew").change(function () {
var name = $("#Name").val();
// var order = $("#DisplayOrder").val();
$.ajax({
type: 'POST',
dataType: 'json',
cache: false,
url: '/Admin/LeadSource/AddLeadSource',
data: { name: name },
success: function (response) {
//alert("Success " + response.success);
$('#FollowUpNotes').kendoWindow('destroy');
// Refresh the DropDown <-- Heres where I need some help!
},
error: function (jqXHR, textStatus, errorThrown) {
alert('Error - ' + errorThrown);
}
});
});
In your success function of your Ajax call add this:
$("IdOfDropDownList").data("kendoDropDownList").dataSource.read();
In this way your dropdownlist will call the read function and reload all data. I assumed that your dropdownlist is binding throught read call.
I highly recommend looking at jQuery UI's autocomplete widget. That said,
$('#YourDropDownID option').remove(); //this will remove all option elements inside the <select id="YourDropDownID">
Then you just need to build new ones based on the response data,
for (var o in data) {
if (data[o].Value != undefined) {
$('#YourDropDownID').append('<option value="' + data[o].Value + '">' + ("" + data[o].Display) + '</option>');
}
}
I do this inside the .done() callback of my AJAX:
.done(function (data) {
//above code
}
Depending on the nature of the data you are sending back you may need to loop through it differently. Mine is an array of objects with a Value and Display properties (in my case, account numbers and account names).
//server side controller
var query = #"
Select
SubString([mn_no], 0, 6) As Value,
RTRIM([acct_desc]) As Display
From [some_table]";
return con.Query(query, new { AccountNumber = accounts.Select(x =>
{
return new { Value = x.Value, Display = x.Display };
});

How to add dynamic a javascript variable in jquery?

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);
});
});

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

Categories

Resources