0

I have my php file on a server that retrieves data from my database.

<?php
$servername = "myHosting";
$username = "myUserName";
$password = "MyPassword";
$dbname = "myDbName";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, name, description FROM tableName;";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
    $row_number = 0;
    while($row = $result->fetch_assoc()) {
        $row_number++;
        echo $_GET[$row_number. ";". $row["id"]. ";". $row["name"]. ";". $row["description"]. "<br>"];
    }
} else {
    echo "0 results";
}
$conn->close();
?>

Unfortunately, I do not know how to receive data from a php file using javascript. I would like the script in javascript to display the received data in the console in browser.

The script written in javascript is Userscript in my browser extension(tampermonkey) and php file is on my server. I've tried to use ajax, unfortunately without positive results. (the php script works as expected).

JS(not working):

    $.ajax({
        url: 'https://myserver.com/file.php', 
        type: 'POST',
        success: function(response) {
            console.log(response);
        }
    }); 

2 Answers2

1

The code within the loop is a little screwy

$_GET[$row_number. ";". $row["id"]. ";". $row["name"]. ";". $row["description"]. "<br>"]

that suggests a very oddly named querystring parameter which is not, I think, what was intended.

Instead, perhaps try like this:

<?php

    $servername = 'myHosting';
    $username = 'myUserName';
    $password = 'MyPassword';
    $dbname = 'myDbName';
    $conn = new mysqli($servername, $username, $password, $dbname);

    if( $conn->connect_error ) {
        die( 'Connection failed: ' . $conn->connect_error );
    }

    $sql = 'select `id`, `name`, `description` from `tablename`;';
    $result = $conn->query($sql);

    if( $result->num_rows > 0 ) {

        $row_number = 0;

        while( $row = $result->fetch_assoc() ) {
            $row_number++;
            /* print out row number and recordset details using a pre-defined format */
            printf(
                '%d;%d;%s;%s<br />',
                $row_number,
                $row['id'],
                $row['name'],
                $row['description']
            );
        }
    } else {
        echo '0 results';
    }

    $conn->close();
?>

A full example to illustrate how your ajax code can interact with the db. The php code at the top of the example is to emulate your remote script - the query is more or less the same as your own and the javascript is only slightly modified... if you were to change the sql query for your own it ought to work...

<?php

    error_reporting( E_ALL );
    ini_set( 'display_errors', 1 );

    if( $_SERVER['REQUEST_METHOD']=='POST' ){
        ob_clean();

        /* emulate the remote script */
        $dbport =   3306;
        $dbhost =   'localhost';
        $dbuser =   'root';
        $dbpwd  =   'xxx';
        $dbname =   'xxx';

        $db = new mysqli( $dbhost, $dbuser, $dbpwd, $dbname );      
        $sql= 'select `id`, `address` as `name`, `suburb` as `description` from `wishlist`';


        $res=$db->query( $sql );
        $row_number=0;

        while( $row=$res->fetch_assoc() ){
           $row_number++;

            /* print out row number and recordset details using a pre-defined format */
            printf(
                '%d;%d;%s;%s<br />',
                $row_number,
                $row['id'],
                $row['name'],
                $row['description']
            );
        }


        exit();
    }
?>
<!DOCTYPE html>
<html lang='en'>
    <head>
        <meta charset='utf-8' />
        <script src='//code.jquery.com/jquery-latest.js'></script>
        <title>Basic Ajax & db interaction</title>
        <script>
            $( document ).ready( function(){
                $.ajax({
                    url: location.href, 
                    type: 'POST',
                    success: function( response ) {
                        console.log( response );
                        document.getElementById('out').innerHTML=response;
                    }
                }); 
            } );
        </script>
    </head>
    <body>
        <div id='out'></div>
    </body>
</html>
Professor Abronsius
  • 33,063
  • 5
  • 32
  • 46
  • did that little change work though is the important bit.. seems to me that the javascript works fine so I think the error in the PHP was your issue – Professor Abronsius Mar 19 '19 at 16:08
  • Unfortunately, no ... when I open a PHP file, I have the entire list received from the database, so PHP file is fine, but javascript can not see any data from php. – Marcin Frąckiewicz Mar 19 '19 at 16:16
  • before you can get the PHP file to provide data to the AJAX ... your ajax must actually work. You jumped right to post and assumed failure from php. but you never checked the ready state of the ajax request to allow getting your values. Remember that ajax is not continuous, the "request/receipt" delay has to be accounted for along with the "when the response is received, do this". Grab a generic AJAX from somewhere. Make that work. Then integrate it. – TheSatinKnight Mar 20 '19 at 02:22
  • @RamRaider I still can't get any data from my php file... $.ajax({ url: 'test-scripts-marcin.000webhostapp.com/y.php', type: 'POST', success: function(response) { console.log(response); } }); – Marcin Frąckiewicz Mar 20 '19 at 16:44
  • From where are you trying to run this ajax script - your local development machine or on the actual webhost? – Professor Abronsius Mar 20 '19 at 19:17
  • @RamRaider from tampermonkey, I need to make userscript – Marcin Frąckiewicz Mar 21 '19 at 01:31
  • I have never used, nor seen, Tampermonkey but have had a quick look just now. Is jQuery available for your "userscript"? – Professor Abronsius Mar 21 '19 at 07:17
0

Hi you can do it this way:

your php script:

if (isset($_POST["action"])) {
        $action = $_POST["action"];
        switch ($action) {
            case 'SLC':
                if (isset($_POST["id"])) {
                    $id = $_POST["id"];
                    if (is_int($id)) {
                        $query = "select * from alumni_users where userId = '$id' ";
                        $update = mysqli_query($mysqli, $query);
                        $response = array();
                        while($row = mysqli_fetch_array($update)){
                        .......
                        fill your response here

                        }
                       echo json_encode($response);
                    }
                }
                break;

        }
    }

Where action is a command you want to do SLC, UPD, DEL etc and id is a parameter

then in your ajax:

function getdetails() {
    var value = $('#userId').val();
   return $.ajax({
        type: "POST",
        url: "getInfo.php",
        data: {id: value}
    })

}

call it like this:

getdetails().done(function(response){
var data=JSON.parse(response);
if (data != null) {
//fill your forms using your data
}
})

Hope it helps

stan chacon
  • 768
  • 1
  • 6
  • 19
  • I still can't get any data from my php file... $.ajax({ url: 'https://test-scripts-marcin.000webhostapp.com/y.php', type: 'POST', success: function(response) { console.log(response); } }); – Marcin Frąckiewicz Mar 20 '19 at 16:43
  • @MarcinFrąckiewicz click the link you have posted in the last comment it return a json array – stan chacon Mar 20 '19 at 17:05
  • @MarcinFrąckiewicz i try to get the response from my pc in order to edit my answer and there was a CORS Policy that block the request check this link to get some information about it https://stackoverflow.com/questions/46522749/how-to-solve-redirect-has-been-blocked-by-cors-policy-no-access-control-allow – stan chacon Mar 20 '19 at 17:36