Object handling in Chrome/FF? - javascript

I have this code:
$('.gBook').click(function(){
var values = [];
var getDiff = $('#totalPrice').attr("data-value");
var i = 0;
$('td[data-check="true"]').each(function(){
var valueToPush = { };
valueToPush["price"] = $(this).attr("data-price");
valueToPush["id"] = $(this).attr("data-id");
valueToPush["diff"] = getDiff;
values.push(valueToPush);
i++;
});
var arrayToSend = {values};
$.post( '<?php echo PATH;?>ajax/updateRoom.php',arrayToSend, function(data){
if(data != "ERROR"){
$('#all-content').html(data).css("overflow-y","auto");
}else{
alert("ERROR");
}
});
});
In Chrome, this line gives an error var arrayToSend = {values}; (Uncaught SyntaxError: Unexpected token }) In Firefox everything is fine.
I guess it's because of the rather "loose" error handling of FF, but how am I doing it correctly?
I tried to initialize the object with var arrayToSend = new Object(); before the $.each, but that gives an empty array after POST.
Where is my mistake?

try this
var arrayToSend = {optionsChosen:values};
Then in php or whatever you use for data handling look for the POST variable optionsChosen.
What you did was try to make an Object with parameter array = nothing
You basically did this in your code. It doesn't take an expert to see whats wrong with this statement.
arrayToSend = new function() {
this.(new Array(1,2,3)); // This is cringeworthy if you see it like this.
}
In the example I gave it translates to this:
arrayToSend = new function() {
this.optionsChosen = new Array(1,2,3);
}

Related

Parse Cloud code query.withinKilometers

