Jquery returns [Object object] from POST function - javascript

i want to get a string from a php file, using a jquery post.
function getString(string) {
return $.ajax({
type : 'POST',
url : 'scripts/getstring.php',
data : { 'string': string }
});
};
in the firebug console i can see that the desired string is found, but if i want to get it with
var blub = getString("test");
alert(blub);
only "object Object" is shown.
just cant get where my mistake is..

That Ajax request that is made to the server is performed asynchronously, so the ajax method actually returns an object representing the request itself, rather than the actual response from the server.
The jQuery XMLHttpRequest (jqXHR) object returned by $.ajax() as of jQuery 1.5 is a superset of the browser's native XMLHttpRequest object.
You could use the success callback instead:
function getString(string) {
return $.ajax({
type : 'POST',
url : 'scripts/getstring.php',
data : { 'string': string }
success: function(result) {
alert(result);
},
});
};
Or if you want to be a bit more flexible, you could take the callback function as a parameter:
function getString(string, callback) {
return $.ajax({
type : 'POST',
url : 'scripts/getstring.php',
data : { 'string': string }
success: callback,
});
};
getString('test', function(result) {
alert(result);
})

You are returning an jQuery jqXHR object.
If you want to deal with the data from the HTTP response, then you need to add a done (or success handler.
blub.done(function (data) {
alert(data);
});

object Object is the expected response, because the data being returned is and object.
If you want to see the resultant object, try:
console.log(blub) instead and view it in the console.
This can then help you determine the correct path to the data you want to retrieve in the object.

Related

Variable lost in ajax request

I'm facing a strange behaviour when trying to pass a variable as parameter to a nested ajax request callback:
$('form').on('submit',function(e){
$.ajaxSetup({
header:$('meta[name="_token"]').attr('content')
})
e.preventDefault(e);
$.ajax({
type:"POST",
url:dest_url,
data:$(this).serialize(),
dataType: 'json',
success: function(data){
if($.isEmptyObject(data.error)){
// performing some actions
// at this point, data.id contains my id
// We call an other function,
// which performs an other ajax request,
// with data.id as parameter
listRefresh(data.id);
}else{
// error message
}
},
error: function(data){
// error message
}
})
});
function listRefresh(id){
console.log(id); // At this point, id contains my id
$.ajaxSetup({
header:$('meta[name="_token"]').attr('content')
})
var src_url = location.href + '?id='+id;
$.ajax({
url: location.href,
type: 'GET',
cache: false
})
.done(function(id) {
console.log(id);
// At this point the console outputs
// all my html code in place of id
// I tried to pass data, response, id, but still the same issue
})
.fail(function() {
//error message
});
}
As said in code comments above, in the listRefresh ajax done callback, my variable seems to disapear and the console.log outputs my entire html code in the console...
I've never seen something like this. Do you have an explanation of why, and how could I pass my id as parameter to the ajax callback ?
The first argument passed to the function in done is the response from the AJAX request. It doesn't matter what you call the variable, that's what will be passed to that function.
You can capture the value in the closure however, simply give it another name and assign it to a local variable. Something like this:
done(function(response) {
var theId = id;
// "response" contains the response from the server.
// "theId" contains the value of `id` from outside this function.
})
The parameter of the .done() method is the response of the AJAX call. If your call returned a HTML page, the id variable got all of the html string assigned to it.
To keep the id in its variable simply use another one like:
.done(function(data) {
console.log(data)
console.log(id);
});

Print JSON string from URL

I'm using ajax to parse JSON data from a URL. I need to capture the parsed array into a variable. How would I go about this? Thanks
function rvOffices() {
$.ajax({
url:'https://api.greenhouse.io/v1/boards/roivantsciences/offices',
type:'GET',
data: JSON.stringify(data),
dataType: 'text',
success: function( data) {
// get string
}
});
}
rvOffices();
var rvOfficesString = // resultant string
You can use JSON.parse(data) to convert the desired output to JSON, and then access the objects and array indexes from within that with .object and [array_index] respectively:
function rvOffices() {
$.ajax({
url: 'https://api.greenhouse.io/v1/boards/roivantsciences/offices',
type: 'GET',
dataType: 'text',
success: function(data) {
var json_result = JSON.parse(data);
//console.log(json_result); // The whole JSON
console.log(json_result.offices[0].name);
}
});
}
rvOffices();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
You also don't need to pass any data, as you're performing a GET request.
Hope this helps! :)
So I guess you are not sure about the ajax call, so lets break it..
Ajax call is a simply method to make a request to remote resource (Get/post/put...) the type of request (GET/POST) depends upon your need.
so if you have an endpoint that return simply data as in your case a simple get/post request is sufficient.
You can send addition data with request to get the data from endpoint (say id of resource (say person) whose other fields you want to get like name, age, address).
here is link for ajax request in jQuery
here is jQuery parse json parse json in jQuery
So for example:
// let's say when you call this function it will make post request to fixed end point and return data else null
function rvOffices() {
var res = null; // let be default null
$.ajax({
url:'https://api.greenhouse.io/v1/boards/roivantsciences/offices',
type:'GET', // type of request method
dataType: 'text', // type of data you want to send if any.
success: function( data) {
res = $.parseJSON(data); // will do the parsing of data returned if ajax succeeds (assuming your endpoint will return JSON data.)
}
});
return res;
}
// lets call the function
var rvOfficesString = rvOffices();
// print the value returned
console.log(rvOfficesString);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
You can try something like: -
$.ajax({
url:'https://api.greenhouse.io/v1/boards/roivantsciences/offices',
type:'GET',
dataType: 'text',
success: function(response) {
// get string
window.temp = JSON.parse(response);
}
});

