简体   繁体   中英

How to properly use JSON to get number of rows from MYSQL database from php file?

I am having difficulty with properly setting up JSON post to get number of rows from MYSQL database from a php file. I am getting "undefined" alert, when I am looking to alert the number of rows as an integer. I have been using a different stackoverflow post to try to build this Get variable from PHP file using JQuery/AJAX .

Here is the ajax call:

// check number of records in Mine
$.ajax({
    url: 'pyrAddToMine.php',
    type: 'POST',
    success : function (result) {
    alert(result['ajax']); // "Hello world!" alerted
    console.log(result['numRec']) // The value of your php $row['numRec'] will be displayed
    },
    error : function () {
        alert("error");
    }
});

Here is the php code in pyrAddToMine.php: mysql_select_db($database_cms_test, $cms_test); $query = "SELECT * FROM $favUserTableName "; $result = mysql_query($query) or die(); $row = mysql_fetch_array($result); $num_records = mysql_numrows($result);

IF ($num_records >= 15){
    $numRec = array(
        'ajax' => 'Hello world!',
        'numRec' => $num_records,
            );
    echo json_encode($numRec);
    exit;
}

Here are more details on the php file:

<?php
require_once('../Connections/cms_test2.php');

...

mysql_select_db($database_cms_test, $cms_test);
$query = "SELECT * FROM `$favUserTableName`";
$result = mysql_query($query) or die();
$row = mysql_fetch_array($result);
$num_records = mysql_numrows($result);

IF ($num_records >= 15){

    $numRec = array(
        'ajax' => 'Hello world!',
        'numRec' => $num_records,
    );
    echo json_encode($numRec);

    exit;
}
...

?>

Hello you forgot to specify the datatype

   $.ajax({
        url : 'myAjaxFile.php',
        type : 'POST',
        data : data,
        dataType : 'json',
        success : function (result) {
           alert(result['ajax']); // "Hello world!" alerted
           console.log(result['advert']) // The value of your php $row['adverts'] will be displayed
        },
        error : function () {
           alert("error");
        }
    })

if you do not set required options for accepting json, you recieve an string that contain ajax format and you did not recieve an object in javascript

$.ajax({
    url: 'pyrAddToMine.php',
    type: 'POST',
    /* required for accept json for ajax */
    accepts:'application/json',
    dataType:'json',
    /* */
    success : function (result) {
    alert(result['ajax']); // "Hello world!" alerted
    console.log(result['numRec']) // The value of your php $row['numRec'] will be displayed
    },
    error : function () {
        alert("error");
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM