Herman Luna Herman Luna - 10 days ago 5
Ajax Question

How to apply diffForHumans() in laravel using ajax?

I'm working with laravel and native ajax. I am wondering where do I put diffForhHumans() when using ajax. In my Controller. I just return the object fetch.

Here's my Controller

public function getDownlines($id) {
$upline = Upline::find($id);

return $upline->downlines;
}


Model

public function downlines() {
return $this->hasMany('App\Downline');
}


HTML Code in View

<div id="downlines">
<div class="downlines-title-container">
<p class="title"></p>
</div>

<div id="downlines-holder">
<div class="p_parent_header">
<p>ID</p>
<p>Account Code</p>
<p>Created By</p>
<p>Created At</p>
</div>
</div>
</div>


Script in Ajax

var downlines = document.getElementById('downlines'),
downlines_holder = document.getElementById('downlines-holder');

function getPromise(url) {
return new Promise(function(resolve, reject) {
var xhr = new XMLHttpRequest();

xhr.open('GET', url);

xhr.onload = function() {
if(xhr.status == 200) {
resolve(xhr.response);
} else {
reject(Error(xhr.statusText))
}
}

xhr.onerror = function() {
reject(Error('Network Error'));
};

xhr.send();
})
}

function getDownlines(e, id) {
getPromise('upline/getdownlines/' + id).then(function(response) {
var resp = JSON.parse(response),
p_parent = document.getElementsByClassName('p_parent'),
p = p_parent.length;

while(p--) p_parent[p].remove();

if(resp.length > 0) {
downlines.style.display = 'initial'
downlines.children[0].children[0].innerHTML = e.innerHTML;

for(var i = 0; i < resp.length; i++) {
var p_parent = document.createElement('div'),
p1 = document.createElement('p'),
p2 = document.createElement('p'),
p3 = document.createElement('p'),
p4 = document.createElement('p');

p_parent.classList.add('p_parent');
p1.innerHTML = resp[i].id;
p2.innerHTML = resp[i].account_code;
p3.innerHTML = resp[i].created_by;
p4.innerHTML = resp[i].updated_at;
p_parent.appendChild(p1);
p_parent.appendChild(p2);
p_parent.appendChild(p3);
p_parent.appendChild(p4);
downlines_holder.appendChild(p_parent);
}
} else {
downlines.style.display = 'none'
}
}, function(error) {
console.log(error);
})
}


I'm searching for the same problem and doesn't find one.

Any help would be appreciated. Thanks!!!

Answer

Please do this before returning the downlines

public function getDownlines($id)
{
  $upline = Upline::find($id);

  return $upline->downlines->map(function($downline) {
    return [
      'id' => $downline->id,
      'account_code' => $downline->account_code,
      'created_by' => $downline->created_by,
      'created_at' => $downline->created_at->diffForHumans(),
      'updated_at' => $downline->updated_at->diffForHumans(),
    ];
  });
}

I am unsure if you want to use created_at or updated_at, because in the html you have written <p>Created At</p> but in the AJAX request, you have written p4.innerHTML = resp[i].updated_at;. So I added both in the return array :)