2

I'm trying to do something which should be really simple:

jQuery post -> which will return a string from the server -> alert string?

But for the life of me I cannot get the alert to display the string, I get object Object or a warning,

What am I doing wrong here?

Results:

JSON.parse: unexpected character at line 1 column 2 of the JSON data

exception: cyclic object

[object Object]

Update Php code:

public function fileupload(){
    $uniqueID = request('uniqueId');
    if($uniqueID != ''){
         echo 'Works'
    }
    else{
         echo 'Failed'
    }
}

Updated jQuery Code: alert is on the last block of code

$(function () {
  
   $('.fileupload').fileupload({
      
      headers: {
      'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
      },
      maxFileSize: 3000000,
      acceptFileTypes:  /(\.|\/)(pdf|jpeg)$/i,
      dataType: 'json',
      done: function (e, data) {
         $.each(data.result.files, function (index, file) {
            $('<p/>').text(file.name).appendTo(document.body);          
         });           
      },
         // Required for Progress bar
      progress: function (e, data) {
         var progress = parseInt(data.loaded / data.total * 100, 10);
         $(this).closest("div").find("div.bar").css(                                                   
            'width', progress + '%'            
         );
         // update text in progress bar
        $(this).closest("div").find("div.percentage").text(progress + '%');        
      }
      // This is required for displaying errors
      }).bind('fileuploadsubmit', function (e, data) {
         data.formData = {
            'uniqueId': $('.uniqueFileId').val()
         };
         
      }).on('fileuploadadd', function (e, data) {
         data.context = $('<div/>').appendTo('#files');
         $.each(data.files, function () {
         var node = $('<p/>').append($('<span/>'));     
         node.appendTo(data.context);
      });
      
      // This is also required for displaying errors 
      }).on('fileuploadprocessalways', function (e, data) {
          
         alert(data);
      
         var index = data.index,
            file = data.files[index],
            node = $(data.context.children()[index]);
            
         if (file.error) {
            node.append($('<span style=\'color:red; \'"/>').text(file.name +' '+ file.error + ',file must be .pdf or .jpg'));
          
         }
      });
   });

Response from php:

updated

Community
  • 1
  • 1
Jelly Bean
  • 1,161
  • 1
  • 11
  • 22
  • Why are you sending it as JSON? – VTodorov May 18 '18 at 09:47
  • @VTodorov Please clarify what you mean? i do not understand, are you referring to json_encode(); if so I am assuming that is how it should be sent, if I am wrong could you post an example of how it should be done? – Jelly Bean May 18 '18 at 09:52
  • Please check if you pasted your Javascript code correctly: the quote marks are not balanced. – dcorking May 18 '18 at 10:22
  • Please post more of your code : in particular the code that assigns data. Also follow normal troubleshooting steps, simplify your code until it does work. For example change your php to something like `echo '"Hello world"'` – dcorking May 18 '18 at 11:21
  • @dcorking update done, is this better? – Jelly Bean May 18 '18 at 11:34
  • Possible duplicate of [How to upload multiple files using PHP, jQuery and AJAX](https://stackoverflow.com/questions/19295746/how-to-upload-multiple-files-using-php-jquery-and-ajax) – dcorking May 19 '18 at 21:28

3 Answers3

1

You should try the following changes :

$msg = 'Hello';
echo json_encode($msg);

Return works if you are using the returned value within PHP functions. In your case you are communicating within PHP and javascript. Ajax default behavior outputs whatever you echo/print in php.

Kawaljeet Singh
  • 357
  • 1
  • 5
1

What Your Issue is you are not specifying a key for your message.

php:

public function fileupload(){
    $uniqueID = request('uniqueId');
    if($uniqueID != ''){
         echo json_encode(array("msg" => 'Works'));
    }
    else{
         echo json_encode(array("msg" => 'Failed'));
    }
}

jQuery:

$(function () {

   $('.fileupload').fileupload({

      headers: {
      'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
      },
      maxFileSize: 3000000,
      acceptFileTypes:  /(\.|\/)(pdf|jpeg)$/i,
      dataType: 'json',
      done: function (e, data) {
         $.each(data.result.files, function (index, file) {
            $('<p/>').text(file.name).appendTo(document.body);          
         });           
      },
         // Required for Progress bar
      progress: function (e, data) {
         var progress = parseInt(data.loaded / data.total * 100, 10);
         $(this).closest("div").find("div.bar").css(                                                   
            'width', progress + '%'            
         );
         // update text in progress bar
        $(this).closest("div").find("div.percentage").text(progress + '%');        
      }
      // This is required for displaying errors
      }).bind('fileuploadsubmit', function (e, data) {
         data.formData = {
            'uniqueId': $('.uniqueFileId').val()
         };

      }).on('fileuploadadd', function (e, data) {
         data.context = $('<div/>').appendTo('#files');
         $.each(data.files, function () {
         var node = $('<p/>').append($('<span/>'));     
         node.appendTo(data.context);
      });

      // This is also required for displaying errors 
      }).on('fileuploadprocessalways', function (e, data) {
console.log(data);



         alert(JSON.parse(data));

         var index = data.index,
            file = data.files[index],
            node = $(data.context.children()[index]);

         if (file.error) {
            node.append($('<span style=\'color:red; \'"/>').text(file.name +' '+ file.error + ',file must be .pdf or .jpg'));

         }
      });
   });

Changes:

1) PHP Code to return a valid JSON else js will treat it as payload. 2) Parse Returning Object and you will have that JSON object in an alert method.

Hope this stats your problem.

  • hi thanks for your post, I have made changes according to your suggestion bud sadly still get JSON.parse: unexpected character at line 1 column 2 of the JSON data warning and nothing is alerted – Jelly Bean May 21 '18 at 07:11
  • the reason for this warning is its trying to convert the array to string in the json_encode process – Jelly Bean May 21 '18 at 07:58
  • Please check I have added console in there what you get in data variable? – Muhammad Zubair Saleem May 21 '18 at 08:01
  • it returns: JSON ''msg'':Works, payload 'msg'':Works im struggling to access it, no need to parse on jquery side because data type is set to json its already done, currently looking at other options to display an error if unique id is empty – Jelly Bean May 21 '18 at 08:31
  • Js Side Works? Now Issue is On PHP Side Right? – Muhammad Zubair Saleem May 21 '18 at 08:38
  • To be honest im not sure at this point im getting the message which means its received from php so i dont think php is the issue, rather the issue currently is accessing the message so i can alert it, e.g data.msg, data['msg'], data[0].msg I dont know how to access the response so that i can alert "msg" – Jelly Bean May 21 '18 at 08:42
  • If Json i slaready parsed as you said in earlier message. try using console.log(data); console.log(data.msg); you will get what you needed when you have just put that string in alert if didn't work please share fiddle link for that – Muhammad Zubair Saleem May 21 '18 at 08:44
  • updated image to display what is returned, the same is returned in the _response result – Jelly Bean May 21 '18 at 09:00
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/171448/discussion-between-muhammad-zubair-saleem-and-jelly-bean). – Muhammad Zubair Saleem May 21 '18 at 09:01
0

According to the documentation, the data object passed to the fileuploadprocessalways handler doesn't contain the ajax response from the server's upload handler.

Instead it contains

two arrays:

files - which contains the result of the process applied.

originalFiles - the original uploaded files.

https://github.com/blueimp/jQuery-File-Upload/wiki/Options#processing-callback-options

Perhaps you meant to write a handler for the done callback. https://github.com/blueimp/jQuery-File-Upload/wiki/Basic-plugin

dcorking
  • 1,146
  • 1
  • 14
  • 24