javascripthtmlajaxurl

How to send very long data in ajax URL?


I am using PHP and ajax together to access data from user and insert into database. The problem is that it works fine with small string but when I try to send data on 10000 characters browser prompts an error saying url to long.. I can make change in PHP but I want it to be dynamic so I have to it using this way only. Please help me.

function submitQuestion(){
    var x=document.forms['Ask']['title'].value;
    var y=document.forms['Ask']['description'].value;
    if(x.length ==  0 || y.length == 0){
        alert('Insufficient Data');
    }else{

        startLoading();
        console.log(y);
        var xhttp = new XMLHttpRequest();
        xhttp.onreadystatechange = function(){
            if(this.readyState == 4 && this.status==200){
                console.log(this.responseText);
                if(this.responseText == "All Done"){
                    clearInterval(startLoadingClearInt);
                    alert("data Inserted");
                    // window.location.replace('../profile/userprofile.php');
                }
            }
        };

        //here x is very inn some cases and produces an error
        xhttp.open("POST","./submitQuestion.php?title="+x+"&description="+y, true);
        xhttp.send();
    }
}

Solution

  • You cannot transfer large data via url (as messerbill said). You have to send them in the Body:

    function submitQuestion(){
        var x=document.forms['Ask']['title'].value;
        var y=document.forms['Ask']['description'].value;
        if(x.length ==  0 || y.length == 0){
            alert('Insufficient Data');
        }else{
    
            startLoading();
            console.log(y);
            var xhttp = new XMLHttpRequest();
            xhttp.onreadystatechange = function(){
                if(this.readyState == 4 && this.status==200){
                    console.log(this.responseText);
                    if(this.responseText == "All Done"){
                        clearInterval(startLoadingClearInt);
                        alert("data Inserted");
                        // window.location.replace('../profile/userprofile.php');
                    }
                }
            };
    
            //here x is very inn some cases and produces an error
            xhttp.open("POST","./submitQuestion.php", true);
            xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
            xhttp.send("title="+x+"&description="+y");
        }
    }
    

    inside the PHP-Script you get the data via the $_POST Array, not via the $_GET Array!