Javascript ile post işlemi

JAVASCRİPT 2023-12-19 23:30:09

Javascript ile post işlemi yaparken fetch ile veri gönderme ve gelen cevabı html olarak gösterme

javascript :

function sendFetch(url, formId, ajaxUrl, responsDiv){
    var myData = new FormData($('form#' + formId)[0]); 
    fetch(url + ajaxUrl, {
        method:"POST",
        body: myData
    })
    .then(response => {
        if (!response.ok) {
            throw new Error('Network response was not ok');
        }
        return response.json();
    })
    .then(result =>{

        if (result.type === "success") {
            if (result.url !== null) {
                goUrl(url + result.url);
            } else {
                document.querySelector(responsDiv).innerHTML = result.message;
            }

        } else if (result.type === "danger") {
            document.querySelector(responsDiv).innerHTML = result.message;
        } else if (result.type === "warning") {
            document.querySelector(responsDiv).innerHTML = result.message;
            goUrl(url + result.url,2);
        }else{
            document.querySelector(responsDiv).innerHTML = result.message;
        }
        
    })
    .catch(error =>{
        console.log(error);
    });
}


function goUrl(url, time = null) {
    if (time == null) {
        setTimeout(function () { location.href = url }, 0);
    } else {
        setTimeout(function () { location.href = url }, time * 1000);
    }

}

php :

function alert($type,$message,$url = null){
    $alert = (Object) [];
    $alert->type = $type;              
    $alert->message = `<div class="alert-'.$type.'">
    <span class="closebtn" onclick="this.parentElement.style.display=\'none\';">&times;</span> 
    <strong> Alert !</strong> <p>'.$message.'</p>
    </div>`;                       
    $alert->url = $url;
    echo json_encode($alert, JSON_UNESCAPED_UNICODE);
    
}
javascript post fecth ajax php

CONTACT ME

0 / 250 karakter