Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

php - Ajax call returns entire page rather than just the echo value

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...