Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

Ajax not completing

Posted on 2016-07-28
11
Medium Priority
?
108 Views
Last Modified: 2016-08-04
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

0
Comment
Question by:Ralph
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 5
  • 3
  • 2
  • +1
11 Comments
 

Author Comment

by:Ralph
ID: 41734040
I don't see how that's relevant.  Please elaborate.
Thanks!
0
 
LVL 4

Expert Comment

by:Justin Smith
ID: 41734041
Sorry that's all I got. Just thought I might hit a home run. I really don't know code.
0
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 
LVL 22

Expert Comment

by:Kim Walker
ID: 41734085
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?
0
 

Author Comment

by:Ralph
ID: 41734974
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.
0
 
LVL 34

Expert Comment

by:Slick812
ID: 41735822
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

0
 

Author Comment

by:Ralph
ID: 41736066
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
0
 
LVL 34

Accepted Solution

by:
Slick812 earned 2000 total points
ID: 41736103
OK, , In using Jquery, many developers do large amounts of Jquery conditionals, and Jquery "Chained" methods, and do not take time to try and use less code, and check for inefficiencies, and redundant code phrases and methods. Ans some developers load so many javascript librarys , like three versions of Jquery, a version of MooTools, and several other javascript add on. . . . This can lead to what you call - "Tremendously flaky at times" javascript, seemingly working, and then a small change it seems not to work, or sometimes it works and sometimes it seems not to.

You may need to re evaluate the amount of javascript add-on, and the amount of javascript code work you have, and Reduce the unneeded "special" widgets, and redundant code processes, , in order to get an "efficient" and optimized and WORKING javascript functioning.

= = = = = = = = = = = = = = = =

you ask - "how should I handle it when the text I need to send includes an ampersand?
e.g.:  customer=AIR BERLIN PLC & CO LUFTVERKEHRS KG"

I tried to explain this to you, and I gave you an example as

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

In further explain, Please Notice, that the necessary URI parameters of & and = are NOT in the encodeURIComponent( ), but just in the unaltered STRING portion as  +"&task="+

So you could build the URI string with -
+"&customer="+encodeURIComponent("AIR BERLIN PLC & CO LUFTVERKEHRS KG")+

Or using variables -
var cus = $('input [name=customer]').val( );
// cus above contains string "AIR BERLIN PLC & CO LUFTVERKEHRS KG"
if (!cus) {alert("customer is Empty, please fill it"); return;}

var tsk = $('#task').text( );

var prms = "tsk="+encodeURIComponent(tsk)+
"&cus="+encodeURIComponent(cus);

prms = {
      url: '/cmdb/PHP/do_FormSearch_query.php',
      method:     "GET" ,
      cache:      false ,
      data:       prms ,
      dataType:   'JSON'
      }

$aj = $.ajax(prms);

$aj.done(function(data) {
  if (data.error) {
  alert("Server ERROR: "+data.error+", because - "+data.factors);
  } else {
  alert("The Server Operation is complete for Customer: "+data.cusName);
  }

 })  ;

aj.fail(function(xhr, error1, err) {
  if (xhr.status==404) alert("ERROR from Ajax as '404 status' the "+prms.url+
  " page was NOT on Server, \nCan NOT recover from this ERROR, This operation is NOT available!");
  else {
    alert("Ajax ERROR = \""+error1+"\", with server Status: "+xhr.status+", post-URL: "+prms.url+
	", \npost-Data: "+prms.data+", \nerror because: "+err);
    if (aj.responseText) {
    console.log("Ajax ERROR response= "+aj.responseText); 
    }else console.log("Ajax Received Text is empty");
  }
  });

Open in new window

0
 

Author Comment

by:Ralph
ID: 41737873
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
0
 
LVL 34

Expert Comment

by:Slick812
ID: 41737973
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.
0
 

Author Closing Comment

by:Ralph
ID: 41743520
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.
0

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

jQuery is a JavaScript library that greatly simplifies JavaScript programming. AJAX is an acronym formed from "Asynchronous JavaScript and XML."  AJAX refers to any communication between client and server, when the human client does not observe a…
Introduction HyperText Transfer Protocol (http://www.ietf.org/rfc/rfc2616.txt) or "HTTP" is the underpinning of internet communication.  As a teacher of web development I have heard many questions, mostly from my younger students who have come to t…
In this brief tutorial Pawel from AdRem Software explains how you can quickly find out which services are running on your network, or what are the IP addresses of servers responsible for each service. Software used is freeware NetCrunch Tools (https…
Have you created a query with information for a calendar? ... and then, abra-cadabra, the calendar is done?! I am going to show you how to make that happen. Visualize your data!  ... really see it To use the code to create a calendar from a q…
Suggested Courses

660 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question