jquery cfml ajax

This is frustrating. Nothing I've read makes this clear. And it shouldn't be this complicated. This is the current state of my code. I've been testing every combination hoping it would make sense. All I want to return from the CFfunction is a record count and show it during the hover.

$(".alphabet").hover(function () {
  $.ajax({ type: "POST", 
  url: "cfc/basic.cfc?method=CountUsersByLetter&returnformat=json", 
  data: "nbw=" + $(this.target).val(), 
  datatype: "html",
  success: function(usercount){
  alert(usercount);
  },
  error: function (xhr, textStatus, errorThrown){ 
   // show error 
   //alert(errorThrown);
   console.log('errorThrown');
    } 
  }); 
    $(this).append($("<span>" + usercount +"</span>"));
     }, 
  function () {
    $(this).find("span:last").remove();
  }
);

<cffunction name="CountUsersByLetter" output="no" returntype="query" access="remote">
 <cfargument name="NBW" required="false" type="string" default="A" hint="name begins with">
 <cfset var qResults = "">
  <cfquery name="qResults" datasource="#request.dsn#">
   select count(id) as usercount from Temp_Duplicate_Individuals_CC
   WHERE left(lastname,1) = <cfqueryparam value="#arguments.NBW#" />
  </cfquery>
 <cfreturn #qResults#>
</cffunction>

preguntado el 01 de febrero de 12 a las 03:02

What error are you getting? One thing I notice is your attribute "datatype" should be "dataType". -

If I make a bad combination with datatype and returnformat I get an error that datatype cannot be ........ So, I don't think it matters in this case. But, I will definitely test it again. -

I get all kinds of errors. One of them is that Coldfusion cannot add to the output stream. Other errors are about combinations of datatype, returnformat, and returntype. -

I guess I will leave this answer for myself; If the error comes from the success function of the ajax call, don't sweat it. If the error comes from the error function of the ajax call, deal with it. If the error tells you that the data cannot be parsed or that the returntype or returnformat are wrong, try datatype:"html" and add &returnformat=json to the data: function of the ajax call. After that, you're on your owwn. Try different combinations. -

4 Respuestas

Tienes que entender eso ajax is async in nature by default so you have to wait until server responds before using usercount which is only available inside success handler. Either make a synchronous call by setting async a false or wait until the server responds.

Move your code inside success handler

$(".alphabet").hover(function () {
  $.ajax({ type: "POST", 
     url: "cfc/basic.cfc?method=CountUsersByLetter&returnformat=json", 
     data: "nbw=" + $(this.target).val(), 
     datatype: "html",
     success: function(usercount){
       //alert(usercount);
       $(this).append($("<span>" + usercount +"</span>"));
     },
     error: function (xhr, textStatus, errorThrown){ 
      // show error 
      //alert(errorThrown);
      console.log('errorThrown');
    } 
  }); 

  }, 
  function () {
    $(this).find("span:last").remove();
  }
);

I would not advice you to make synchronous call because it makes the whole page wait and sometimes the browser hangs completely if the server takes time to respond.

Respondido 01 Feb 12, 07:02

This is the console log entry after moving the hover start in the success function; {"COLUMNS":["USERCOUNT"],"DATA":[["0"]]}<!-- " ---> ColdFusion was unable to add the text you specified to the output stream. This is probably because you have already used a CFFLUSH tag in your template or buffered output is turned off. </font> </td> </tr> <tr> <td height>&nbsp;</td> </tr> - user990016

Why don't you try cfreturn qResults.recordCount? You are returning the entire query object right now.

Respondido 01 Feb 12, 18:02

I did. And I will test it again and post the results as soon as I get the code to - user990016

Oops, Scott was right, I didn't see the count() in your query, so you already have the record count. You just need the column. - JT

OK, got the code straightened out. I get the following error from the hover/ajax/error event. Unable to add text to HTML HEAD tag. - user990016

