OlevAbel
OlevAbel

Reputation: 211

ajax success doesnt alert anything

I have an AJAX request and if get id succeeds I would like to alert the data.

If I print_r my PHP function I get the correct result.

My ajax:

$.ajax({
            type: "GET",
            url: "getQuestions.php",
            datatype: "json",
            data:{
                compid:  id[4].innerHTML
            },
            success: function(response){
                alert(response);
            }

        });

My getQuestions.php:

<?php
include "functions.php";

getQuestions($_GET['compid']);

My function getQuestions($compid) in functions.php:

function getQuestions($compid){
    $int=intval($compid);
    $vastus=array();
    $conn = dbconnect();
    $sql="SELECT * FROM bet_question WHERE compid = $int";
    $result = $conn->query($sql);
    if ($result->num_rows > 0) {
        while($row = $result->fetch_assoc()) {
            array_push($vastus,$row);
        } 
    } else {
        echo "Error: " . $sql . "<br>" . $conn->error;
    }
    return  json_encode($vastus);
}

If I do print_r(getQuestions("some valid id")) in getQuestion.php I get valid result and if I do var_dump($_GET['compid']) in getQuestion I'll get the correct id from ajax request.

If I check if the request is sent using inspect elements I get that request is sent with correct params, but the response is empty.

Upvotes: 0

Views: 56

Answers (2)

Fredmat
Fredmat

Reputation: 958

You don't have to return the data, use echo instead, and set content type:

function getQuestions( $compid ) {

    $int=intval($compid);
    $vastus=array();
    $conn = dbconnect();
    $sql="SELECT * FROM bet_question WHERE compid = $int";
    $result = $conn->query($sql);

    if ($result->num_rows > 0) {

        while($row = $result->fetch_assoc()) {

            array_push($vastus,$row);

        }

    } else {

        echo "Error: " . $sql . "<br>" . $conn->error;

    }

    @header( 'Content-Type: application/json' );
    echo json_encode( $vastus );
    exit;

}

Hope it helps

Upvotes: 0

Narendrasingh Sisodia
Narendrasingh Sisodia

Reputation: 21437

Instead of return you need to use echo and it should be updated as

if ($result->num_rows > 0) {
        while($row = $result->fetch_assoc()) {
            array_push($vastus,$row);
        } 
          echo json_encode($vastus);
    } else {
        echo "Error: " . $sql . "<br>" . $conn->error;
    }
    exit;

Upvotes: 4

Related Questions