I have a users table and lesson table. In users table I have watch_history column in which I want to store the data of current playing lesson_id and currentTime of video so the user can continue watching from skip or left video.
I am new to ajax so I don't know how to send the data continuously to database using ajax.
This is my JS code which is printing the currentTime in console.
<script>
var vid = document.getElementById("player");
$(function() {
var timeout;
$("#player").on("playing pause", function(e) {
// save reference
var v = this
// clear previous timeout, if any
clearTimeout(timeout)
// call immediately if paused or when started
performaction(v.currentTime, v.duration)
// set up interval to fire very 5 seconds
if (e.type === "playing") {
timeout = setInterval(function() {
performaction(v.currentTime, v.duration)
}, 3000)
}
})
function performaction(currentTime, duration) {
console.log(currentTime);
}
})
</script>
How can I send the timing of video with lesson id in one array using ajax in Laravel. I am using the plry.io video player. This above JS code is present on the Lesson_video.blade.php page on which I have the lesson id.
I am working on a college project.
In your html:
<input type="hidden" name="_token" value="{{csrf_token()}}"/>
In your javascript do this:
function performaction(currentTime, duration, videoId){//pass video id to this function where you call it.
var data = {time: currentTime, duration: duration}; //data to send to server
var dataType = "json"//expected datatype from server
var headers = { 'X-CSRF-TOKEN': $('input[name="_token"]').val()}
$.post({
url: '/saveTime/'+videoId, //url of the server which stores time data
data: data,
headers: headers,
success: function(data,status){
alert(status);
var data = JSON.parse(data)
alert(data['message']);
},
dataType: dataType
});
}
function resumePlayback(videoId){//Ajax request for getting the time
$.ajax({
url: '/getTime/'+videoId,
success: function(data,status){
var data = JSON.parse(data);
if(status == 200){
document.getElementById('player').currentTime = data['playbackTime'];
alert(playbackTime);
}
},
dataType: "json"
});
}
In your routes/web.php:
Route::post('/saveTime/{video}', 'InstructorCourseController#saveTime')->name('video.saveTime');
Route::get('/getTime/{video}', 'InstructorCourseController#getTime')->name('video.getTime');//Route for getting the saved time
In your InstructorCourseController.php:
public function saveTime(Request $request, $video){
$request->validate([
'time' => 'required',
'duration' => 'required'
]);
$user = Auth::user();
if($user === null){
return response()->json(['message' => 'User not authenticated', 403);
}
$user_id = $user->id;
$video = Video::where('id',$video)->first();
if($video === null){
return response()->json(['message' => 'Video not found', 404);
}
$currentTime = $request->time;
$duration = $request->duration;
//save them somewhere
return response()->json(['message' => 'Time saved', 200);//send http response as json back to the ajax call
}
public function getTime(Request $request, $video){
$user = Auth::user();
if($user === null){
return response()->json(['message' => 'User not authenticated', 403);
}
$video = Video::where('id',$video)->first();
//get the time from saved time where you saved it with this data
$playbackTime = Somemodel::where('video_id',$video->id)->where('user_id',$user->id)->get()->last();//use this one if you insert the time instead of updating an existing row each time a time is saved.
$playbackTime = Somemodel::where('video_id',$video->id)->where('user_id',$user->id)->first();//use this one if you update the time instead of inserting a new row each time a time is saved.
if($playbackTime === null){
//there's no saved time
$playbackTime = 0;
}else{
$playbackTime = $playbackTime->currentTime;//use what column you saved the time in.
}
return response()->json(['playbackTime' => $playbackTime, 200);
}
Related
I need it to fit and I click on a file to increase the number to 1 and saved in the database
I already have the database created and part of the AJAX code ready, in addition to the number YA INCREMENTA, the issue is that I have an update of the page manually instead of only updating the div
Number to update
<span id="'.$rowRE[id_reclamo].'" class="badge badge-primary badge-pill like">'.$rowRE[positivo].'</span>
Function with ajax
$(document).ready(function () {
$('.like').on('click', function () {
var reclamoID = $(this).attr('id');
if (reclamoID) {
$.ajax({
type: 'POST'
, url: 'like.php'
, data: 'reclamo_id=' + reclamoID
, success: function () {}
});
}
else {
alert("error");
}
});
});
php code
$reclamoID=$_POST['reclamo_id'];
$query = $db->query("UPDATE reclamos SET positivo = positivo +1 WHERE id_reclamo = $reclamoID");
//Count total number of rows
$rowCountTabla = $query->num_rows;
I need you NOT to recharge the entire page if not ONLY THE NUMBER
Return the count in the same request you make when you post your data. Something along the lines of:
PHP:
$reclamoID = pg_escape_string($_POST['reclamo_id']);
$results = $db->query("SELECT positivo FROM reclamos WHERE id_reclamo = '".$reclamoID."'");
// Whatever DB wrapper you're using here... this is just a guess.
$count = $results[0]['positivo'];
echo json_encode(array(
'id' => $reclamoID,
'count' => $count
));
Javascript:
$('.like').on('click', function () {
var element = $(this);
var reclamoID = element.attr('id');
if (reclamoID) {
$.post(
'like.php',
{
reclamo_id: reclamoID
},
function (responseData) {
element.text(responseData.count);
},
'json'
);
}
});
ALWAYS sanitize posted data, to prevent injections and other malicious code.
I'm trying to generate a csv file with egyg33k bundle which I'm using in my symfony project.
I have a twig which contains two date picker inputs and a button. When I click on the button I get the values of the two date pickers and pass them to the php action to use them on a query builder (all of this works), but the file doesn't start downloading. Instead I get the content at the browser console (see photo)
moreover the action was working before using ajax.
ajax call:
$(document).ready(function() {
$("#get_extract").on("click", function() {
$.ajax({
method: "POST",
url: "/back-office/extraction",
data: {
begin_date: $("#begin_date").val(),
end_date: $("#end_date").val()
}
})
});
});
PHP:
public function getExtractRecordsAction(Request $request)
{
if ($request->isXmlHttpRequest() || $request->query->get('showJson') == 1) {
$beginDate = $request->get('begin_date');
$endDate = $request->get('end_date');
$recordsRepository = $this->getDoctrine()->getRepository(Record::class);
$query = $recordsRepository->createQueryBuilder('r')
->where('r.createdAt BETWEEN :beginDate AND :endDate')
->setParameter('beginDate', $beginDate)
->setParameter('endDate', $endDate)
->getQuery();
$records = $query->getResult();
$writer = $this->container->get('egyg33k.csv.writer');
$csv = $writer::createFromFileObject(new \SplTempFileObject());
$csv->insertOne([
'ID',
'FIRST_NAME',
'LAST_NAME',
'CIVILITY',
'PHONE_NUMBER',
'EMAIL',
'ZIP_CODE',
'OPTIN',
]);
foreach ($records as $record) {
$csv->insertOne([
$record->getId(),
$record->getPersonalDetails()->getFirstName(),
$record->getPersonalDetails()->getLastName(),
$record->getPersonalDetails()->getCivility(),
$record->getPersonalDetails()->getPhoneNumber(),
$record->getPersonalDetails()->getEmail(),
$record->getPersonalDetails()->getZipCode(),
$record->getPersonalDetails()->getOptin(),
]);
}
$csv->output('EXAMPLE.csv');
exit();
}
}
Ciao, please extend your ajax call, it just download the data you need to force the download of the file. Actually the ajax call transfer the data from remote to local browser so you just need a way to let the browser putting everything inside a file and starting the local download (from browser to Download folder)
$("#get_extract").on("click", function() {
$.ajax({
method: "POST",
url: "/back-office/extraction",
data: {
begin_date: $("#begin_date").val(),
end_date: $("#end_date").val()
},
success: function(csv_content) {
let filename = 'data.csv';
let csvFile = new Blob([csv_content], {type: "text/csv"});
let downloadLink = document.createElement("a");
downloadLink.download = filename;
downloadLink.href = window.URL.createObjectURL(csvFile);
document.body.appendChild(downloadLink);
downloadLink.click();
}
})
I have some code that sends a variable (pin) to php via AJAX the database is then queried and if a result is found the php echo's a value of 1. Everything is working fine, except that the Ajax does not recognise the value returned by the php.
Here is my code
$(document).ready(function () {
$("form.submit").submit(function () {
var pin = $(this).find("[name='pin']").val();
// ...
$.ajax({
type: "POST",
url: "http://www.example.com/pin.php",
data: {
pin : pin,
},
success: function (response) {
if (response == "1") {
$("#responsecontainer").html(response);
window.location.href = "home.html?user=" + user;
// Functions
} else { // Login failed
alert("LOGIN FAILED");
}
}
});
this.reset();
return false;
});
});
And here is my PHP code, I know that the code below returns a value of 1. When Ajax is triggered it returns a value that generates a login fail message. Is there a way to see what Ajax is sending, if i swap out the ajax and directly submit the for to the server it also returns a 1 on the php echo.
$pin = $_GET["pin"];
$db = new PDO("mysql:host=localhost;dbname=xxxxx;charset=utf8", "xxxx", "xxxx");
$count = $db->query("SELECT count(1) FROM users WHERE pin='$pin'")->fetchColumn();
echo $count;
It's recommended to return JSON data as result for an ajax request.
So try this :
Edit: I've updated the php code to make the sql query with PDO prepare() method taking into account #Dominik's commentary
$pin = $_POST['pin'];
$db = new PDO('mysql:host=localhost;dbname=xxxxx;charset=utf8', 'xxxx', 'xxxx');
$stmt = $pdo->prepare('SELECT count(1) FROM users WHERE pin = :pin');
$stmt->execute(array('pin' => $pin));
return json_encode([
"count" => $stmt->fetchColumn()
]);
And in your ajax success callback :
...
success: function(response) {
var count = JSON.parse(response).count;
if (count == "1") {
$("#responsecontainer").html(response);
window.location.href = "home.html?user="+ user;
} else {// Login failed
alert("LOGIN FAILED");
}
},
error: function(error) {
...
}
Hope it's helps you :)
I've got 6 different routes that can be chosen from an input select. Each selected route then posts to its own database.
The problem is I get a 500 error back for all of them, but on half of them, it actually posts to the database. I've gone through line-by-line, and other than the variable names, the code is identical. Here's an example of one that doesn't work at all.
submit.js
$('#submit-event').on('click', function() {
event.preventDefault()
let title = $('#title').val()
let type = $('#type').val() // for selecting which DB
let start = $('#start').data('DateTimePicker').date()
let end = $('#end').data('DateTimePicker').date()
let data = {
'_token': token,
'title': title,
'start': start,
'end': end
}
console.log(type); // logs the correct POST route
$.ajax({
method: 'POST',
url: type,
data: data,
success: function(data) {
console.log(data);
},
error: function(err) {
console.log(err)
}
});
})
routes.php
Route::post('/createmeeting', [
'uses' => 'MeetingController#postCreateMeeting',
'as' => 'createmeeting'
]);
MeetingController.php
class MeetingController extends Controller
{
// Get Meeting from DB - works
public function getMeetings()
{
$meetings = Meeting::orderBy('created_at', 'desc')->get();
return $meetings;
}
// Add new Meeting to DB - doesn't work (500 error)
public function postCreateMeeting(Request $request)
{
if (!request['_token']) {
return redirect()->route('calendar')->with(['message' => "You must be logged in"]);
}
// Save Meeting
$meeting = new Meeting();
$meeting->title = $request['title'];
$meeting->start = $request['start'];
$meeting->end = $request['end'];
if ($request->user()->meetings()->save($meeting)) {
$message = 'Event successfully added to calendar';
return redirect()->route('calendar')->with(['message' => $message]);
}
return redirect()->route('calendar')->with(['message' => $message]);
}
}
Responses to similar problems suggest a problem with the token, but I test for that here. Any idea where the mistake could be happening?
i try using ajax request for extjs calendar. the only problem is when creating new record .How to send back eventId to the form .I want to test the update record after receiving new record.When i try to update it send back auto increment internal record instead of return ajax response eventId.
What i do.
'eventadd': {
fn: function (win, rec) {
win.hide();
rec.data.IsNew = false;
rec.data.eventId = 'testing'; // tengok boleh tak bypass
this.eventStore.add(rec);
this.showMsg('Event ' + rec.data.Title + ' was added');
var data;
reminder = function (data) {
var remind;
if (!data) {
remind = null;
} else {
remind = data;
}
return remind;
};
Ext.Ajax.request({
url: '../controller/eventController.php',
params: {
method: 'create',
calendarId: rec.data.CalendarId,
eventTitle: rec.data.Title,
eventStart: rec.data.StartDate,
eventEnd: rec.data.EndDate,
eventIsAllDay: rec.data.IsAllDay,
eventReminder: rec.data.Reminder,
eventIsNew: rec.data.IsNew,
leafId: leafId
},
success: function (response, options) {
var jsonResponse = Ext.decode(response.responseText);
if (jsonResponse.success == true) {
title = systemLabel;
} else {
title = systemErrorLabel;
}
Ext.MessageBox.alert(title, jsonResponse.message);
},
failure: function (response, options) {
// critical bug extjs
var jsonResponse = Ext.decode(response.responseText);
Ext.MessageBox.alert(systemErrorLabel, jsonResponse.message);
}
});
},
scope: this
},
Response Output.
{"success":true,"message":"Record Created","data":{"eventId":13},"eventId":13}
When update the record.the only problem on me is eventId.
FireBug Console Parameter
calendarId 1
eventEnd 2011-08-11T01:00:00
eventId 10000
eventIsAllDay false
eventIsNew false
eventReminder
eventStart 2011-08-11T00:00:00
eventTitle oh update4d
leafId 516
method update
On create, the event window adds an auto-incremented id to the new record only so that it has a unique id in the local data store, before it gets sent to the server. It is the responsibility of the server code generating the response after an add to replace the id with the real database PK. Any subsequent CRUD actions would then use the correct id.