(Edit 1)
I'm trying to work with the cloud code and GeoPoint. With the function "query.withinKilometers" I have a pointer to the Location Class but when I try to call the function I get the error "invalid key name". What is the right way to do this? I could not find anything in the documentation, here is a file of the cloud function.
Error: "code":105,"message":"Invalid key name: [object Object]"
here de documentation: http://parseplatform.org/Parse-SDK-JS/api/v1.11.1/Parse.html
Parse.Cloud.define("getCloseFindings", function(request, response){
var query = new Parse.Query("findings");
var locQuery = query.include("location");
var LocQuery = locQuery.get("geoLocation");
var Loc_Lat = request.params.Latitude;
var Loc_Long = request.params.Longitude;
var UserLocation = new Parse.GeoPoint(Loc_Lat,Loc_Long);
var RadiusLocation = request.params.Radius;
query.equalTo("isDeleted", false);
query.withinKilometers(locQuery, UserLocation, 100);
query.find({
success: function(results){
if(results === undefined){
var response_jsonArr = {
code : 404,
message : "Not Found"
};
response.success(response_jsonArr);
}else{
var jsonArr = [];
for ( var i = 0; i < results.length; ++i ) {
var finding_location = results[i].get("location");
jsonArr.push({
name: results
});
}
response.success(jsonArr);
}
}, error: function(error){
response.error(error);
}
});
You are passing an object to query.withinKilometers as the first parameter when you should be passing a String. Try using the key from your query.include call instead, like this:
query.withinKilometers("location", userLocation, 100);

Parse : Retrieving properties from an object that is related

So I am doing a query to bring back a list of records, these records have a link to the user that created the record. The link is to the object.
My query gets me the object but I cant then access the fields of that object (except of course ID)
query.equalTo("search", search);
query.include("user");
query.find({
success: function(Report) {
for (var i = 0; i < Report.length; i++) {
var test = Report[i].id;
query.get(test, {
success: function(result) {
var reportDescription = result.get("reportDescription");
var reportPicture = result.get("reportPicture");
var reportPosition = result.get("reportPosition");
var reportType = result.get("reportType");
var reportDate = result.get("createdAt").toLocaleString();
var reportSearchId = result.get("search").id;
var user = result.get("user")
console.log(user)
var reportSearchBy = user.username;
},
error: function(result, error) {
alert(error.message);
}
});
};
},
error: function(error) {
alert(error.message);
}
});
What am I doing wrong?
i tried to run similar code to what you did. when i tried to access with dot notation i get undefined but when i tried to get it with .get("fieldName") it works..
here is my code:
var FileTest = Parse.Object.extend("FileTest");
var query = new Parse.Query(FileTest);
query.include("user");
query.find().then(function(results){
var lastItem = results[results.length - 1];
if (lastItem){
var user = lastItem.get("user");
console.log(user.get("username"));
}
},function(error){
});
please notice that i also use Promise for better coding and in order to get the username i did lastItem.get("username")
so please try to replace user.username with user.get("username")
and see if it works.

Error While Updating parse.com Parse Object

We wrote the parse cloud function to update the object .
Until today morning it was working fine. Now our cloud code is not working . can you please check this ?
Below is our code to update the object which is throwing error
var point = new query(); for this line we are getting error like
TypeError: undefined is not a function
below is our full code
var query = Parse.Object.extend("Merchants");
var point = new query();
point.id = request.params.id;
point.set("keyfield1",request.params.keyfield1);
point.set("keyfield2",request.params.keyfield2);
point.set("keyfield3",request.params.keyfield3);
point.set("keyfield4",request.params.keyfield4);
point.set("keyfield5",request.params.keyfield5);
point.save(null,{
success:function(response)
{
var resp={};
resp.ResponseCode = "1000";
resp.data = response;
response.success(resp);
},
error:function(response)
{
response.error(response.status);
}
});
Can you please help us with this issue.
Try this:
var Merchants = Parse.Object.extend("Merchants");
var merchantQuery = new Parse.Query(Merchants);
merchantQuery.equalTo("<someKey>", <someVal>);
merchantQuery.find().then(...);
Hope it helps

Passing array from php to javascript through ajax response

This is my first post in stackoverflow. I have always got my answers from previously posted questions. This problem has been bugging me and all the solutions I tried have not worked.
I have a js function which makes an ajax request to get weather info of town passed:
var _getWeatherInfo = function(ntown){
var town = ntown;
var url = "PHP/weather.php?town=" + town;
request1.onreadystatechange = _refreshWeatherList();
request1.open("GET", url, true);
request1.send("");
}
I am using the following php code to return the sql results stored in array:
<?php
//Connection to the database
$mysql = mysql_connect("localhost","xuvaz","x");
//Selecting Database
$db = mysql_select_db("weather");
$town = $_GET['town'];
$tarray = array();
$sql1= mysql_query("SELECT * FROM weather WHERE town='$town'");
while($row = mysql_fetch_assoc($sql1)) {
$tarray = array('town' => $row['town'],'outlook' => $row['outlook']);
}
echo json_encode($tarray);
?>
Then I have a function that is called when the request is completed:
var _refreshWeatherList = function() {
var weather_info = request1.responseText;
for(var i = 0; i < weather_info.length; i++){
var wtown = weather_info[i].town;
var woutlook = weather_info[i].outlook;
var wmin = weather_info[i].min_temp;
var wmax = weather_info[i].max_temp;
}
var wLine = new WLine(wtown, woutlook, wmin, wmax);
_weather.push(wLine);
_refreshWeatherDisplay();
}
The problem is I cant access the array values.
I can see the values as {"town":"Christchurch","outlook":"fine"} in firebug under response.
Even when I use JSON parse it gives error in the firebug , JSON.parse: unexpected end of data. If
I can just access the data my whole project would be completed.
Your PHP code is returning an object (last row from your loop) rather than an array of objects, but your JavaScript is expecting an array.
Change your PHP to the following to appand to $tarray:
while($row = mysql_fetch_assoc($sql1)) {
$tarray[] = array('town' => $row['town'],'outlook' => $row['outlook']);
}
Your JavaScript needs to wait for readyState = Loaded and JSON-decode the responseText:
var _refreshWeatherList = function() {
if(request1.readyState == 4) {
var weather_info = JSON.parse(request1.responseText);
....
}
}
If the parse is failing, trying logging it to the console to make sure the PHP isn't returning extra characters.
var _refreshWeatherList = function() {
var weather_info = eval("("+request1.responseText+")");
for(var i = 0; i < weather_info.length; i++){
var wtown = weather_info[i].town;
var woutlook = weather_info[i].outlook;
var wmin = weather_info[i].min_temp;
var wmax = weather_info[i].max_temp;
}
var wLine = new WLine(wtown, woutlook, wmin, wmax);
_weather.push(wLine);
_refreshWeatherDisplay();}
'request1.responseText' must be 'object' use eval() --! my english not well
Thank you for all your help. I found the fault. I forgot to include these two lines.
if (request1.readyState == 4) {
if (request1.status == 200){

Cannot access children of JSON object

I have a JSON object musicianobj, an example of which I have pasted below:
{
id: "451026389391"
name: "John Frusciante"
type: "profile"
url: "http://open.spotify.com/artist/XXXXXXXXXXXXXX"
}
I got this from the Facebook API using the Javascript SDK. I can run console.log(musicianobj); which successfully prints the object to the log in Chrome, but console.log(musicianobj.name);, console.log(musicianobj[1]);, and console.log(musicianobj["name"]); all return undefined for no apparent reason. Any ideas?
Edit: code below.
var playFriendsTrack = function(friend){
FB.api("/"+friend+"/music.listens", function(data) {
var songname = data.data[0].data.song.title;
var artistname = "";
FB.api(data.data[0].data.song.id,function(trackdata){
var musicianobj = trackdata.data.musician;
console.log(musicianobj);
console.log(musicianobj["name"]); // Doesn't work
console.log(musicianobj.name); // Doesn't work
artistname = musicianobj[1]; // Doesn't work
});
if(artistname.length <= 0){
alert("Error! Please try another friend.")
}
}
);}
Have you decoded it? It seems it is still a string.
musicianobj = JSON.parse(musicianobj);
console.log(musicianobj.name); // Now this should work
Got it working! I had to put a [0] after musicianobj. Apparently I don't know JSON as much as I'd like to. The working code is pasted below:
var playFriendsTrack = function(friend){
FB.api("/"+friend+"/music.listens", function(data) {
var songname = data.data[0].data.song.title;
var artistname = "";
FB.api(data.data[0].data.song.id,function(trackdata){
var musicianobj = trackdata.data.musician;
console.log(musicianobj);
console.log(musicianobj[0]["name"]);
console.log(musicianobj[0].name);
artistname = musicianobj[0].name;
});
if(artistname.length <= 0){
alert("Error! Please try another friend.")
}
}
);}

Categories

Resources