I have function in la-ravel controller which i use to get email from my gmail using IMAP client, but i want to always get new message without having to refresh the web page, and i dont know how to get it done, pls i request for help, below is my function code;
public function mail()
{
$last = DB::table('mails')->latest()->first();
$oClient = Client::account('default');
$oClient->connect();
$oFolder = $oClient->getFolders('Gmail.unread');
/*$date=$last->date;
$date=Carbon::createFromFormat('Y-m-d', $date)->format('d.m.Y');*/
foreach($oFolder as $oFolder){
// dd($oFolder);
try {
$message = $oFolder->query()->from('xxxxxxgmail.com')->since('25.04.2020')->get();
$msg=$message->get('items');
if ($msg='null') {
$mails=mail::where('status',1)
->get();
return view('mail', compact('mails'));
}
}
catch (ModelNotFoundException $exception)
{
$mails=mail::where('status',1)
->get();
return view('mail', compact('mails'));
}
foreach($message as $message){
$message= $message->getTextBody();
$calling= preg_match("/Calling number(.*), /", $message,$matches);
$calling=preg_match("/ (.*), /", $matches[1],$match);
$calling=$match[1];
$messages=str_replace("\r\n\r\n", '', $message);
$callback= preg_match("/Callback phone(.*)C/", $messages,$cb);
$callback = ltrim($cb[1], '?');
$name= preg_match("/name(.*)C/", $messages,$cb);
$result=$cb[1];
$name= preg_match("/(.*)C/", $result,$cb);
$name=ltrim($cb[1], '?');
$callcount= preg_match("/Calling number(.*), /", $messages,$matches);
$callcount=preg_match("/,(.*),/", $matches[0],$match);
$callcount=preg_match("/:(.*)/", $match[1],$match);
$callcount=$match[1];
$date= preg_match("/Date(.*) /", $messages,$cb);
$date=preg_match("/:(.*),/", $cb[1],$match);
$date=$match[1];
$callscript= preg_match("/Call script(.*) /", $messages,$cb);
$callscript =$cb[1];
$date=strtotime($date);
$date = date('Y-m-d',$date);
$mail=new mail();
$mail->date=$date;
$mail->name=$name;
$mail->calling_no=$calling;
$mail->callback_phone=$callback;
$mail->message=$callscript;
$mail->save();
$mails=mail::where('status',1)
->get();
return view('mail', compact('mails'));
}
}
}
what i want is a java script/AJAX code to automatically always call this function without refreshing the web page
You have to use get
method like this and get new message withTime period then use like this
function getNewMessage() {
$.ajax({
type: "GET",
url: "{{url('')}}/mail",
success: function (response) {
console.log(response);
}
});
}
setTimeout(getNewMessage, 1000); // 1000 indicated 1 second