1

How do you handle two echo responses from your PHP script with $.ajax() function.Im new to ajax and my code is not working.Here's my code: form.js

$(document).ready(function(e){
    $("#form").on('submit', function(e){
        e.preventDefault();
        var Form = new FormData(this);
        $.ajax({
            url: "uploader.php",
            type: "POST",
            data: Form,
            processData: false,
            contentType: false,
            success:function(data){
                alert(data[0]);
            }
        });
    }); 
});

And my uploader.php:

echo "stuff1";
//some other code.
echo "stuff2";

Wasn't is supposed to alert "stuff1"?...instead it doesn't send the request.

kalehmann
  • 4,821
  • 6
  • 26
  • 36
Joseph
  • 63
  • 1
  • 10
  • Possible duplicate of [Jquery/Ajax Form Submission (enctype="multipart/form-data" ). Why does 'contentType:False' cause undefined index in PHP?](https://stackoverflow.com/questions/20795449/jquery-ajax-form-submission-enctype-multipart-form-data-why-does-contentt) – Martin Zeitler Sep 09 '18 at 13:38

1 Answers1

1

Instead of parsing the plain text for results you should use JSON for response. And then on server side, you can use arrays to send multiple values in response.

$.ajax({
    url: "uploader.php",
    type: "POST",
    data: Form,
    dataType: "json", // <-- Add this param
    processData: false,
    contentType: false,
    success: function (data) {
        alert(data[0]);
    }
});

and On php's end, you can use json_encode() to convert the array to a json string.

$output = [];
$output[] = "stuff1";
//some other code.
$output[] = "stuff2";
echo json_encode($output);
Mohd Abdul Mujib
  • 13,071
  • 8
  • 64
  • 88