简体   繁体   中英

Undefined PHP output from ajax call

I'm looking to create a PDF file through ajax via TCPDF. Everything works perfectly, PDF is saved in the server I pass the URL to my HTML

$responseArray = array('id' => 'Success', 'message1' => 'Hello', 'message2' => '/pdfgen/genpdf/'.$filetitle.'.pdf');
$encoded = json_encode($responseArray);             echo $encoded;

Then I get redirect. The problem is although my browser console tab shows what PHP has sent which is

{"id":"Success","message1":"Hello","message2":"/pdfgen/genpdf/1703419677.pdf"}

back on the HTML file I can't assign the URL to a variable.

it just prints undefined.

$.ajax({
    type: 'POST',
    url: "path to php",
    data: ({mob: mob}),
    dataType: 'json',
}).done(function(data) {
    console.log(data);
    var id = data.id;   
    var message1 = data.message1;
    var message2 = data.message2;
});

just replace data with response

$.ajax({
        type: 'POST',
        url    : "path to php",
        data: ({mob: mob}),
        dataType: 'json',
        })
.done(function(response) {
        console.log(data);
        var id = response.id;   
        var message1 = response.message1;
        var message2 = response.message2;
        alert(message2 );
        });

Replace your code response.id , response.message1 and response.message2 with
data.id, data.message1 and data.message2 . SInce you have used data in your success function

Hope help:

$.ajax({
    type: 'POST',
    url: "path to php",
    data: ({mob: mob}),
    dataType: 'json',
}).done(function(response) { <-- edit
    console.log(response); <-- edit
    var id = response.id;   
    var message1 = response.message1;
    var message2 = response.message2;
    alert(message2);
});
$.ajax({
    url: 'path to php',
    type: 'post',
    data: {mob: mob},
    dataType: 'json',
    success: function(response) {
        console.log(response); 
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM