Handling Facebook response [duplicate] - javascript

This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 10 months ago.
I've got this code to handle Facebook response:
if (response && !response.error_message) {
alert('Posting completed with Post ID:' + response.post_id);
FB.api( '/' + response.post_id, function( response ) {
x$().xhr('<?php echo Yii::app()->createUrl('survey/saveSocialMediaPost', array('answer_id'=>$answer->id, 'social_network'=>1)); ?>', {
method: 'POST',
async: true,
meta: response,
});
console.log( response );
});
} else {
alert('Error while posting.');
}
}
As you can see, after a right post what I want to do is call an ajax to do some actions in my database. The problem here is that I don't know how to handle the response. console.log(response) throws something like that:
Object { created_time: "2016-03-05T01:27:27+0000", message: "Prueba de comentarios.", id: "xxxxxx_xxxxx" }
Exactly what I need to get is message. id is solved with response.post_id.

How about this:
console.log(response.message);
It´s a simple JSON object, you should get familiar with JSON - it´s very important in the JavaScript world.

Related

unable to fetch the JSON Data using jquery in ajax [duplicate]

This question already has answers here:
JavaScript "cannot read property "bar" of undefined [duplicate]
(4 answers)
Closed 4 years ago.
I am unable to fetch the JSON data using jquery in ajax.Getting Uncaught TypeError: Cannot read property 'customers' of undefined error.
<script type="text/javascript">
$("#savechanges").click(function(e) {
e.preventDefault();
jQuery.ajax({
url: "<?=base_url()?>customers/updatecustomerorderdetail",
data: $('#savecustomer input').serialize(),
type: "POST",
dataType: 'json',
beforeSend: function() {
//$("#update_"+id).html('');
$("#savechanges").html('<i class="fa fa-spinner fa-spin"></i>updating...');
},
success:function(data){
var customer_name = data[0].customers[0].customer_name;
alert(customer_name);
console.log(data);
},
error:function (error){
console.log(error);
}
});
});
JSON response from the above code
{
"customers":[
{
"customer_id":22,
"customer_name":"fggfd",
"customer_email":"fggd",
"customer_mobile":"dfgf",
"updated_user_id":"5",
"updated_datetime":"2018-07-30 21:00:57"
}
]
}
I want to alert customer_name from the JSON data in the success function of ajax. can anyone please tell me what I am doing wrong here?
Your data is an object clearly not an array so do this:
data.customers[0].customer_name;

How to pass the ajax get request data to nodejs GET route? [duplicate]

This question already has answers here:
How to get GET (query string) variables in Express.js on Node.js?
(26 answers)
Closed 5 years ago.
This is my ajax request call
$.ajax({
url: '/refresh',
type: 'GET',
contentType: "application/json",
data: {
Name: $("#inputName").val(),
Url: $("#inputUrl").val()
},
success: function(data) {
console.log('form submitted.' + data);
}
});
This is the GET route in nodejs
app.get('/refresh', function(req, res) {
console.log("My data" + JSON.stringify(req.body));
//other operations
}
How can i get the data which is passed from ajax call in my js?? Please help!! Thanks a lot!
jQuery's .ajax() method sends the data property as a query string for GET requests, so in your Express code you have to retrieve that data from req.query instead of from req.body.
You can simply use req.query for that:
const id = req.query._some_query_param; // $_GET["id"]
// Sample URL: https://foo.bar/items?id=234
app.get("/items",function(req,res){
const id = req.query.id;
//further operations to perform
});
If you want to get the route parameters you could use req.params which only gets the route parameters and not the query string parameters.
For example:
// Sample URL: https://foo.bar/items/322
app.get("items/:id",function(req,res){
const id = req.params.id;
//further operations to perform
});

Success callback not firing [duplicate]

This question already has answers here:
JavaScript closure inside loops – simple practical example
(44 answers)
Why are Callbacks from Promise `.then` Methods an Anti-Pattern
(2 answers)
Closed 5 years ago.
Currently I have 2 functions which call some of my API endpoints. They're setup to take a request followed by a success & failure callback functions. I'm trying to call my DeleteTask function from the success callback of my DeleteTaskUser function. However the DeleteTaskUser function is never firing.
I am pretty new to javascript, trying to build this application as a way to learn it so I could be misunderstanding how to use callbacks in javascript.
Any ideas?
The 2 functions:
this.DeleteTaskUser = function(request, success, failure){
AuthService.resHttp({
method: 'DELETE',
resource: 'DeleteAssignments',
params : request
}).then(
function(res) {
success(res)
},
function(res) {
failure(res)
}
);
}
this.DeleteTask = function(request, success, failure){
AuthService.resHttp({
method: 'DELETE',
resource: 'Task',
data : request
}).then(
function(res) {
success(res)
},
function(res) {
failure(res)
}
);
}
I am trying to call the functions as follows:
for(i = 0; i < $scope.tasksList.length; i++){
TaskApi.DeleteTaskUser(
{
id: $scope.tasksList[i].id,
},
//handle success
function(res){
//This function is never firing, despite the above function succeeding.
console.log("After Task User Deletion");
TaskApi.DeleteTask(
{
id: $scope.tasksList[i].id,
},
function(res){},
function(res){}
)
},
//handle failure
function(res){
console.log(res);
}
)
}

Json check if certain element has been received

I have an ajax call to one of my servlets that does some database manipulation. The question I am asking is, is there and easy way to see if I receive a certain element in my json. For example, I am receiving back a { message: "Some data message" } but if there is an error, I want to send back {error: "my error message"}. Is there a simple way to see if there was an error sent?
The logic I am thinking of is like this (this does not work)
$.post( "database.json", { id: id, info: info})
.done(function( data ) {
if(data.error){
alert(data.error);
} else {
alert(data.message);
}
You can check this with
if (data.hasOwnProperty("error")) {
alert(data.error);
} else {
alert(data.message);
}

How to process JSON post response [duplicate]

This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 9 years ago.
I am receiving the following successful response :
{"123abc": {"lat": 101.45, "lon": 777.87},"uid345":{"lat":12.09,"lon":98.08}}
After posting this jquery ajax request :
$.ajax({
url: postUrl,
type: 'POST',
beforeSend: function () {
$.mobile.loading('hide');
},
complete: function () {
$.mobile.loading('hide');
},
crossDomain: true,
data: {
lat: 101.45,
lon: 777.87,
uid: '123abc'
},
dataType: 'json',
success: function (dataString) {
alert(dataString);
},
error: function (error) {}
});
alert(datastring); prints [object object] in a alert window.
How can I process the received response?
p.s: I just completed a udacity web development course and this is new to me.
Use the console to check your response, that way you can expand the object out and what fields are available:
console.log(dataString);
There are a number of options for processing depending on what you want to do. The most used is iterating over your objects keys and displaying the appropriate info via a for in or $.each loop.
To iterate the lat and lon of each object, something like below will work:
for (var key in dataString) {
console.log(dataString[key].lat);
console.log(dataString[key].lon);
}
access properties as datastring.lat Or datastring.[0].lat. You'll get the gist how to access other's
If the later is true,
Do loop on datastring till datastring.length

Categories

Resources