Reputation: 1
I am using javascript and jquery to send a simple text push notification via parse.com using their rest api. This works :-
$.ajax({
type: 'POST',
headers: {
'X-Parse-Application-Id': "1234567890",
'X-Parse-REST-API-Key': "1234567890"
},
url: "https://api.parse.com/1/push",
data: '{"channel": "","type":"ios","expiration_interval":86400,"data":{"alert":"canned alert","badge" :0,"sound":""}}',
contentType: "application/json"
});
But this does not:-
var my_msg = "canned alert";
$.ajax({
type: 'POST',
headers: {
'X-Parse-Application-Id': "1234567890",
'X-Parse-REST-API-Key': "1234567890"
},
url: "https://api.parse.com/1/push",
data: '{"channel": "","type":"ios","expiration_interval":86400,"data":{"alert":my_msg,"badge" :0,"sound":""}}',
contentType: "application/json"
});
I cannot find a way to replace successfully send an alert with a variable instead of "canned alert". I am not an experienced programmer but even the parse.com tesch support could not explain why; can anyone suggest a solution please?
Upvotes: 0
Views: 4689
Reputation: 28124
Take the my_msg variable out of the single quotes in the second snippet, and it should behave exactly like the first one:
data: '{"channel": "","type":"ios","expiration_interval":86400,"data":{"alert":'+my_msg+',"badge" :0,"sound":""}}',
The way you wrote the second snippet, it looks like you confused a JSON string with an object literal.
Upvotes: 2
Reputation: 193261
You can pass data as an object, no need of any quotes, jQuery will take care of it:
var my_msg = "canned alert";
$.ajax({
type: 'POST',
headers: {
'X-Parse-Application-Id': "1234567890",
'X-Parse-REST-API-Key': "1234567890"
},
url: "https://api.parse.com/1/push",
data: {
channel: "",
type: "ios",
expiration_interval: 86400,
data: {
alert: my_msg,
badge: 0,
sound: ""
}
},
contentType: "application/json"
});
Upvotes: 0
Reputation: 413717
You can use JSON.stringify
to build the JSON from a plain object:
var my_msg = "canned alert";
$.ajax({
type: 'POST',
headers: {'X-Parse-Application-Id':"1234567890",'X-Parse-REST-API-Key':"1234567890"},
url: "https://api.parse.com/1/push",
data: JSON.stringify({
"channel": "",
"type":"ios",
"expiration_interval": 86400,
"data":{
"alert": my_msg,
"badge" :0,
"sound":""
}
}),
contentType: "application/json"
});
Using JSON.stringify
will ensure that any special characters in "my_msg" will be correctly escaped, so that your JSON is guaranteed to be valid.
Upvotes: 0