0

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?

2
  • data: data.join() is not how you create json. coldfusion will not be able to deserialize it as if it were json. Commented Apr 13, 2016 at 22:01
  • If you are using jQuery, why are you using document.getElementById()? Use jQuery to get those values. data.push( $('#customersid') ) I have found this to be a great tool to put form data into json easily, github.com/macek/jquery-serialize-object Commented Apr 14, 2016 at 13:23

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I fixed that using JSON.stringify(data), but I am getting parsererror when I return data from CFC to AJAX
@Apprentice123456 - Please update your question and append the current code AND error message.
0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.