AJAX request in ColdFusion - javascript

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

Related

Passing data from javascript to PHP via POST not working

Im trying to send an array, populated using javascript on client-side, to a php file in the backend.
MAIN.JS
var list = iterateItems();
_ajax("https://127.0.0.1/prog1/final/class/ticket.php", list)
.done(function(list){});
});
function _ajax(url,data) {
var ajax = $.ajax({
type : "POST",
datatype : "string",
url : url,
data : data
})
return ajax;
}
function iterateItems() {
// array is an array populated in this function, returned to be sent to ticket.php
return JSON.stringify( array );
};
TICKET.PHP
<?php
var_dump(json_decode($_POST['list']));
?>
And executing this, I'm getting this result:
Notice: Undefined index: list in D:\127.0.0.1/prog1/final/class/ticket.php on line 2
NULL
Im not understanding why im getting an undefined index.
I tried googling this, but most responses seem to point in the direction of using some kind of HTTPS method, which is what I'm trying to achieve via POST.
Any help will be greatly appreciated. Thank you.
The 'list' undefined issue might be due to the structure of the JSON array you pass.
Try the below code and check if it works. If not let's check further :)
var list = {'list': iterateItems()};
_ajax("https://127.0.0.1/prog1/final/class/ticket.php", list)
.done(function(list){});
});
function _ajax(url,data) {
var ajax = $.ajax({
type : "POST",
datatype : "json",
url : url,
data : data
})
return ajax;
}
function iterateItems() {
// array is an array populated in this function, returned to be sent to ticket.php
return JSON.stringify( array );
};
Your PHP Code:
<?php
var_dump(json_decode($_POST['list']));
PHP can't parse JSON parameters automatically. $_POST will only be filled in from a URL-encoded string or a FormData object.
$.ajax will URL-encode an array automatically for you.
_ajax("https://127.0.0.1/prog1/final/class/ticket.php", array)
.done(function(list) {});
function _ajax(url, data) {
var ajax = $.ajax({
type: "POST",
dataType: "string",
url: url,
data: {list: data}
})
return ajax;
}
In PHP you then don't need to call json_decode(). The value of $_POST['list'] will be the array.

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

Uncaught SyntaxError: Unexpected end of input in parseJSON method javascript

In a webpage that uses javascript, I pass data to a hidden input field using
$("#waypt_sel").val(JSON.stringify(itins.arr_intin));
and then later access that data using
waypts_input = $.parseJSON($("#waypt_sel").val())
This works, except that sometimes it gives a
Uncaught SyntaxError: Unexpected end of input
. I tracked the error to this line with the json parsing. but I am baffled because this works sometimes but sometimes it doesn't for the same, identical string.
I checked the values that are passed to the html inputs and it works and doesn't work for the same values.
Here's an example of the json string I am passing:
"[{\"location\":\"8.3353156, 80.3329846\",\"stopover\":true}, {\"location\":\"8.0326424, 80.7446666\",\"stopover\":true}, {\"location\":\"7.9577778, 80.667518\",\"stopover\":true}, {\"location\":\"7.953208, 81.006675\",\"stopover\":true}, {\"location\":\"7.885949, 80.651479\",\"stopover\":true},{\"location\":\"7.2905425, 80.5986581\",\"stopover\":true},{\"location\":\"7.300322, 80.386362\",\"stopover\":true}]"
Here's the structure of the code I use.
$(document).ready(function() {
$.ajax({
url: "aa.php",
type: "POST",
data: {
id: selected_i
},
success: function(result) {
itins = $.parseJSON(result);
$("#waypt_sel").val(JSON.stringify(itins.arr_intin));
}
});
$.ajax({
type: "POST",
contentType: "application/json",
url: "dd.php",
success: function(result) {
locations = $.parseJSON(result);
initializeMap();
}
});
function initializeMap() {
//other code
calculateAndDisplayRoute();
//other code
function calculateAndDisplayRoute() {
//other code
waypts_input = $.parseJSON($("#waypt_sel").val());
waypts_json_input = $.parseJSON(waypts_input);
//other code
}
}
});
And here is the detailed error message I get on firefox developer edition browser.
SyntaxError: JSON.parse: unexpected end of data at line 1 column 1 of
the JSON data
calculateAndDisplayRoute() map.js:366
initializeMap() map.js:290
.success() map.js:62
m.Callbacks/j() jquery-1.11.3.min.js:2
m.Callbacks/k.fireWith() jquery-1.11.3.min.js:2
x() jquery-1.11.3.min.js:5
.send/b() jquery-1.11.3.min.js:5
Thanks in advance.
"\" is unnecessary when deserialize json string in javascript .
what json tools you used?
you serialize in one tool , and deserialize with other , may get this scene .
The issue was that I was using an asynchronous ajax request to retrieve json data. by the time the data had been retrieved and pasted to the html, the execution of the code that used the html data had happened, and thus gave an error. I used a callback function for the ajax query and this did the job.
function get_det(callback) {//Your asynchronous request.
$.ajax({
url: "aa.php",
type: "POST",
success: function (result) {
alert("1st call");
callback();//invoke when get response
}
});
}
and in the code where this is called:
get_det(secondFunction);//calling with callback function
function secondFunction()//your callback function
{
alert("2nd Call");
}
Alternatively you may also try async: false in the ajax query parameters. But this can cause browser freezing and is not recommended.

How to get a <list> from mvc controller to view using jquery ajax

I need to get a list from mvc controller to view using jquery ajax. But I get [object Object].
Ajax code
$.ajax({
type: 'POST',
contentType: 'application/json; charset=utf-8',
url: '/Home/getList',
success: function (data) {
debugger;
$scope.StuList = data;
alert(data);
}
});
In Controller
public JsonResult getList()
{
Models.clsSave obj = new Models.clsSave();
var list = new List<Model>();
list= obj.getList();
return Json(list,JsonRequestBehavior.AllowGet);
}
If you are getting [Object,Object] means it contains the data. You just Iterate it on the success function of your $.ajax as shown below
success: function (data) {
$.each(data.items, function(item) {
alert('id :'item.id +' Name:'+item.sname);
});
}
All the best
You are getting an Object from ajax response to view that in alert try to stingify your object:
alert(JSON.stringify(data))
I need to get a list from mvc controller to view using jquery ajax.
But I get [object Object].
that means you're getting correct data list
how will I store it in $scope.StuList
You can just assign that data to $scope.StuList.
$scope.StuList = data;
Just to verify your data, put it in iteration
$.each($scope.StuList,function(i,v){
alert(v.sname);
});
You should get the correct data.
Or you can also put it in console, and verify yourself.
console.log($scope.StuList)
Hope this will help, or let me know if you still facing any issue.

Jquery returns [Object object] from POST function

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.

Categories

Resources