1

I know ajax is easy to use with jquery, but here I am trying to understand ajax with core javascript, I am sending two values name and age from index.html to indexPhp.php, In console it shows this message XHR finished loading: POST "http://localhost:8080/delPro/indexPhp.php". but it is not showing any result in div, here is html, js and php script

<html>
<head>    
<link rel="stylesheet" type="text/css" href="style.css"/>
<script src="scripts.js"></script>
</head>        

<body>            
Name: <input type="text" id="name" name="name"><br><br>
Age:  <input type="text" id="age" name="age"><br><br>  
<button type="submit" value="Submit" onclick="showUser()">Submit</button>
<div id="resultDiv"></div>     
</body>        
</html>

Javascript

function showUser() {

var hr = new XMLHttpRequest();
var url= "indexPhp.php";   
var name= document.getElementById("name").value;
var age= document.getElementById("age").value;    

var vars = {Name: name, Age: age};

hr.open("POST",url,true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

hr.onreadystatechange = function(){

    if(hr.readyState == 4 && hr.status == 200){

        var return_data = hr.responseText;
        alert(hr.responseText);
        document.getElementById("resultDiv").innerHTML = return_data;
    }        
}
  hr.send(vars);

}

php script

if(isset($_POST['name']) && isset($_POST['age'])){

echo  $name = $_POST['name'] . " " . $age = $_POST['age'];    

}
2

2 Answers 2

1

Have you tried passing the data like this,

var vars = "Name="+name+"&Age="+age;

In your code you are sending the data as an object.

Sign up to request clarification or add additional context in comments.

2 Comments

yes i did this way also, using this way it's shows values in url
hr.open("POST",url,true); hr.send(vars); This won't be displaying the value in the url
0

Here is an ajax function I made sometimes ago. It can do both post and get and the use is just like you would use jQuery's ajax.

function ajax(options, timeout){
    method = options.method || "POST";
    url = options.url || "#";
    (!timeout) ? timeout = 10000 : timeout = timeout * 1000; 
    var request, timedOut = false, xhrTooLong, datas = "";
    try{
        request = new XMLHttpRequest();
    } catch ( error ) {
        try {
            request = new ActiveXObject( "Microsoft.XMLHTTP" );
        } catch ( error ) {
            return true;
        }
    }
    if(options.data){
        for( dat in options.data){
            (datas == "")?datas+= (method.toLowerCase()=="get"?"?":"")+dat+"="+
               options.data[dat]:datas+="&"+dat+"="+options.data[dat];
        }
    }
    if(method.toLowerCase() == "get" && datas.length > 0)
        url = url + datas;
    request.open(method, url, true);
    request.onreadystatechange = function() {
        if( request.readyState == 1 ) {
            xhrTooLong = setTimeout(function(){
                if(request.readyState == 1){
                    timedOut = true;
                    request.abort();
                    if(options.aborted) options.aborted(true);
                }
            }, timeout);
        }
        if(request.readyState == 4 && !timedOut){
            window.clearTimeout( xhrTooLong );
            if(options.complete) options.complete (true);
            if ( /200|304/.test( request.status ) ) {
                if(options.success) options.success(request.responseText);
            } else {
                if(options.error) options.error(request.status);
            }
        }
    }
    request.setRequestHeader( 'If-Modified-Since', '06 Oct 1970 00:00:00 GMT' );
    if(method.toLowerCase() == "get"){
        request.send( null );
    } else {
        if(!options.contentType){
            request.setRequestHeader( 'Content-type','application/x-www-form-urlencoded; charset=UTF-8' );
        } else {
            request.setRequestHeader( 'Content-type',options.contentType );
        }
        request.setRequestHeader( 'Accepts', '*' );
        request.send( encodeURI( datas ) );
    }
    return false;
}

Now you can rewrite showUser like this:

function showUser() {

    var url= "indexPhp.php";   
    var name= document.getElementById("name").value;
    var age= document.getElementById("age").value;

    var vars = {Name: name, Age: age};

    ajax({
        url: url,
        method: "post",
        data: vars,
        success: function(result){
            alert(result);
            document.getElementById("resultDiv").innerHTML = result;
        },
        error: function(){ alert("Failed!") },
        aborted: function(){ alert("Aborted!") },
        complete: function(){ alert("Complete!") }
    });

}

You could also pass in an optional timeout in seconds after closing the function braces in the ajax call.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.