AJAX request in ColdFusion

How can I do a AJAX request in ColdFusion?
I have my javascript:
function getdata(){
var formElements=document.getElementById("CFForm_1").elements;
var data=[];
for (var i=0; i<formElements.length; i++){
if(formElements[i].name == 'customersid')
data.push({'customersid':document.getElementById("customersid").value});
if(formElements[i].name == 'customerstoid')
data.push({'customerstoid':document.getElementById("customerstoid").value});
}
$.ajax(
{
type: "get",
url: "components/BillingCalc.cfc",
data: {
method:"ajaxGetTotalCost",
data: data.join()
},
dataType: "json",
success: function( objResponse ){
}
});
}
My component:
component displayName="Calc" {
remote function ajaxGetTotalCost(data){
data = deserializeJSON(arguments.data);
WriteDump(data); abort;
}
I am getting the error: JSON parsing failure at character 2:'o' in [object Object],[object Object]
Does anyone knows how to do AJAX request in CF?
This function:
remote function ajaxGetTotalCost(data){
data = deserializeJSON(arguments.data);
WriteDump(data); abort;
}
is not complete. It's at the stage where you have to call it from a ColdFusion page, not with javascript. That will enable you to see the results of the writedump(data) command to ensure it's what you expect. You have to add more code to the function to get it to produce a variable javascript can receive, and then return that variable to whatever is calling the function.
The issue is related to dataType attribute you are passing with $.ajax() method. dataType: "json" indicates your AJAX request is expecting JSON data as a response. But in your case you are simply returning DUMP of the deserialized JSON, which is HTML not JSON. So if you want it to work properly, then you need to return JSON data from your ColdFusion function. You can try this and see if it works.
remote function ajaxGetTotalCost(data){
data = deserializeJSON(arguments.data);
return serializeJSON(data));
}

How to bind variable to jquery ajax request?

This is self-explanatory:
while (...) {
var string='something that changes for each ajax request.';
$.ajax({'type': 'GET','dataType': 'json', 'url': 'get_data.php'}).done(processData);
}
function processData(data) {
// get string into here somehow.
}
As you can see, I need to get string into processData somehow. I can't make a global variable because string is different for every ajax request. So, the question is, how do I bind string to my ajax request so that I can access it from processData?
I really don't want to have to append string to the query and have the server return it, but if this is my only option, I have no choice.
Thanks in advance.
try in this way:
while (...) {
var str = 'something that changes for each ajax request.';
(function(_str) {
$.ajax({'type': 'GET','dataType': 'json', 'url': 'get_data.php'})
.done(function(data) {
processData(data, _str);
});
}(str));
}
function processData(data, str) {
console.log(data, str);
}
and no global variables were used :)
var string='something that changes for each ajax request.';
// Use a closure to make sure the string value is the right one.
(function() {
// Store the "string" context
var that = this;
$.ajax({
'type': 'GET',
'dataType': 'json',
'url': 'get_data.php'
}).done(
$.proxy( processData, that )
);
}(string));
function processData( data ) {
this.string === 'something that changes for each ajax request.' // true
}
$.proxy is the jQuery version (cross-browser) of .bind().
You could add an argument as #Joel suggested (in his deleted answer), but the less arguments the better.
$(document).bind("ajaxSend",function(){
$("#ajax_preloader").show();
}).bind("ajaxComplete",function(){
$("#ajax_preloader").hide();
});

jQuery - Difference between replaceWith making ajax call or vice versa

Suppose I want to make an ajax call to the server and use the response to replace a section of existing document content. Would there be any reason to choose one of these methods over the other?
Option 1 - make the ajax call, and perform the replaceWith from the error/success functions. Example:
$.ajax({
type : 'GET',
url : '/some/path/here',
success : function(data) {
// process data here
$('#container').replaceWith(processedData);
}
});
Option 2 - call replaceWith, passing in a function that makes the ajax call. Example:
$("#container").replaceWith(function(){
var responseData;
$.ajax({
type : 'GET',
url : '/some/path/here',
success : function(data) {
// process data here
responseData = processedData; //
}
});
return responseData;
});
Second one is not an option. When you take the function out;
function(){
var responseData;
$.ajax({
type : 'GET',
url : '/some/path/here',
success : function(data) {
// process data here
responseData = processedData; //
}
});
return responseData;
}
This will return undefined. Cause, when the time function runs and returns, reponseData is undefined. Only, sometime in future, success function executes and sets responseData. However, your replaceWith code has already finished executing.
Go with option 1.
Option 1 is your only choice, as option 2 would not work as the call would execute asynchronously. This means your function would never return anything.
If you are looking to externalise the processing of the data returned from your AJAX call, just set the success parameter as a reference to the function you want to execute:
$.ajax({
type: 'GET',
url: '/some/path/here',
success: processData
});
function processData(data) {
// process data here
$('#container').replaceWith(data);
}

Categories

Resources