简体   繁体   中英

How does php handle ajax post request

Maybe I am just not as smart as I think I am but I really am having issues with aJax and PHP interacting with each other. I am trying to make a save method.

This is the PHP that I have. My only guess is that I am not checking the right things.

(this is a page called edit.php)

<?php
if(isset($_POST['text']) && isset($_GET['dir'])){
   $File = $_POST['location']; 
   $Handle = fopen($File, 'w') or die("can't open file");
   $Data = $_POST['text']; 
   fwrite($Handle, $Data); 
   fclose($Handle); 
}

?>

<input type="text" value="<?=$_GET['dir'];?>" id="saveValue"> This is the function that gets called when I push Ctrl and S

    function saveFile(){
var data = new FormData();
    data.append('text', e.getSession().getValue());
    data.append('location',$('#saveValue').val());
var url = $('#saveValue').val(); 
var split = url.split('/public_html'); 
    alert(split[1]);
var url = "edit.php?dir="+split[1];
  $.ajax({
    url: url,
    type: "post",
    data: data,

    success: function (data, textStatus, jqXHR) {
        if (data == "false") {
            console.log("There is a problem on the server, please try again later");    
        } else {
                //Do something with what is returned
                console.log("failed");
        }
    }
});      
};

I think that I am either checking the wrong thing or I am not submitting what I think I am. May I please get some help or at least some clarification on this.

I have read that I need to use $_REQUEST['text'] instead of $_POST but neither have worked.

IMO you are trying to mix up two request types GET as well as POST .

In your AJAX call the URL you specify doesn't contain the dir parameter, as a consequence the condition isset($_POST['text']) && isset($_GET['dir']) fails.

You cannot have edit.php?dir=foo because you can have request method either GET or POST`

Your server side script has an if() condition to check for POST parameters. As suggested by @Marcel Gwerder it would be like if(isset($_POST['text']) && isset($_POST['location']))

Happy to help.

I have fixed what was wrong with my code. Here is what I now have.

function getDir(){
var url = $('#saveValue').val(); 
    var split = url.split('/public_html'); 
    return split[1];
}; 


function saveFile(){
var datas = {
        'text': e.getValue(),
        'location':$('#saveValue').val()
        };
  $.ajax({
    url: "edit.php",
      type: 'POST',
      data: datas,
      success: function (data, textStatus, xhr) {
            errorReport(datas.toString());
      }
});      
};
function errorReport(data){
    var msg = document.createElement('p');
    msg.className = "msg";
    msg.innerHTML = data
    $('.error').append(msg);
    $('.msg').fadeIn('slow');
    setTimeout(function(){
        $('.msg').fadeOut("slow");
        $('.msg').remove();
    },9500);
};

and for the little bit of PHP that I had, I now have this. From what I can tell I was not sending the right kind of object through the form.

if(isset($_POST['text'])  && isset($_POST['location'])){
   $File = $_POST['location'];  
   $Handle = fopen($File, 'w') or die("can't open file");
   $Data = $_POST['text']; 
   fwrite($Handle, $Data); 
   fclose($Handle); 
} 

When using POST request with Ajax, some headers need to be set

  http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

This header makes php think of the data being submitted as a form submission. Now, the corresponding data can be handle in php as normal $_POST[] variables.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM