Jitesh Sojitra
Jitesh Sojitra

Reputation: 4043

Can't run SQL query via AJAX request, same type of AJAX query used and works fine everywhere other than this

I'm using this AJAX call everywhere else and it works like a charm but only this gives problem. I don't understand what is the problem? Why I'm getting "Error retried record:" still I don't see any problem and so easy.

PS: I echoed the values at AJAX side response and getting all three values there but database gives problem. More, same SQL query works fine at database side but when it deals with AJAX and PHP, it gives problem.

Values passed fine:

id1=get-version&id2=machine055&id3=vmlab

Database query seems fine:

SELECT `version` FROM `table1` where `machine` = 'machine055'

PHP+UI:

serverChange.on('change', function(){
            $("#progress").show();
            var selectedServer = $(this).val();

            $.ajax({
                type: "POST",
                url: "/web/scripts.php",
                data: { id1: "get-version", id2: selectedServer, id3: "vmlab" },
                success:function(msg){
                    $("#progress").hide();
                    alert(msg);
                }
            });

        });

PHP+Ajax:

if ($_POST['id1'] == "get-version" && $_POST['id3'] == "vmlab") {

    $conn = mysqli_connect("localhost", "root", "pwd", "db");
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }

    $sql = "SELECT `version` FROM `table1` where `machine` = '" .trim($_POST['id2']). "'";
    if ($conn->query($sql) === TRUE) {
        echo "Machine retrieved successfully.";
    } else {
        echo "Error retried record: " . $conn->error;
    }

Upvotes: 3

Views: 315

Answers (1)

Jitesh Sojitra
Jitesh Sojitra

Reputation: 4043

I tried different approach and its working fine so not exploring much, here is the solution:

    $conn = mysqli_connect("localhost", "root", "pwd", "db");
     if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }

    $sql = "SELECT `version` FROM `table1` where `machine` = '" .trim($_POST['id2']). "'";
    $result = mysqli_query($conn, $sql);

    while($row =  mysqli_fetch_array($result)) {
        $rows[] = $row['version'];
    }

    echo ($rows[0]);

    $conn->close();

Thanks all for reading the issue and resolution.

Upvotes: 1

Related Questions