I run a mysql query and get the results successfully. However, I cannot read the elements of the array from javascript side. Can anyone help??
//JAVASCRIPT makes a request
function profiles(){
$.post('dbConn.php', { opType:"getProfileList" }, fillProfileCombo, "text");
}
function fillProfileCombo(res) {
alert(res);
}
//dbConn.php takes the request , gets the result and passes via echo as it is shown as follows:
//RETURN PROFILE LIST
else if (!strcmp($opType, "getProfileList")){ //no param is coming
$connect = mysql_connect( $db_host, $db_user, $db_pass ) or die( mysql_error() );
mysql_select_db( $db_name ) or die( mysql_error() );
$profiles = mysql_query(" SELECT DISTINCT profileName FROM `map_locations` ");
$row = mysql_fetch_array($profiles);
/*while() {
echo $row['FirstName'] . " " . $row['LastName'];
echo "<br />";
}
*/
//$data = array();
//$row = mysql_fetch_assoc($profiles)
/*while($row = mysql_fetch_assoc($profiles))
{
$data[] = $row;
}*/
if ($row){
echo $row;
} else {
echo "ERROR occured";
}
}
//PROBLEM:
//when I change echo $row; into echo $row[0]; , I see the first element in an alert box...query is definitely working..
//however when I change res to res[0], it does not show anything - which is normal because I do not know how to cast php array into js array..
function fillProfileCombo(res) {
alert(res[0]); // does not work..
}
I do not want to use json by the way... I am not very good at. I do not want to mess it up. Any suggestion and help is appreciated.
// PHP
$res = array();
while ($row = mysql_fetch_array($profiles)) {
$res[] = $row['profileName'];
}
header('Content-type: application/json');
echo json_encode($res);
// JavaScript
$.post('dbConn.php', { opType:"getProfileList" }, function(data) {
alert(data.length + " profiles returned");
}, "json");
Thanks Phil..This works now.. I followed your way by changing sth.. Maybe it was working but I couldnt run it. Very similar except a couple of changes. I changed it as like this:
//PHP
$data = array();
while($row = mysql_fetch_assoc($profiles))
{
$data[] = $row;
}
if ($data){
echo json_encode($data);
} else {
echo $data;
}
//JS
function profiles(){
//$.post('dbConn.php', { opType:"getProfileList" }, fillProfileCombo, "json");
$.post('dbConn.php', { opType:"getProfileList" }, fillProfileCombo, "json");
}
function fillProfileCombo(data) {
alert(data[1].profileName);
}
Related
I've been pounding on this for a few days, so time to ask for help. I'm trying to use Ajax/PHP/MySQL to show only a subset of a table based on the user's selections in dropdown. The PHP code calls a MySQL stored procedure. The call I'm constructing is right, and if I echo it out and then copy it and run it as is from the phpMyAdmin MySQL console, I get exactly the results I expect. But from the PHP code that's called by Ajax, I instead see this result (echoed in Firebug, after I JSON_encode it):
{"current_field":null,"field_count":null,"lengths":null,"num_rows":null,"type":null}
The relevant part of the page itself is:
<script>
function updateActions() {
var results = '';
var success = false;
var selectedIssues = getIssues();
var fnargs = "GetActions|'" + selectedIssues + "'";
$.ajax({
url: 'retrievedata.php',
type: "POST",
async:false,
data: {"functionname":"getactions", "arguments":fnargs},
dataType: "JSON",
complete: function (obj, textStatus) {
if( (obj.error != '') ) {
alert(JSON.parse(obj));
$("#testresult").text(textStatus);
}
else {
$("#testresult").text("Error");
// console.log(obj.error);
}
success = true;
},
error: function(textStatus, errorThrown) {
success = false;
$("#testresult").text('Error occurred: '.textStatus);
}
})
};
</script>
Two notes. First, the getIssues script it calls returns the expected value. Second, I haven't actually written the right code to process the result once I get it. Still trying to get the right result back to the page.
Page retrievedata.php looks like this:
<?php
include "dbfns.php";
$aResult = array();
$returnval = 'before tests';
if( !isset($_POST['functionname']) ) {
$aResult['error'] = 'No function name!';
}
if( !isset($_POST['arguments']) ) {
$aResult['error'] = 'No function arguments!';
}
if( !isset($aResult['error']) ) {
$functionName = $_POST['functionname'];
$argsarray = explode('|', $_POST['arguments']);
$argcount = count($argsarray);
$returnval = 'before switch';
switch($_POST['functionname']) {
case 'getactions':
if( $argcount < 2 ) {
$returnval = 'too few arguments';
}
else {
$returnval = 'in else';
$returnval = getactions($argsarray[0], $argsarray[1]);
}
break;
default:
$returnval = 'function not found';
break;
}
}
return $returnval;
?>
The relevant portions of dbfns.php (with identifying data and credentials removed, of course) are:
<?php
function connect2db() {
$hostname = "XXX";
$username = "XXX";
$password = "XXX";
$database = "XXX";
$conn = mysqli_connect($hostname, $username, $password, $database);
if( $conn == false ) {
echo "Connection could not be established.<br />";
die( print_r( myslqi_connect_error(), true));
}
return $conn;
}
function getactions($spname, $params, $errorstring = 'Unable to retrieve requested data') {
$conn = connect2db();
$query = "CALL ".$spname."(".$params.")";
echo $query."\r\n";
$result = mysqli_query($conn, $query);
if ($result == false) {
$errmessage = mysqli_error($conn);
$allresult = $errmessage;
echo $errmessage;
die( print_r( mysql_error(), true));
}
else {
echo "In else case\r\n";
$allresult = json_encode($result);
}
echo $allresult;
return $allresult;
}
?>
I have another PHP function in retrievedata that calls the same MySQL SP, but not from Ajax and it returns the expected result, so I'm pretty confident that the SP does what I expect.
I think there must be something I don't get about how to do all this from Ajax.
Edit: Just want to add that I've tried success rather than complete in the ajax call, and _GET rather than _POST. No change in results.
That looks like it's serializing the result object from mysqli_query(). I'm not sure what it does internally, but it may not return the actual resulting data until you enumerate/fetch the results.
See this example on one way to convert it to a JSON result.
I am trying to return ajax response in json, but when I print it in log it gives null even tables has rows,
my php code is:
if(isset($_GET['proid'])){
$projid = $_GET['proid'];
include(db.php);
$res = mysqli_query($con, "SELECT * FROM data WHERE project_id LIKE '%$projid%'");
while($row = mysqli_fetch_assoc($res))
{
$dataarray[] = $row;
}
echo json_encode($dataarray);
}
ajax :
$.ajax({
url : 'getRecStudy.php',
type : 'GET',
data : {proid:study},
success : function(data) {
$('#tbody').empty();
$("#tbody").append(data);
console.log(data);
}
});
whats wrong?
I find no issue in your code except varibales. You need to debug the code in php file
if(isset($_GET['proid'])){
echo $_GET['proid'] . " is proid";
$projid = $_GET['proid'];
include(db.php);
echo "db connected";
$res = mysqli_query($con, "SELECT * FROM data WHERE project_id LIKE '%$projid%'");
echo "result fetched";
while($row = mysqli_fetch_assoc($res))
{
$dataarray[] = $row;
echo "inside while";
}
echo json_encode($dataarray);
print_r($dataarray);
exit;
}
after all this hit http://yourdomain.com/yourfile.php?proid=correctvalue
You will get the bug.
use parseJSON method in success function like this
var obj = jQuery.parseJSON( data );
alert( obj.name ); // For example name is a key
I'm trying to get a number from a mysql line then outputting it to ajax. the number can't be a string because I will multiply it in ajax. This is what i have so far. I'm not sure what to do from here.
ajax:
$(document).ready(function()
{
$("#btnCalc").click(function()
{
var user = $("#txtUser").val();
var amount = $("#txtAmount").val();
var category = $("txtCat").val();
var number = $("txtNum").val();
var result = '';
$.get("code/value.php",
{
ID:user,
amount:amount,
result:result
},function(query)
{
if ( user > 0 and user < 30 ){
alert(result);
}
else{
alert( 'invalid user ID');
}
});
});
});
php:
<?php
$userID = $_GET["ID"];
$amount = $_GET["amount"];
$category = $_GET["category"];
$num = $_GET["number"];
require "../code/connection.php";
$SQL = "select userAmount from user where userID= '$userID'";
$reply = $mysqli->query($SQL);
while($row = $reply->fetch_array() )
{
}
if($mysqli->affected_rows > 0){
$msg= "query successful";
}
else{
$msg= "error " . $mysqli->error;
}
$mysqli->close();
echo $msg;
?>
Pretty straightforward - you just grab the value from the row and cast it as a float.
while($row = $result->fetch_array() )
{
$msg = floatval($row['userAmount']);
}
if($msg > 0) {
echo $msg;
} else {
echo "error" . $mysqli->error;
}
$mysqli->close();
And one small change in your ajax call:
$.get("code/value.php",
{
ID:user,
amount:amount,
result:result
},function(query)
{
alert(query);
});
});
You need to add echo $row['userAmount']; inside or after your while loop, and drop the second echo. You should be able to take result within your AJAX code and use it as a number directly.
Here function(query), query is the response from the AJAX call. So your alert should be:
alert(query);
result is empty.
You also should be using prepared statements and outputting the value you want.
Something like:
<?php
$userID = $_GET["ID"];
$amount= $_GET["amount"];
require "../code/connect.php";
$SQL = "SELECT userAmount FROM user WHERE userID= ?";
$reply = $mysqli->prepare($SQL);
if($mysqli->execute(array($userID))) {
$row = $reply->fetch_array();
echo $row['amount'];
}
else
{
$msg = "error" . $mysqli->error;
}
$mysqli->close();
?>
Then JS:
$(document).ready(function()
{
$("#btnCalc").click(function()
{
var user = $("#txtUser").val();
var amount = $("#txtAmount").val();
var result = '';
$.get("code/value.php",
{
ID:user,
amount:amount,
result:result
},function(query)
{
alert(query);
});
});
});
You can use https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/parseFloat or https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt to convert the value to an integer/float in JS.
I have a simple database query written in PHP using PDO. When I var_dump my $results, I get an associative array. So I figured I'd just use return $ result, call the script using AJAX and then work from there. But now when I console.log the data I get, I just get an empty string.
Can somebody explain what I'm doing wrong and how to fix it? Thanks
Here's my php (I've emptied host, username and password for "safety"):
<?php
try {
$hostname = "";
$username = "";
$password = "";
$db = new PDO("mysql:host=$hostname;dbname=topdecka_PTC",$username, $password);
$raw_result = $db->query('SELECT * FROM articles');
$result = $raw_result->fetchAll(PDO::FETCH_ASSOC);
return $result;
} catch (PDOException $e) {
echo "Error!: " . $e->getMessage() . "<br/>";
die();
}
?>
and my AJAX function:
$(document).ready(function() {
$.get( "db_queries/all_articles.php", function( data ) {
console.log( data );
});
});
You need to echo JSON encoded data:
Change this line:
return $result;
To:
echo json_encode($result);
I have read through dozens of similar questions on this website, and am having a lot of trouble trying to understand what is wrong with my code. I am trying to dynamically update select boxes based on the value of another one, but for some reason cannot seem to get any type of response data back once I post to PHP with Ajax.
JAVASCRIPT:
function toggleHiddenDIV()
{
var dc = document.getElementById("datacenter");
var dcVal = dc.options[dc.selectedIndex].value;
// Check if Datacenter selection has no Value selected
if(dcVal != '')
{
document.getElementById("hidden-options").style.display="block";
$.ajax({
type: "POST",
url: "handler.php",
data: { 'action_type': 'update_inventory_fields', id: dcVal },
success: function(response)
{
alert(response);
}
});
}
else
{
document.getElementById("hidden-options").style.display="none";
}
};
</script>
PHP:
if ($_POST['action_type'] == "update_inventory_fields")
{
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
if (empty($_POST["id"])) { return; }
}
$result = mysql_query("SELECT id, ip, block FROM ipv4 WHERE datacenter = " . $_POST["id"]);
$data = array();
while($row = mysql_fetch_array($result, true))
{
$data[] = $row;
};
return json_encode($data);
}
Don't call return (since you're not returning a function); just echo then content onto the page:
echo json_encode($data);
Change to this...no need to return, just echo, since youre outside of a function call
if ($_POST['action_type'] == "update_inventory_fields")
{
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
if (empty($_POST["id"])) { return; }
}
$result = mysql_query("SELECT id, ip, block FROM ipv4 WHERE datacenter = " . $_POST["id"]);
$data = array();
while($row = mysql_fetch_array($result, true))
{
$data[] = $row;
};
echo json_encode($data);
}
If the php code you posted is inside a function than you need to use echo functionname();
If the php code is not in a function, then just use echo json_encode($data);