Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am making an ajax call to a .php page where I am making a query to the database. However, when I echo a value from the .php page, the entire html file is returned rather than just the numerical value I need.

This is my ajax script:

<script type="text/javascript">

$(document).ready(function()
{
    $("#valuebutton").click(function()
    {
        var id1=$('.player1').val();
        $.ajax
    ({
        type: "POST",
        url: "updatevaluebox.php",
        data: ({g1: id1}),
        cache: false,
        success: function(value)
        {
            //alert(value);
            $('#valuebox').val(value);
        }
    });
    });
});
</script>

And this is the php page updatevaluebox.php:

<?php
    require("connect_db.php");
    $q="SELECT price FROM playerlist where id=".$_POST['g1'];
    $r=mysqli_query($dbc,$q);
    $price=mysqli_fetch_array($r,MYSQLI_NUM);
    mysqli_close($dbc);
    echo $price[0];
?>

Both files are in the same directory.

I have checked other answers to this question on stackoverflow but none seem to work.

The output I am getting from the alert statement looks like:

<html>

<head><title>

</title></head>

<body>

</body>

</html>5.5

The 5.5 at the end is the only value I need!

I have set the ajax dataType to text but even that doesn't help.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
963 views
Welcome To Ask or Share your Answers For Others

1 Answer

Yep! You need to remove any HTML in the connect_db.php file. I recommend storing a variable in that file checking if your connection was successful. For example:

connect_db.php

$isConnected = false;
$dbError = "";
if ($dbc=mysqli_connect('localhost','*****','*****','ff') {
    $isConnected = true;
} else {
    $dbError = mysqli_connect_error();
}

other files

require("connect_db.php");

if($isConnected) {
    //DO ALL YO STUFF!!
} else {
    //HANDLE THE ERROR AS YOU LIKE, LIKE PRINTING IT OUT
    echo $dbError;
}

Doing this will allow you to handle the DB logic in your files if it fails to connect so you may handle failed connections gracefully.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...