简体   繁体   English

在AJAX和LARAVEL中变得未定义

[英]Getting undefined in AJAX and LARAVEL

im getting undefined problem in getting data from my laravel and ajax trials. 我从laravel和ajax试用中获取数据时遇到了不确定的问题。

here's my ajax 这是我的阿贾克斯

var data = $(this).serialize();
$.ajax({
    url: "{{ route('ajaxdata.getactivities') }}",
    type: "GET",
    datatType: 'json',
    data: data,
    cache: false,
    processData: false,
    error: function (data) {
        console.log('AJAX call Failed');
    },
    success: function (data) {
        console.log('AJAX call success');
        $('#test').append('Add' + data.id); //data.id is showing undefined. if it is only data it doesnt show anything but AJAX call success
    },
});

Here's my route 这是我的路线

Route::get('ajaxdata/getactivities', 'AjaxdataController@getactivities')
    ->name('ajaxdata.getactivities');

Here's my controller function 这是我的控制器功能

function getactivities()
{
    $activities = Activity::orderby('id', 'asc')->get();

    return view('student.ajaxdata', compact('activities'));
}

You have typo in orderby in your controller: 您的控制器中有orderby错误:

$activities = Activity::orderBy('id','asc')->get();

And ajax does not return view, try to: 而且ajax不返回视图,请尝试:

return compact('activities');

Also data from response is array of activities and you can't take id of array. 同样,来自响应的数据是活动数组,您不能获取数组的id。 Try data[0].id for example. 例如,尝试使用data[0].id

在此处输入图片说明 Let us Rewrite the whole stuff 让我们重写整个内容

var data = $(this).serialize();
        $.ajax({
            url: "{{ route('ajaxdata.getactivities') }}",//if this page 

// does not end with something.blade.php, it will not render your url, i.e if you have seperate .js file, consider rewriting this line, probably like so
   // $url=$(this).attr('action');
            type:"GET",
            datatType : 'json',
            data: data,

            error: function (data)
      {
        console.log('AJAX call Failed');
      },
        success: function(data)
      {
        console.log('AJAX call success');
        $('#test').append('Add' + data.id); //data.id is showing undefined. if it `is only data it doesnt show anything but AJAX call success`
    },
        })

It looks like you want to return the view, you will need to render it like so 看起来您想返回视图,您将需要像这样渲染它

function getactivities()
    {    
    $activities = Activity::orderBy('id','asc')->get();
    $data=view('student.ajaxdata', compact('activities'))->render();
return response()->json(['html'=>$data]);
    }

and access it in your ajax success as 并以成功的方式访问它

console.log(data.success)// this will return the page with the value and not the values alone.

but if you do not want to return the page, then work it out like so 但是如果您不想返回该页面,则可以像这样解决

function getactivities()
{    
$activities = Activity::orderBy('id','asc')->get();
//return view('student.ajaxdata', compact('activities'));
return response()->json(['$data'=>$activities]);
//remember the data returned here is a collection since you are using a `get() method, you cannot do data.id in your ajax without iterating over it, if you plan to return just a row, then rewrite this line`
$activities = Activity::orderBy('id','asc')->first();
}

and access it same way in ajax success. 并以相同的方式在ajax中成功访问它。

    console.log(data)

$data: Array(3)
0:
ActionDescription: ""
ActivityDate: "0000-00-00"
ActivityID: "1"
ActivityName: "Training"
ActivityTime: "00:00:00"
ActivityTypeID: ""
Location: "Moa"
QRCode: ""
created_at: null
event_id: 1
id: 1
updated_at: null
__proto__: Object
1: {id: 3, ActivityName: "Bruno", Location: "NY", ActionDescription: "A", ActivityDate: "0000-00-00", …}
2:
ActionDescription: "Training"
ActivityDate: "0000-00-00"
ActivityID: null
ActivityName: "Bad Blood"
ActivityTime: "12:00:00"
ActivityTypeID: null
Location: "SM Trinoma"
QRCode: null
created_at: "2019-04-11 05:38:30"
event_id: 2
id: 2
updated_at: "2019-04-11 05:38:30"
__proto

Can you try to log data only? 您可以尝试仅记录数据吗?

As Activity::orderBy('id','asc')->get() may be returning collection here so better log data ,than do something like below success: 由于Activity::orderBy('id','asc')->get()可能在此处返回集合,因此比执行以下成功操作更好的日志数据:

`success: function (data) {
    { 
        $.each(data, function() 
        { 
            console.log(data);  //shows the data in array 
            $('#test').append('Add' + data.id); }); 
        }
    }`

with all that hassle using $.each doesnt work for looping the data, so I use for to output the data. 使用$ .each的所有麻烦都无法用于循环数据,因此我用于输出数据。 Here's my working code 这是我的工作代码

$(document).ready(function() {
    var data = $(this).serialize(); 
    $.ajax({ url: "{{ route('ajaxdata.getactivities') }}", 
    method: "get",
    dataType:"JSON", 
    data: data, 
    // cache: false, 
    // processData: false, 
    success: function (data) 
    { 
        $.each(data,function(key,value) { 

            for(var x=0; x < value.length; x++){
            console.log(value[x].ActivityName);

            $('#activities').append($('<option>', {value:value[x].id, text:value[x].ActivityName}));
           }
        })
      }, 
   });
});

The issue is, You are sending view(Blade file) rather than data. 问题是,您正在发送视图(刀片文件)而不是数据。 send json formated data which is easy for you to access data in javascript. 发送json格式的数据,您可以轻松使用javascript访问数据。 Why dont you use return response()->json(['status'=>200,'payload'=>$ourdata]); 为什么不使用return response()->json(['status'=>200,'payload'=>$ourdata]); And also orderby is like orderBy 而且orderby就像orderBy

Like the following 像下面

$activities = Activity::orderBy('id','asc')->get(); return response()->json(['status'=>200,'payload'=>$activities]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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