Link to home
Start Free TrialLog in
Avatar of EICT
EICTFlag for United Kingdom of Great Britain and Northern Ireland

asked on

JQuery which passes and collects data from php page not working on remote web only localhost

Hi,
I have the following JQuery which passes data to a php page and populates a form with the response from the php page. It works fine on my local host, but I just can't figure out why it does nothing on the remote web server. Any clues welcome.

<script type="text/javascript" src="../includes/jquery-1.10.2.min.js"></script>

<script>
$(document).ready(function(){
    $("#signal").click(function(){
      indata = $("#xinput").val();
        $.post("add_agencyreferral_prepop.php", {myArg:indata}, function(response){
            response = jQuery.parseJSON(response);
            document.getElementById("outname").value = response.name;
            document.getElementById("outadd1").value = response.add1;
            document.getElementById("outadd2").value = response.add2;
            document.getElementById("outcity").value = response.city;
            document.getElementById("outcounty").value = response.county;
            document.getElementById("outpostcode").value = response.postcode;
            document.getElementById("outtelNo").value = response.contactNo;
          
            
        }); 
     }); 
  });
</script>

Open in new window



php page code which takes the id input and returns address info is

require_once ('../../mysql_connect.php');  // Connect to the db.

$id = $_POST['myArg'];

		$queryagency = "SELECT id, name, address1, address2, city, county, postcode, contactNo FROM agency WHERE id = '$id'";
		$resultagency = @mysql_query ($queryagency); // Run the query.
		$rowagency = mysql_fetch_array($resultagency, MYSQL_ASSOC);
		

if(mysql_num_rows($resultagency) == 1)
{		
// SEND THE CONTENTS OF THE OUTPUT BUFFER
//die($rowagency[1]); 
$output =  array('name'=>$rowagency['name'],
                 'add1'=>$rowagency['address1'],
                 'add2'=>$rowagency['address2'],
                 'city'=>$rowagency['city'],
                 'county'=>$rowagency['county'],
                 'postcode'=>$rowagency['postcode'],
                 'contactNo' => $rowagency['contactNo']);

echo json_encode($output,JSON_FORCE_OBJECT);

} else
{		
// SEND THE CONTENTS OF THE OUTPUT BUFFER
//die($rowagency[1]); 
$output =  array('name'=>'',
                 'add1'=>'',
                 'add2'=>'',
                 'city'=>'',
                 'county'=>'',
                 'postcode'=>'',
                 'contactNo' => '');

echo json_encode($output,JSON_FORCE_OBJECT);

}

Open in new window


Is there something I need to do on the remote web server to make it understand JQuery?

Thanks
Avatar of EICT
EICT
Flag of United Kingdom of Great Britain and Northern Ireland image

ASKER

Added to this when I use the firefox debugger I get the following error, but only on the remote version.

"SyntaxError: JSON.parse: unexpected character "
SOLUTION
Avatar of Ray Paseur
Ray Paseur
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of EICT

ASKER

Thanks Ray.

I'm in the process of moving from mysql to mysqli, but decided to leave this till after I've resolved this problem so I can make the changes site wide.
Your "What NOT to do" is very helpful.  Seeing bad code must drive you mad - I think I've learnt bad habits from books and other resources!

Thanks.
No, bad code does not drive me mad -- I've written enough of my own to appreciate it in other people's work!  But that aside, this appears to be a data-dependent problem.  Not 100% sure of that yet, but here is what I'd like to do.  

Run the script from the browser, then copy and paste the JSON string here (use the code snippet feature).  JSON must be UTF-8 and if there are any ASCII characters above code point 127 it will fail.

More on the encoding issues here:
https://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/A_11880-Unicode-PHP-and-Character-Collisions.html
Also, you can make the MySQL -> MySQLi conversion piecemeal.  You can create both the MySQL and MySQLi connections at the same time and convert your queries one at a time.  If you choose the Object Oriented MySQLi extension the conversion will be easiest because it keeps the arguments in the same order as the MySQL extension.
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Julian Hansen
The problem might be with your data. The code is fine.

Do you have a link to the problematic server?
Make sure your page are saved as UTF8 without BOM
You can find when you ftp to your server those BOM characters suddenly become visible screwing up your code. Try opening the page that creates the JSON in your FTP program and see if they are visible right at the beginning of the page.
Gary: The PHP script is (supposedly) creating the JSON string.  I'm pretty sure that PHP will not put a BOM into a JSON string.  There is some other kind of failure, possibly a query failure, or perhaps the query returned two rows.  Because the original code does not test for this we have to do some visualization anyway, so when we get to see the JSON maybe there will be a clue.

Best to all, ~Ray
It's a possibility.  The code works fine locally so you would assume there is nothing wrong with the json data.  But if you upload a UTF8 file that has BOM characters they can/will be literally translated into the text file with an FTP program.  Ergo the php file will have those strange characters at the beginning of the file (no longer as BOM) so his file then writes out the json but those characters will be sent as part of the page before he gets to
echo json_encode,,,

Edit.
Just a quick test and you will end up with this at the beginning of the file.


I tell a lie it still sends it as BOM and invalidates the JSON
It seems to me that if the PHP script had a BOM in it, the BOM would be browser output no matter where you were running it, and it would still get prepended to the JSON string either on the localhost or the server.  I've never tested it.  I would think (hope) that the FTP process would not change any of the program code or data.

Anyway, we will be able to see more once we get a visual on the JSON string.
You are correct, I cannot manage to break it.
Maybe we are not talking about the same file locally and remotely.
Different files at local and remote?  That's not an uncommon occurrence.  Even when you have version control it's still possible to screw it up!
Avatar of EICT

ASKER

Hi Ray & Gary,

Sorry it's been a few days since I replied, I've been working on other things.

When I looked at what was returned from the add_agencyreferral_prepop.php page I was getting an JSON.parse error stating  " json_encode() expects exactly 1 parameter, 2 given ".
After a bit of research I discovered that the remote server was running PHP 5.2 and in order to assign values to property names you must be running PHP 5.3 or later.

When I upgraded the remote server to 5.3 I then started to receive the following - a bit more promising

{"name":"Bedford College","add1":"Cauldwell Street","add2":"","city":"Bedford","county":"","postcode":"MK42 9AH","contactNo":"01234 291000"} 

Open in new window


I've been doing a bit of reading about mysqli and OO programming in php so I understand Ray's script and can implement it.

Ray: When I look at what is returned from your object or json string , I get

{"current_field":null,"field_count":null,"lengths":null,"num_rows":null,"type":null}

Open in new window


Your json seems to be encoding the query result not the object or the row values. Is this correct?

Either way the results are not being collected and handled by the parent page add_agencyreferral.php.

The advise so far has been very helpful in getting this far - thanks.
That's the problem with not having a test bed - you make mistakes and can't readily find them!

Go to this line (42) in the code sample posted above:

$jso = json_encode($res);

Change it to this:

$jso = json_encode($obj);
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Try running the backend script from the browser address bar.  You probably want to change lines 41-43 from this:

// RETURN THE ROW IN THE FORM OF A JSON STRING
$jso = json_encode($obj);
die($jso);

to this:

// VISUALIZE THE DATA
var_dump($obj);
Avatar of EICT

ASKER

I needed to upgrade to PHP 5.3 and use the GET Statement in order for this to work. I have as yet not had the opportunity to try using JQuery but I'm reading the recommended book.
Thanks Matt
Thanks for the points and thanks for using EE, ~Ray