简体   繁体   中英

Pass a return value from php to js

I have 3 files main.php, action.js and ajax.php and i successfully changed the content on click of some divs from main.php to some of ajax.php with a ajax call in my javascript file. It looks like this:

var value = $(this).attr("id");

$.ajax({
    type: 'get',
    url: "ajax.php",
    data: {
        auto_value: value
    },
    success: function(response) {
        $('.gridnr1, .textnr1').fadeOut(400, function(){
            $('.textnr2, .gridnr2').fadeIn(400);
        });

        var newtextcaption = $(response).filter('#newtextcaption').html();
        var box = $(response).filter('#box').html();

        $('#textnr2').html(newtextcaption);
        $('#gridnr2').html(box);

        for (var i=0; i<VALUE_FROM_AJAXphp; i++) {
            DO SOMETHING WITH i;
        }
    });

Now i need a return value from a function in ajax.php in my action.js because I want to iterate till this value (see the code above). How to pass this value from the ajax.php to the action.js. I am confused what do I need to get the value ajax?, json? or something else?

Thank you.

in the success function, response, is what you get back from the PHP. so sending JSON would be easiest, because then your response is just an object.

Lets say ajax.php returns this JSON

{
    "newtextcaption": "whatever the text is",
    "boxhtml": "whatever your box html is",
    "AjaxValue": 4389489473289
}

then your success function should be

 success: function(response) {
                $('.gridnr1, .textnr1').fadeOut(400, function(){
                    $('.textnr2, .gridnr2').fadeIn(400);
                });

                var newtextcaption = response.newtextcaption;
                var box = response.boxhtml;

                $('#textnr2').html(newtextcaption);
                $('#gridnr2').html(box);

                for (var i=0; i<response.AjaxValue; i++) {
                     DO SOMETHING WITH i;
                }

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