Solved

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

Posted on 2014-01-23
19
459 Views
Last Modified: 2014-02-24
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
0
Comment
Question by:EICT
  • 10
  • 5
  • 3
  • +1
19 Comments
 

Author Comment

by:EICT
Comment Utility
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 "
0
 
LVL 108

Assisted Solution

by:Ray Paseur
Ray Paseur earned 500 total points
Comment Utility
Short answer is "no" because jQuery is JavaScript and it runs on the client machine.

Better answer is "deconstruct the problem" so you can find where the issue lies.  Can you run the PHP script standalone, without jQuery and get a response?

The way I would go about testing this is to change the POST-method request to a GET-method request.  (It should have always been a GET request - it's not changing anything on the server).  Once you have it set up as a GET request you can run it from the browser address bar and look in the browser "view source" to see what you get back.

Also, you may want to learn a few more of the fundamentals about how to use PHP and MySQL.  These articles can help.

Good learning resources for PHP and MySQL
What NOT to do (several instances in the code here)
The Right Way to get off MySQL (Do it now before it becomes an emergency)
0
 

Author Comment

by:EICT
Comment Utility
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.
0
 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
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:
http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/A_11880-Unicode-PHP-and-Character-Collisions.html
0
 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
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.
0
 
LVL 108

Accepted Solution

by:
Ray Paseur earned 500 total points
Comment Utility
Maybe try something like this.

Line 7 of the javascript changed to GET request:

$.get("add_agencyreferral_prepop.php", {myArg:indata}, function(response){

Open in new window

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

/**
 * ASSUMES THAT THE mysql_connect.php SCRIPT HAS ALSO MADE
 * AN OOP MYSQLI CONNECTION AND THE CONNECTION OBJECT IS
 * IN A VARIABLE NAMED $mysqli
 */
 
// SANITY CHECK: ENSURE THAT THE ARGUMENT IS AN INTEGER
$id = (int)$_GET['myArg'];

// CONSTRUCT THE QUERY (NOTE: WE USE NAMES TO MATCH THE RETURN VALUES IN THE JSON)
$sql 
= 
"
SELECT 
  name
, address1 AS add1
, address2 AS add2
, city
, county
, postcode
, contactNo 
FROM agency 
WHERE id = '$id'
LIMIT 1
"
;

// RUN THE QUERY AND TEST FOR SUCCESS
$res = $mysqli->query($sql);
if (!$res) trigger_error("FAIL: $sql " . $mysqli->error(), E_USER_ERROR);

// EXPECT ONE AND ONLY ONE ROW BECAUSE OF QUERY LIMIT CLAUSE
if ($res->num_rows == 0) /* HANDLE NO-DATA CONDITION */

// RETRIEVE THE ROW IN THE FORM OF AN OBJECT
$obj = $res->fetch_object();

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

Open in new window

0
 
LVL 51

Expert Comment

by:Julian Hansen
Comment Utility
The problem might be with your data. The code is fine.

Do you have a link to the problematic server?
0
 
LVL 58

Expert Comment

by:Gary
Comment Utility
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.
0
 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
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
0
Do You Know the 4 Main Threat Actor Types?

Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

 
LVL 58

Expert Comment

by:Gary
Comment Utility
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
0
 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
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.
0
 
LVL 58

Expert Comment

by:Gary
Comment Utility
You are correct, I cannot manage to break it.
Maybe we are not talking about the same file locally and remotely.
0
 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
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!
0
 

Author Comment

by:EICT
Comment Utility
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.
0
 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
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);
0
 

Assisted Solution

by:EICT
EICT earned 0 total points
Comment Utility
Hi Ray,
I've tried this but still no joy. However, now I've upgrade to PHP 5.3 and fixed an error I made ,when testing prior to my last post, my original code but with the GET statements now works.

I would much prefer using mysqli and OO programming so will continue to look at this. For some reason the json_encode($obj) returns a null value.

By the way - one error without the test bed is pretty good I think. :-)
0
 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
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);
0
 

Author Closing Comment

by:EICT
Comment Utility
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
0
 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
Thanks for the points and thanks for using EE, ~Ray
0

Featured Post

Top 6 Sources for Identifying Threat Actor TTPs

Understanding your enemy is essential. These six sources will help you identify the most popular threat actor tactics, techniques, and procedures (TTPs).

Join & Write a Comment

Suggested Solutions

PROBLEM: The other day I was working on adding an ajax request to a webpage that already had a dialog box on the page.  The dialog box was using relative positioning to be positioned next to a form field I had on the page.  Everything was working…
Since pre-biblical times, humans have sought ways to keep secrets, and share the secrets selectively.  This article explores the ways PHP can be used to hide and encrypt information.
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

743 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

Need Help in Real-Time?

Connect with top rated Experts

16 Experts available now in Live!

Get 1:1 Help Now