Solved

Issues with JavaScript/AJAX/MySQL/PHP

Posted on 2014-01-28
9
482 Views
Last Modified: 2014-01-29
I have a web application that is built using JavaScript/JQuery. I need to pull values into this out of aMySQL database. I use AJAX to access a PHP script to do this and I can return the proper value. However the JavaScript does not recognize it as data and displays it as a string no matter what I do.
0
Comment
Question by:Clayton Decker
  • 3
  • 2
  • 2
  • +2
9 Comments
 
LVL 11

Expert Comment

by:Amar Bardoliwala
ID: 39816883
Hello InfiniumIT,

Can you please post your current code here?

what have you given in dataType property of your ajax call?

it should be set to json, if you want to access it as json object.

By default it is html and you return data will be treated as string.

how are you sending data back from php to javascript?

Hope this will help you.

Thank you.

Amar Bardoliwala
0
 
LVL 82

Expert Comment

by:Dave Baldwin
ID: 39816927
JavaScript does not recognize it as data and displays it as a string no matter what I do.
My first response is... of course it does.  Everything returned from the database and passed back by PHP is going to be text.

My first question is... what are you expecting?  If you were expecting binary numbers, that won't happen.  If you were expecting a particular text format, did you do anything to create that format?

Javascript is weakly 'typed' meaning that you have to tell it if you want a numeric text string to be used as a number.  I typically do that by adding 0 to it or multiplying by 1.  Either operation will force javascript to view that data as a number.
0
 
LVL 51

Assisted Solution

by:Julian Hansen
Julian Hansen earned 167 total points
ID: 39816981
Here is a basic sample that illustrates what you need to do to get this to work.
PHP
<?php
// Get any parameters sent to the script here
$id = empty($_POST['id'])?0:$_POST['id'];
// Do your database query here
// Assuming data is returned in an array

// Sample data to be sent back
$data = array();
$data['name'] = 'John';
$data['email'] = 'john@domain.com';

// Terminate script sending data back as a json string
die(json_encode($data));
?>

Open in new window

HTML
<!doctype html>
<html>
<head>
<title>Test AJAX PHP MYSQL</title>
<script src="http://code.jquery.com/jquery.js">></script>
<script type="text/javascript">
// On ready
$(function() {
  // trap event to do aJAX
  $('#data').click(function(e) {
    // disable default behaviour
    e.preventDefault();
    // Call the script with parameters as needed
    $.post('ajax.php',{id: 1}, function(resp) {
      // set the values of the fields based on response
      $('#name').val(resp.name);
      $('#email').val(resp.email);
    }, 'json'); // Important - don't leave this out or else
                   // JQuery won't translate the returned JSON and you will just get a string
  });
});
</script>
</head>
<body>
<input type="button" id="data" value="Get Data" /><br/>
Name <input type="text" id="name" /><br/>
Email <input type="text" id="email" /><br/>
</body>
</html>

Open in new window

0
 
LVL 108

Accepted Solution

by:
Ray Paseur earned 333 total points
ID: 39817390
This question is a little bit like "My car won't start."  We might need to know a little more of the specifics before we can tell you what to do next :-)  An example, with test data, or maybe a link to the failing URL?

There are several "transport layers" involved in your processes.  For binary data to survive across the transport layers, base64_encode() is often helpful (for example, when sending encrypted data or putting images into a data base).  Other than that, pretty much everything you send will be a string, and will be interpreted in "duck type" meaning that if it quacks like a duck, it must be a duck.  So a numeric string like "123" can be used directly in arithmetic.

You might find this article to be helpful.  It shows the essential moving parts of the interaction between jQuery and a PHP back-end script.
http://www.experts-exchange.com/Programming/Languages/Scripting/JavaScript/Jquery/A_10712-The-Hello-World-Exercise-with-jQuery-and-PHP.html
0
What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

 

Author Comment

by:Clayton Decker
ID: 39818065
OK I'll see if I can get my code to you. If I set it to json it doesn't return anything so I'm thinking the problem is on the php side. I'm reading a book on it and I'm not putting it in name value pairs and I'm not sure how to do that and then parse it correctly. Also in a lot of questions I've found online, pertaining to this subject, they talk about using a callback or else the data is unusable because of the asynchronous aspect of the function.
0
 
LVL 108

Assisted Solution

by:Ray Paseur
Ray Paseur earned 333 total points
ID: 39818228
The easiest way to get code to us is to post the code in the comment block, using the Code tag.  Copy your code, then in the gray bar with the formatting symbols, click Code and then paste right where it's put the cursor.
0
 

Author Comment

by:Clayton Decker
ID: 39818290
OK yes I understand this. Sorry I was very short in my explanation. By returning data I meant that it was returning numbers but that I am not able to use them in my JavaScript. For example I'm returning a stock price. I can put it into a variable and display that variable but if I try to multiply that variable times three it doesn't return anything even if I've set it as a number. I think I have a few ideas now though thanks to your response.
0
 

Author Comment

by:Clayton Decker
ID: 39818536
Thanks!
0
 
LVL 51

Expert Comment

by:Julian Hansen
ID: 39818763
If your numbers are coming back as strings try using parseInt and parseFloat to convert them to numbers that can be used in mathematical operations.
0

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
Nothing in an HTTP request can be trusted, including HTTP headers and form data.  A form token is a tool that can be used to guard against request forgeries (CSRF).  This article shows an improved approach to form tokens, making it more difficult to…
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…

705 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

20 Experts available now in Live!

Get 1:1 Help Now