Link to home
Create AccountLog in
Avatar of Ralph
RalphFlag for United States of America

asked on

Ajax not completing

This used to work, I lost some code, thank you Windows, and now it doesn't.

The PHP does its thing and returns, but nothing happens on the return to JavaScript.  No "HERE THREE!"!

The JS AJAX code:
var php_params = "job=SearchForm&task=PartialForm&tablename=Customer&uniq_field_value="+cust_name ; 
      var fields_to_BU = ['cust_name', 'cust_desig_2char', 'cust_desig_3char', 'region'] ;
      var customer_id ;
      $('#debug').html(php_params) ;
      
      $.ajax({
      url: '/cmdb/PHP/do_FormSearch_query.php',
      method:     "GET" ,
      cache:      false ,
      data:       encodeURIComponent(php_params)  ,
      dataType:   'JSON'
      }).done(function(data) 
      {
        alert("HERE THREE!");
        customer_id = data.customer_id ;
        $('input [name=cust_desig_2char]').val(data.cust_desig_2char) ;
        $('input [name=cust_desig_3char]').val(data.cust_desig_3char) ;
        $('input [name=region]').val(data.region) ;
        
        $('#RtMgn_Customer').val(customer_id) ;
        
         blah blah blah;
        
        
      })  ;  // EO AJAX .done function()

Open in new window



