-3

Is it possible to make an ajax post without having an HTML form? And if it is how should i do it and what PHP variable is used to fetch the variable? The PHP is inside the fetched file. I'm not using any framework.

function ajax(instruction, push, url, callback){
 
 var xmlhttp; // the object for the httprequest
 
 if (window.XMLHttpRequest) {
            // code for IE7+, Firefox, Chrome, Opera, Safari
            xmlhttp = new XMLHttpRequest();
        } else {
            // code for IE6, IE5
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
  
  
  
  
        xmlhttp.onreadystatechange = function() { // every time the readystate changes
     
     
            ajaxLoad(xmlhttp.readyState); // Calls function with the ready state each time it uppdates
     

            if (xmlhttp.readyState == 4) { // status 200 = sucessfull page! NOT 404!  // 1 2 3 4 are states of the request (4 is when it's done)
   
          // When load bar is complete
  
  
  
  
          if(xmlhttp.status == 200){
     
        callback(xmlhttp.responseText); // goes to the callback function (from the argument "callback") and then passes the xmlhttp
     
    }
          else if(xmlhttp.status == 404){ // Could not find file
             
     ajaxError() // Function that will call the ajax but with the error file
    
    }else{}
       
    ajaxDone(); // activates all the nessesary js to check what to do with some parts of the site
            }
   else{}
   
        };
  
 
        xmlhttp.open(instruction,url, true); // sends a the var q to the next php file
        
  if(instruction === "GET"){
      xmlhttp.send('');             // Sends the request
  }
  else if(instruction === "POST"){
   
   xmlhttp.send(url);             // Sends the request
   
  }
  else{
   console.log("This ajax does not support " + instruction + " requests.");
  }
 
 
 
 
 
 if(push == true){ // Change the link to the url of the ajax with

  var urlPath = window.location.protocol + "//" + window.location.host + window.location.pathname; // where the host is on
  
  
  if(url == "home.php"){ // If it's the starting page REMOVE THE ?p= !!
           
       var urlPath = window.location.protocol + "//" + window.location.host + window.location.pathname;
            window.history.pushState({path:urlPath},'','./'); // an empty url push (!REMOVE THE DOT WHEN THE SITE IS HOSTED PROPERLY)  
      return; // exit's the function
  
  }else{}
  
  
        var newLink = "?p=" + url; // Gives us the link we want except that we don't want the .php
        newLink = newLink.substring(0, newLink.indexOf('.')); // makes a new string with character 0 to the dot! Will not include the ending of the file

           
  window.history.pushState({path:urlPath},'',newLink); // the push
  
    } 
    else{}
 
}
<a href="?p=page1" onclick="ajax('POST', true, 'page1.php', function(content){ document.getElementById('content_holder').innerHTML = content;});  return false;">To page 1</a>
Johan Sundman
  • 145
  • 1
  • 15

3 Answers3

1

You can find some answers here, about how to make Vanilla JS Ajax call: http://www.sitepoint.com/guide-vanilla-ajax-without-jquery

About to send without forms, you already have the response here: Send POST data using XMLHttpRequest

You can get your params server-side(php) with the global variables $_GET["your_param_name"] and $_POST["your_param_name"], they are arrays so I think you know how to use them.

Community
  • 1
  • 1
Clovis Portron
  • 556
  • 3
  • 7
1

Of course, you can make AJAX request in pure js, even jquery handle ajax request in pure js in behind.

JavaScript:

var ajax = {};
ajax.x = function () {
    var xhr;

    if (window.XMLHttpRequest) {

        xhr = new XMLHttpRequest();
    } else {

        xhr = new ActiveXObject("Microsoft.XMLHTTP");
    }
    return xhr;
};

ajax.send = function (url, callback, method, data, async) {
    if (async === undefined) {
        async = true;
    }
    var x = ajax.x();
    x.open(method, url, async);
    x.onreadystatechange = function () {
        if (x.readyState == 4) {
            callback(x.responseText)
        }
    };
    if (method == 'POST') {
        x.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
    }
    x.send(data)
};

ajax.get = function (url, data, callback, async) {
    var query = [];
    for (var key in data) {
        query.push(encodeURIComponent(key) + '=' + encodeURIComponent(data[key]));
    }
    ajax.send(url + (query.length ? '?' + query.join('&') : ''), callback, 'GET', null, async)
};

ajax.post = function (url, data, callback, async) {
    var query = [];
    for (var key in data) {
        query.push(encodeURIComponent(key) + '=' + encodeURIComponent(data[key]));
    }
    ajax.send(url, callback, 'POST', query.join('&'), async)
};

Call Ajax Method: I will recommend you to not use it in onclick.

ajax.get('ajax.php',{DATA_TO_PASS},function(response) {
   //Do something with response 
   console.log(response);
},true);

$_GET to receive the ajax data; OR:

ajax.post('ajax.php',{DATA_TO_PASS},function(response) {
   //Do something with response 
   console.log(response);
},true);

$_PSOT to receive the ajax data;

Meathanjay
  • 1,703
  • 16
  • 22
0

You don't need a form to use ajax post.

$.post( "test.php", { 'choices[]': [ "Jon", "Susan" ] } );

as the same way you are using form you can fetch the values from php using $_POST

Yasitha
  • 834
  • 2
  • 13
  • 39