How to get PHP data with JSON and AJAX

advertisements

I don't understand how to get data from PHP file with json and ajax. Help me please.

I tried:

addnews.tpl:

    $("#send").click(function(e){
    e.preventDefault();
    $.ajax({
        url: "news.php?addnews",
        type: "POST",
        data: {
            title: $("#title").val(),
            text: $("#text").val()
        },
        beforeSend: function() {
            $(".loading").css({
                "display": "inline"
            });
        },
        success: function() {

        }
    });
});

$("#send").click(function () {
    $.ajax({
        type: 'GET',
        url: "news.php?addnews",
        data: {},
        dataType: 'json',
        success: function(data) {
            $('.message').html(data.error);
        },
        error: function(xhr){
            $('.message').html('error fetching data');
        }
    });
});

news.php:

    if(isset($_GET['addnews'])) {
    if(!isset($_SESSION['id'])) {
        echo json_encode(array("error" => "error."));
    }
    $news->addNews($_SESSION['id'], $_POST['title'], $_POST['text']);
    $smarty->display("template/addnews.tpl");
}

Another question: how to hide json array (text) on the page?


Untested

Either choose post or get. Post has been used in the below code.

addnews.tpl:

$("#send").click(function () {
    $.ajax({
        type: 'POST',
        url: "news.php",
        data: {
        title: $("#title").val(),
        text: $("#text").val(),
        addnews: //your add news value
        },
        dataType: 'json',
        success: function(data) {
            $('.message').html(data);
        },
        error: function(xhr){
            $('.message').html('error fetching data');
        }
    });
});

News.php

if(isset($_POST['addnews'])) {
    if(!isset($_SESSION['id'])) {
        echo json_encode("error");
    }else{
    $news->addNews($_SESSION['id'], $_POST['title'], $_POST['text']);
    // $smarty->display("template/addnews.tpl");
    echo json_encode("success");
    }
}