Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 949
Faculty Avatar asked Nov 26 '25 08:11

Faculty


1 Answers

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;
                }
like image 88
Danielle Avatar answered Nov 27 '25 20:11

Danielle



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!