Solved

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

Posted on 2014-01-23
19
476 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
[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
  • 10
  • 5
  • 3
  • +1
19 Comments
 

Author Comment

by:EICT
ID: 39802936
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 110

Assisted Solution

by:Ray Paseur
Ray Paseur earned 500 total points
ID: 39802938
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
ID: 39802978
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
Webinar: Aligning, Automating, Winning

Join Dan Russo, Senior Manager of Operations Intelligence, for an in-depth discussion on how Dealertrack, leading provider of integrated digital solutions for the automotive industry, transformed their DevOps processes to increase collaboration and move with greater velocity.

 
LVL 110

Expert Comment

by:Ray Paseur
ID: 39803035
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 110

Expert Comment

by:Ray Paseur
ID: 39803065
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 110

Accepted Solution

by:
Ray Paseur earned 500 total points
ID: 39803121
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 56

Expert Comment

by:Julian Hansen
ID: 39803232
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
ID: 39803477
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 110

Expert Comment

by:Ray Paseur
ID: 39803766
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
 
LVL 58

Expert Comment

by:Gary
ID: 39803802
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 110

Expert Comment

by:Ray Paseur
ID: 39804338
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
ID: 39804439
You are correct, I cannot manage to break it.
Maybe we are not talking about the same file locally and remotely.
0
 
LVL 110

Expert Comment

by:Ray Paseur
ID: 39804473
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
ID: 39814982
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 110

Expert Comment

by:Ray Paseur
ID: 39815206
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
ID: 39815327
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 110

Expert Comment

by:Ray Paseur
ID: 39815436
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
ID: 39882027
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 110

Expert Comment

by:Ray Paseur
ID: 39882316
Thanks for the points and thanks for using EE, ~Ray
0

Featured Post

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
MySQL limit and not so limited 13 37
Need guidance for special auto increment values 2 21
Multi line FPDF footer: 3 25
Put POST values into cookies. 14 34
Introduction JSON is an acronym for JavaScript Object Notation.  It is a text-string data transport mechanism, capable of representing simple or complex data structures in a consistent and easy-to-read manner.  Similar in concept to XML, but more e…
3 proven steps to speed up Magento powered sites. The article focus is on optimizing time to first byte (TTFB), full page caching and configuring server for optimal performance.
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …

749 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