The PHP:
case "PartialForm":
        
        $uniq_field_value = htmlspecialchars($_GET['uniq_field_value']) ; 
        $tablename = htmlspecialchars($_GET['tablename']) ;
        
        switch($tablename)
        {
        case 'Customer':
          
          do_mysql_multi("SELECT * FROM Customer WHERE `cust_name`= '".$uniq_field_value."' ;", 1, $result_vector1, $result_vector2) ;
          
          echo json_encode($result_vector1['values'][1]) ;
          
          break ;

Open in new window

What PHP returns (sample):
{"customer_id":"76","cust_name":"QATAR AIRWAYS","cust_desig_2char":"QR","cust_desig_3char":"QTR","region":"Middle East","note_id":"75750"}

Open in new window

Avatar of Justin Smith
Justin Smith
Flag of United States of America image

Avatar of Ralph

ASKER

I don't see how that's relevant.  Please elaborate.
Thanks!
Sorry that's all I got. Just thought I might hit a home run. I really don't know code.
Have you confirmed that PHP is returning the data per the sample you've provided? Or is this a sample of what PHP is supposed to be returning?

Can you post a link to the page so we can see the wheels in motion?
Avatar of Ralph

ASKER

Hi Kim,

When I run the PHP w/ the GET parameters in a window by itself it returns what I posted above.

I'm behind a firewall at work.

The JS code is part of a very large .js file that has successful AJAXing all through it that still work.
The PHP code is similar, (but not relevant).

I'm baffled.
greetings Ralph, , I looked at the JS code and the PHP code, you have this as your AJAX javascript return method in the .done( ) method-
.done(function(data) 
      {
        alert("HERE THREE!");

Open in new window


IF there is no error in the PHP return JSON text format, then you should always see the alert , , but you say -  No "HERE THREE!" ! alert is shown,  I have seen this hundreds of times, where I do changes in the PHP code, and a "fatal error"  or "warning" is generated in the PHP text return to AJAX, which invalidates the needed proper JSON CSV text format. You need to look at the PHP TEXT returned to the AJAX and see the incorrect JSON format text. You should have the Jquery AJAX .error( ) method in your code for DEBUGGING, where you can get the PHP string sent to AJAX receiver.

I really think that your problem is this line -
data:       encodeURIComponent(php_params)  ,

You can not use the encodeURIComponent( )  on the ENTIRE URI string, because it will change the needed & and the = to the substitution HEX code, to use that you need to code it as -

var php_params = "job="+encodeURIComponent("SearchForm")+
"&task="+encodeURIComponent("PartialForm")+
"&tablename="+encodeURIComponent("Customer")+
"&uniq_field_value="+
encodeURIComponent(cust_name) ;


HOWEVER since you are using  Jquery  you can benefit by using the Jquery AJAX URI string build using a javascript Object like this -
$.ajax({
      url: '/cmdb/PHP/do_FormSearch_query.php',
      method:     "GET" ,
      cache:      false ,
      data:      {job : "SearchForm", task : "PartialForm", tablename : "Customer", uniq_field_value : cust_name } ,
      dataType:   'JSON'
      }).done(function(data) 
      {
        alert("HERE THREE!");
        customer_id = data.customer_id ;
        $('input [name=cust_desig_2char]').val(data.cust_desig_2char) ;
        $('input [name=cust_desig_3char]').val(data.cust_desig_3char) ;
        $('input [name=region]').val(data.region) ;
        
        $('#RtMgn_Customer').val(customer_id) ;
        
         blah blah blah;
        
        
      })  ;  // EO AJAX .done function()

Open in new window

Avatar of Ralph

ASKER

Hi Slick812,

Stranger and stranger things get.
It's now working, and it isn't.

I changed the data: attributes as you suggested, and included a fail: function, then it Sort Of started working.
Before I go there though, I'm still getting directly from PHP the same looking (good) results as I did before (see first post).  Big shrug.

Anway, I'm seeing the (now removed) alert("HERE THREE!"), so it is succeeding, and in Chrome's inspector I see the data returned, but now simple jQuery value() setting is flaking out on me.

... Moments later.
Ahhh javascript.  Tremendously flaky at times.  Gotta love/hate it.

Just inserting a line here, copying and pasting same jQuery .val setting, and all of a sudden what didn't work starts to.

I just inserted a console.log() after the code that was not populating the form, and all is well.
Remove the console.log() and it's still, (w/o warm fuzzies), working.

-- -- --

On that advice on not using encodeURIComponent( ) on the entire URI string because of the ampersand and equal signs, how should I handle it when the text I need to send includes an ampersand?
e.g.:  customer=AIR BERLIN PLC & CO LUFTVERKEHRS KG
?
As I've been doing it with the encodeURIComponent()  (no "="), it gets to PHP, PHP can echo the text and it looks fine, I can copy the text and use it is MySQL Workbench/where ever, and it works fine.  But in the normal flow of the application, it doesn't work.

Thank you oh mystery solver Slick.  :^)

Ralph
ASKER CERTIFIED SOLUTION
Avatar of Member_2_248744
Member_2_248744
Flag of United States of America image

Link to home
membership
Create an account to see this answer
Signing up is free. No credit card required.
Create Account
Avatar of Ralph

ASKER

Thanks for the advice on not adding in the JS kitchen sink.  The only thing I have is jquery-2.2.3 and my own libraries that rely on that one.

THANKS for the clear and elucidating $.ajax() most-all-options laid out!
A good learning thing to keep and share w/ others.

I did get your message about use of encodeURIComponent(), and I will do that explicitly or append a JS object key:value as you also showed.

However I have about a dozen situations where I put a little database internals info into the JS application, that I'm not eager to rewrite.
This is an in-house application never for the public.

It's in this scenario where the ampersand in the customer name is messing with me.

No other "=" signs, but apostrophes and percent signs.  Could they be mucking with the string containing the ampersand?
See the 2nd last line of code:
  // -----------------------------------------------------------------------------------------------
  
  var php_params = "job=SearchForm&task=FullForm&offset="+offset+"&tablename=Customer&where_clause=" ; 
  var where_clause= "WHERE " ;
  
  if (cust_name != "")         { where_clause = where_clause+"cust_name LIKE '%"+cust_name+"%' AND "  ; }
  if (cust_desig_2char != "")  { where_clause = where_clause+"cust_desig_2char LIKE '%"+cust_desig_2char+"%' AND "  ; }
  if (cust_desig_3char != "")  { where_clause = where_clause+"cust_desig_3char LIKE '%"+cust_desig_3char+"%' AND "  ; }
  
  // -----------------------------------------------------------------------------------------------
   
  if (where_clause.length < 10)
  {
    alert("Please enter a searchable value into a field that may uniquely identify a Customer.") ; 
    throw "No data to search with."  ;
  }
  
  var plen=where_clause.length ;
  where_clause=where_clause.substring(0,plen-1-4) ;
  
  php_params=php_params+encodeURIComponent(where_clause) ;
  
  $('#debug').html(php_params) ;

Open in new window

Certainly I could uriencode the data w/in my where_clause, but will I then run into % and ' problems?
Is there a way around this or do I have to change course?

Many many thanks.

Ralph
Looked at your code above, and could not see where you may or may not have a problem

If I understand your code, you are making a SQL string finish and placing it in the "where_clause" parameter of the URL string, , BUT this is a very , very BAD practice, , you should not ever BUILD SQL database Query strings on the browser side, you CAN not re-processes and analyze the INPUT values on the server side and make adaptations for correct SQL on the server side., you should just send up the values from the three variables - cust_name , cust_desig_2char , and cust_desig_3char to the server, and then test them for content, and if there is content , then use the SERVER code to build the string from the AJAX values, this can save an large amount of time and head aches in development.
 = = = = = = = = = = = = = = =

it looks like the WHERE string should be along the lines of -
    "WHERE cust_name LIKE '%Ben Smith%' AND cust_desig_2char LIKE '%My Design3%' AND"

 You absolutely can not place that string in a URL parameter, and must use the JS encodeURIComponent( ) like you showed -
             php_params+=encodeURIComponent(where_clause) ;
and this will work to transfer the symbols % and the q marks ' and any spaces or other punctuation properly to the POST elements in the Server Side received  AJAX.

you ask -
     "Certainly I could uriencode the data w/in my where_clause, but will I then run into % and ' problems?"

I do not really understand where this question comes from,? ? ? As without the encodeURI there may be problems, but using the encodeURIComponent( ) on just the URL parameters , is what JQUERY does in their OBJECT to URL string parameters conversion, , and any other javascript that has to process USER typed in input or strings that may have NON alpha numeric content.
Avatar of Ralph

ASKER

Okay, getting past the difficulty passing tablequalifier.fieldname from JS to PHP I no longer really have SQL in JS.
(Though one could argue that the "tablequalifier~" before the fieldname still gives too much away.)
The same code in PHP is used for 12 forms.

Thanks Slick for the vehamence of your concern and the solution.