1

Hi this is my first time posting here and I need a bit of help, I am having problem echoing back the result from php to ajax. I want to show the filename once new canvas is created and store to server.

AJAX

                    $.ajax({
                        url: 'save_map.php',
                        data: { img_data:img_data },
                        type: 'post',
                        dataType: 'json',
                        success: function (response) {
                        window.location.reload();

                        }

From this PHP I want to print the name of new image that has been just created. I want to get the string value created in $filename and then print it.

PHP

<?php 

    $result = array();
    $imagedata = base64_decode($_POST['img_data']);
    $filename = md5(date("dmYhisA"));
    //Location to where you want to created sign image
    $file_name = './doc_map/'.$filename.'.png';
    file_put_contents($file_name,$imagedata);
    $result['status'] = 1;
    $result['file_name'] = $file_name;
    echo json_encode($result);


?>

1 Answers1

2

You are reloading the page after a successful request. You should use the response variable to display whatever you return back from your PHP code.

   success: function (response) {
   window.location.reload();
   }

Try instead:

   success: function (response) {
   alert(response.file_name);
   }
Dunams
  • 112
  • 1
  • 10
  • I tried this and it throws [object Object] in alert. I am pretty new to ajax – Ruz Maharjan Oct 06 '18 at 00:54
  • That is because your response is a json object as specified in your dataType parameter. That's not an error, try response.file_name – Dunams Oct 06 '18 at 01:00
  • @RuzMaharjan `response` is a JSON object, you need to access it. https://stackoverflow.com/questions/10895306/how-to-access-json-object-name-value – user3783243 Oct 06 '18 at 01:01