Return string from PHP and alert jQuery response

how to get value from ajax response in php
jquery ajax post json response example
how to return json data from php to ajax
jquery ajax post example php
how to get array response in jquery ajax
ajax json response php
jquery post json example
jquery ajax return array from php

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:

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.

jQuery.get(), A plain object or string that is sent to the server with the request. success As of jQuery 1.5, all of jQuery's Ajax methods return a superset of the Alert the results from requesting test.php (HTML or XML, depending on what was returned). Return JSON response from AJAX using jQuery and PHP JSON stands for JavaScript Object Notation, it is a data interchange format which is also been used to passing data from the server. It is the best and effective way when need to return multiple values as a response from the PHP script to the jQuery.

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.

Return JSON response from AJAX using jQuery and PHP, Directly returning an Array is not possible from AJAX as a response you need to convert it into the valid format (XML or JSON). So here's my issue, I am using AJAX (jQuery) to post a form to process.php but the page actually needs to echo out a response such as apple or plum. I'm not sure how to take the response from proce

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

jQuery post() Method, post() Method. ❮ jQuery AJAX Methods alert("Data: " + data + "\nStatus: " + status); }); }); Change the text of a <div> element using an AJAX POST request:. How could I return a variable from php in the success part of ajax jquery? This would be like what my php page would look like (which the ajax code refers to):

jQuery.post(), urlA string containing the URL to which the request is sent. As of jQuery 1.5, all of jQuery's Ajax methods return a superset of the XMLHTTPRequest object. for this request var jqxhr = $.post("example.php", function() { alert("success"); })  I want to manipulate that data and return to to the calling jQuery script. How to return data from PHP to a jQuery ajax call a comma-separated string return

Can't get a JSON object in response to an Ajax request with wp_ajax , log of my "posts" var I get a string 'Array'. No matter how I pass the $list variable in PHP it will always return a string. The query returns posts elsewhere, so it's not  Thank you for learning our post about jQuery AJAX Post Example with PHP and JSON! RELATED TUTORIAL: PHP, MySQL and AJAX CRUD Tutorial – Step by Step Guide! If you think our work is helpful, please share it to your friends!

Admin Ajax is returning 0, It was not the jQuery as such though I have improved that, it was the data:​dataString, success: function(data){ console.log(data); }, error: function() { console.log("Error"); } });. Because in wp-admin/admin-ajax.php is handler for action variable: 'data': form_data }; $.post(ajaxurl, data, function(response) { alert(response); });. The return statement stops the execution of a function and returns a value from that function. Read our JavaScript Tutorial to learn all you need to know about functions. Start with the introduction chapter about JavaScript Functions and JavaScript Scope.

Comments
  • Why are you sending it as JSON?
  • @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?
  • Please check if you pasted your Javascript code correctly: the quote marks are not balanced.
  • 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 update done, is this better?
  • Good answer thank you, i think this will help others but unfortunately my problem still persists.
  • 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?