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

6
  • Why are you sending it as JSON? Commented May 18, 2018 at 9: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? Commented May 18, 2018 at 9:52
  • Please check if you pasted your Javascript code correctly: the quote marks are not balanced. Commented May 18, 2018 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"' Commented May 18, 2018 at 11:21
  • @dcorking update done, is this better? Commented May 18, 2018 at 11:34

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Good answer thank you, i think this will help others but unfortunately my problem still persists.
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.

9 Comments

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
the reason for this warning is its trying to convert the array to string in the json_encode process
Please check I have added console in there what you get in data variable?
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
Js Side Works? Now Issue is On PHP Side Right?
|
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.