$(".alphabet").hover(function() { var _$this = $(this); var usercount = 0; $.ajax({ type: "Get", url: "cfc/basic.cfc?method=CountUsersByLetter&returnformat=plain", data: "nbw=" + $(this.target).val(), datatype: "html", success: function(res) { alert (data); usercount = eval("(" + res + ")").DATA[0][0]; _$this.append($("<span> (" + usercount + ")</span>")); }, error: function(xhr, textStatus, errorThrown) { console.log('errorThrown'); - user990016

return type from the cfc function is string - user990016

There's a lot of things that could use tweaking in the code.

I would add this line of code right before the .ajax() call:

$.ajaxSetup({ timeout: 5000, cache: false }); // this is needed or ie will cache the ajax responses!

@Jason Tabler's response is close. RecordCount of a query using COUNT() will always return a value of 1 (one). I would change the cfreturn statement to be this:

<cfreturn qResults.usercount />

Pound signs are not needed in the cfreturn and this will return the value instead of a query object.

The ajax call should not be a "POST". "POST" is usually used to submit to a form action page. This should be a "GET".

I always use Firebug to check the data format returned for the success: function and then add code to display it. Since the return was changed above it should become a much simpler json object to use.

Respondido 02 Feb 12, 01:02

I totally missed that out was a count query! - JT

Change success function as per below.. As function return whole query not only count so you will get query object in usercount argument not only count. Also you will receive as text string you may need to convert to JSON object using eval() function.

EDIT: Here is full functional code. I was looking into success function issue only but appending SPAN you had wrote outside success was also causing issue.

    $(".alphabet").hover(function () {
              var _$this = $(this);
              var usercount = 0;
              $.ajax({ type: "POST", 
              url: "scribble.cfc?method=CountUsersByLetter&returnformat=json", 
              data: "nbw=" + $(this.target).val(), 
              datatype: "html",
              success: function(res){
                 usercount = eval("(" + res + ")").DATA[0][0];
                 _$this.append($("<span> (" + usercount +")</span>"));
              },
              error: function (xhr, textStatus, errorThrown){ 
               console.log('errorThrown');
                } 
            }); 
        }, 
          function () {
            $(this).find("span:last").remove();
          }
        );

Respondido 02 Feb 12, 09:02

For some reason I am limited in my reply. I can't post the code. But, in Firebug, the executable code shows the line numbe rin green. None of my code appears to be executable. No breakpoints work. - user990016

< script type = "text/javascript" > var usercount = 0; $(document).ready(function() { $('.notdupe').live('click', function(e) { alert("indivNum=" + $(e.target).val() + "&SetValue=" + $(e.target).is(":checked")); $.ajax( { type : "POST", url : "cfc/basic.cfc?method=SetNotDupe", data : "indivNum=" + $(e.target).val() + "&SetValue=" + $(e.target).is(":checked"), error : function (xhr, textStatus, errorThrown) { // show error alert(errorThrown); } } ); } ); - user990016

$('.alphabet').live('click', function(l) { SelectedLetter = $(l.target).val(); $(".alphabet").each(function(i) { var CheckLetter = $(this).val(); if (CheckLetter == SelectedLetter) { $(this).css("background-color", "yellow"); $('.NameBeginsWith').val(SelectedLetter); } ELSE { $(this).css("background-color", ""); } } ); $('.Reinit').attr('value', SelectedLetter); $('.Reinit').trigger ('click'); } ); - user990016

$(".alphabet").hover( function () { $.ajax( { type : "POST", url : "cfc/basic.cfc?method=CountUsersByLetter&returnformat=json", data : "nbw=" + $(this.target).val(), dataType : "html", success : function(usercount) { //alert(usercount); usercount = eval("(" + usercount + ")").DATA[0][0]; $(this).append($("<span>" + usercount + "</span>")); } , error : function (xhr, textStatus, errorThrown) { alert(errorThrown); //console.log('errorThrown'); } } ); } - user990016

, function () { $(this).find("span:last").remove(); } ); } ); - user990016

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.