skip to Main Content

I can’t understand the problem when sending data in httpc.send I tried JSON.stringify but nothing to do the return is always null. The different subjects concerning ajax do not have the area to have a problem.

var data = {
    concat_operation: params
};
var httpc = new XMLHttpRequest(); // simplified for clarity
var url = "calcul.php";


httpc.onreadystatechange = function() { //Call a function when the state changes.
    if(httpc.readyState == 4 && httpc.status == 200) { // complete and no errors
        console.log(httpc.response); // some processing here, or whatever you want to do with the response
        // console.log(JSON.parse(httpc.responseText)); // some processing here, or whatever you want to do with the response
        var serverResponse = JSON.parse(httpc.responseText);
        console.log(serverResponse);
    }
};
httpc.open("POST", url, true); // sending as POST
console.log(data);
httpc.send(data);

However, I managed to do it in Jquery. A processing must be supported by Jquery that I haven’t thought of?

var data = {
    concat_operation: concat_number
};
$.post("calcul.php", data , function(response){
    var result = response.result;
    $('.parent').before(`<div class="result">${result}</div>`);
}, "json")

3

Answers


  1. You have to set the headers correctly and send the stringified data

     httpc.open("POST", url, true); // sending as POST
     httpc.setRequestHeader("Content-type", "application/json");
     httpc.send(JSON.stringify(data));
    
    Login or Signup to reply.
  2. You should be able to happily send data to a PHP script using a FormData object which can then be processed in PHP by accessing $_POST variables like this

    <?php
        
        #----------
        #calcul.php
        #----------
        
        if( $_SERVER['REQUEST_METHOD']=='POST' && isset( $_POST['concat_operation'] ) ){
            $op=$_POST['concat_operation'];
            $response=array();
            
            /* do stuff with supplied data */
            $response['foo']='bar';
            
            
            header('Content-Type: application/json');
            exit(json_encode($response));
        }
    ?>
    

    The Fetch / Ajax code:

    let fd=new FormData();
        fd.set('concat_operation',params);
        
    fetch('calcul.php',{ method:'post',body:fd })
        .then(r=>r.json())
        .then(json=>{
            console.log(json)
            /* do stuff with response */
        })
        .catch(alert)
    

    This would send a single POST parameter named concat_operation with whatever data is in params and within the PHP code would be accessed using $_POST['concat_operation'] – given that the URL supplied to the fetch call does not begin with either a slash or ./ means that both scripts (calcul.php and script sending ajax request) are in the same directory. Use the console tools to check for errors and to analyse the HTTP request

    Login or Signup to reply.
  3. Yes, you lost something, the param type of send method could be String ,FormData,Blob and so on,but not an Object,In addition you must set Conten-Type to let the service knowing your data type ,the function transformData in below will return a String to fit the content-type setting.

    var data = {
      concat_operation: params
    };
    var httpc = new XMLHttpRequest(); // simplified for clarity
    var url = "calcul.php";
    httpc.setRequestHeader('Conten-Type', 'application/x-www-form-urlencoded')
    httpc.onreadystatechange = function() { //Call a function when the state changes.
      if (httpc.readyState == 4 && httpc.status == 200) { // complete and no errors
        console.log(httpc.response); // some processing here, or whatever you want to do with the response
        // console.log(JSON.parse(httpc.responseText)); // some processing here, or whatever you want to do with the response
        var serverResponse = JSON.parse(httpc.responseText);
        console.log(serverResponse);
      }
    };
    httpc.open("POST", url, true); // sending as POST
    console.log(data);
    httpc.send(transformData(data));
    
    function transformData(data) {
      if (typeof data === 'object') {
        let res = ''
        for (const key in data) {
          if (res) res += '&'
          res += key + '=' + data[key]
        }
        return res
      }
      return data
    }
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search