Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel AJAX GET and show new data

I've been working on a project and thus far I've been able to POST to the database using AJAX, so when the user submits data the page wont refresh but the data is still uploaded to the database.

Now what I want to do, is show those results to the user without needing to refresh the page. I've spent a lot of time trying to figure it out but right now I'm very stuck. Could anyone point me in the right direction? I've read the documentation on the website, watched hours worth of videos but still have no luck.

The code I have so far.

Script

$.ajax({
    type: 'GET', //THIS NEEDS TO BE GET
    url: '{{$video->id}}/shownew',
    success: function (data) {
        console.log(data);
        $("#data").append(data);
    },
    error: function() { 
         console.log(data);
    }
});

Controller

public function shownew($video)
{
    $getstamps = DB::table('timestamps')
                    ->where('videoid', '=', $video)
                    ->orderByRaw('LENGTH(timestamp_time)', 'ASC')
                    ->orderBy('timestamp_time', 'asc')
                    ->get();

    return response()->json(array('success' => true, 'getstamps' => $getstamps));
}

Console

{success: true, getstamps: Array(3)}
getstamps: Array(3)
    0: {
        timestamp_id: 128,
        videoid: "5",
        timestamp_name: "Title",
        timestamp_time: 1,
        created_at: "2017-10-04 23:28:12",
        …
    }
    1: {
        timestamp_id: 129,
        videoid: "5",
        timestamp_name: "1",
        timestamp_time: 1,
        created_at: "2017-10-04 23:41:01",
        …
    }
    2: {
        timestamp_id: 130,
        videoid: "5",
        timestamp_name: "1",
        timestamp_time: 1,
        created_at: "2017-10-04 23:41:21",
        …
    }
length: 3
__proto__: Array(0)
success: true
__proto__: Object
like image 737
WhoIsMostash Avatar asked Jan 30 '26 20:01

WhoIsMostash


1 Answers

here is the solution for you problem

$.ajax({
    type: 'GET', //THIS NEEDS TO BE GET
    url: '{{$video->id}}/shownew',
    success: function (data) {
        var obj = JSON.parse(data);
        var your_html = "";
        $.each(obj['getstamps'], function (key, val) {
           your_html += "<p>My Value :" +  val + ") </p>"
        });
         $("#data").append(you_html); //// For Append
         $("#mydiv").html(your_html)   //// For replace with previous one
    },
    error: function() { 
         console.log(data);
    }
});
like image 191
M Arfan Avatar answered Feb 01 '26 18:02

M Arfan