I am trying to get the state and time of the Jwplayer but I get an "undefined" message when trying to see the result of both. I am using Jwplayer 5.7. Please if you can look at my code to see what I have done wrong, that would be awesome. Also my jquery.post() to the database does not fire anything (might be because i am not getting a state). In my console log under networking I cant see the file being called upon.
One final note, I am trying to send the message to the database in a post when the user clicks out of the browser, so far I have not been able to get that to work yet. I think I might be on the right path so please any further guidance would be appreciated.
Thanks in advance.
<?php
$sessionid = 9;
$channelid = 2;
$ipaddress = get_client_ip();
function get_client_ip() {
$ipaddress = '';
if (isset($_SERVER['HTTP_CLIENT_IP']) )
$ipaddress = $_SERVER['HTTP_CLIENT_IP'];
else if( isset($_SERVER['HTTP_X_FORWARDED_FOR']) )
$ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
else if( isset($_SERVER['HTTP_X_FORWARDED']) )
$ipaddress = $_SERVER['HTTP_X_FORWARDED'];
else if(isset($_SERVER['HTTP_FORWARDED_FOR']) )
$ipaddress = $_SERVER['HTTP_FORWARDED_FOR'];
else if(isset($_SERVER['HTTP_FORWARDED']) )
$ipaddress = $_SERVER['HTTP_FORWARDED'];
else if(isset($_SERVER['REMOTE_ADDR']) )
$ipaddress = $_SERVER['REMOTE_ADDR'];
else
$ipaddress = 'UNKNOWN';
return $ipaddress;
}
?>
<!Doctype>
<HTML>
<head>
<!--<link rel="stylesheet" href="css/grid.css" type="text/css">-->
<link rel="stylesheet" href="css/main.css" type="text/css">
<script type="text/javascript"></script>
<!-- Cll on slider.js here -->
</head>
<body>
<!--<div class="side_banner"><img src="images/logo1.png"/></div>-->
<div class="container">
<div class="grid4 omega">
<div class="banner">
<img src="images/banner.png"/>
</div>
<div id="video_container"></div>
<div id="timer"></div>
<div id="state"></div>
</div>
</div>
<script type="text/javascript" src="js/jwplayer.js"></script>
<script type="text/javascript">
jwplayer("video_container").setup({
'modes': [
{type: 'flash', src: 'includes/jwplayer/player.swf'},
{type: 'html5'}
],
'height': 405,
'width': 720,
'autostretch':'false',
'wmode':'transparent',
'controls':false,
'autostart':false,
'file':'<?php echo json_encode($sessionid); ?>.flv',
'repeat':true,
});
var state = jwplayer("video_container").getState();
var time = jwplayer("video_container").getPosition();
document.getElementById('timer').innerHTML = 'The time is ' + time;
document.getElementById('state').innerHTML = 'The player is in a ' + state +' state';
if(state == "PAUSED"){
document.getElementById('timer').innerHTML = 'On pause, the time is ' + time;
}if(state == "IDLE"){
//try to push to database
try{
$.post(
'save_time.php',
{time:time,
ipaddress:<?php echo json_encode($ipaddress);?>,
channelid:<?php echo json_encode($channelid);?>,
sessionid:<?php echo json_encode($sessionid); ?>
},
function data(){
alert(data);
if(data == 'failed'){
alert(failed);
}
}
);
}catch(err){}
}
//take care of the exit
window.onbeforeunload = function(){
console.log('leeeeeeaaavvvving');
//alert('Are you sure you want to close out?');
var formData = {time:time, ipaddress:<?php echo json_encode($ipaddress); ?>, sessionid:<?php echo json_encode($sessionid); ?>, channelid: <?php echo json_encode($channelid); ?>};
$.ajax({
url:'save_time.php',
type:'POST',
data: formData,
async: false,
timeout: 2000,
success: function(data, textStatus, jqXHR)
{
//data - response from server
console.log(data);
},
error: function (jqXHR, textStatus, errorThrown)
{
console.log('errrororrrrrrr');
}
});
}
</script>
<!--<div class="bottom_buttons">
<div class="button left">Start Over</div>
<div class="button right">Continue</div>
</div>-->
</body>
</html>
I was able to figure this out incase anyone else had the same issue. This is what I did below:
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="includes/jwplayer/jwplayer.min.js"></script>
<script type="text/javascript">
//create the general variables
var videoid = <?php echo json_encode($videoid);?>;
var ipaddress = <?php echo json_encode($ipaddress); ?>;
var channelid = <?php echo json_encode($channelid); ?>;
jwplayer("video_container").setup({
'modes': [
{type: 'flash', src: 'includes/jwplayer/player.swf'},
{type: 'html5'}
],
'height': 405,
'width': 720,
'autostretch':'false',
'wmode':'transparent',
'controls':false,
'autostart':false,
'file':'http://content.bitsontherun.com/videos/nPripu9l-60830.mp4',
'repeat':true,
'events': {
onPause :function(){
time = jwplayer("video_container").getPosition();
//get state
browsercloser(time);
},
onBuffer: function(){
time = jwplayer("video_container").getPosition();
browsercloser(time);
},
onPlay :function(){
time = jwplayer("video_container").getPosition();
browsercloser(time);
},
onIdle: function(){
time = jwplayer("video_container").getPosition();
try{
$.post("save_time.php",{time:time, ipaddress:ipaddress, videoid:videoid, channelid:channelid}, function(data){
if(data == 'good'){
alert('We are all good');
}else{
//
alert(failed);
}
});
}catch(err){}
}
}
});
function browsercloser(time){
//take care of the exit incase it happens on play or any other setting
window.onbeforeunload = function(){
console.log('leeeeeeaaavvvving');
//alert('Are you sure you want to close out?');
var formData = {time:time, ipaddress:ipaddress, videoid:videoid, channelid:channelid};
$.ajax({
url:'save_time.php',
type:'POST',
data: formData,
async: false,
timeout: 2000,
success: function(data, textStatus, jqXHR)
{
//data - response from server
console.log(data);
},
error: function (jqXHR, textStatus, errorThrown)
{
console.log('errrororrrrrrr');
}
});
}
}
</script>
It works on Chrome, Firefox, Internet Explorer and Opera.
Related
I am new to javascript and I have problem with an ajax POST to php.
I am trying tosend javascript variables to php via an ajax POST but it doesn't work.
The ajax post is sent but it sends empty POST. I got alert "Error occured ! 202" when trying to save data to bdd.
Thanks in advance for helping me.
here are my javascript and php codes :
<script type="text/javascript">
function save_marker(mId, vId)
{
//Save new marker using jQuery Ajax
var myData = { 'markerId' : mId, 'vendorId' : vId }; //post variables
console.log(myData);
jQuery.ajax({
type: "POST",
url: "https://marchad.fr/wp-content/plugins/wc-multivendor-marketplace/includes/map_process.php",
data: myData,
cache: false,
dataType: "json",
contentType : "application/json; charset=utf-8",
success: function(dataResult){
var stringified = JSON.stringify(dataResult);
var dataResult = JSON.parse(stringified);
if(dataResult.statusCode==200){
alert("ok"+dataResult);
}
else if(dataResult.statusCode==201){
alert("Error occured !");
} else if(dataResult.statusCode==202){
alert("Error occured ! 202");
} else if(dataResult.statusCode==203){
alert("Error occured ! 203");
}
},
error:function (xhr, ajaxOptions, thrownError){
alert('Ooops, something happened: ' + ajaxOptions + ' ' +thrownError);
}
});
}
</script>
<?php
global $WCFM, $WCFMmp, $wpdb;
$mId = filter_var($_POST["markerId"], FILTER_SANITIZE_STRING);
$vId = filter_var($_POST["vendorId"], FILTER_SANITIZE_STRING);
################ Save & delete markers #################
if( isset($mId) && isset($vId) ) //run only if there's a post data
{
if( !empty($mId) && !empty($vId) ){
//make sure request is comming from Ajax
$xhr = $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest';
if (!$xhr){
header('HTTP/1.1 500 Error: Request must come from Ajax!');
exit();
}
$results = $wpdb->query("INSERT INTO markers_users (id, mark_id, user_id, user_actif) VALUES ('', $mId , $vId , 'oui')");
if (!$results) {
echo json_encode(array("statusCode"=>201));
} else {
echo json_encode(array("statusCode"=>200));
}
} else {
echo json_encode(array("statusCode"=>202));
}
} else {
echo json_encode(array("statusCode"=>203));
}
?>
Your problem is here:
var myData = { 'markerId' : mId, 'vendorId' : vId };
The field names don't need to be in quotes
Change it to this and try again:
var myData = { markerId : mId, vendorId : vId };
try this
data: JSON.stringfy(myData)
ok so the solution is :
<script type="text/javascript">
function save_marker(mId, vId)
{
//Save new marker using jQuery Ajax
var myData = { markerId : mId, vendorId : vId }; //post variables
console.log(myData);
jQuery.ajax({
type: "POST",
url: "https://marchad.fr/wp-content/plugins/wc-multivendor-marketplace/includes/map_process.php?markerId="+ mId +"&vendorId="+ vId,
data: myData,
cache: false,
dataType: "json",
contentType : "application/json; charset=utf-8",
success: function(dataResult){
var stringified = JSON.stringify(dataResult);
var dataResult = JSON.parse(stringified);
if(dataResult.statusCode==200){
alert("ok"+dataResult);
}
else if(dataResult.statusCode==201){
alert("Error occured !"+dataResult.statusCode+dataResult.mId+dataResult.vId+dataResult.rawData+dataResult.rawDataMid+dataResult.rawDataVid+dataResult.datamId+dataResult.datavId);
} else if(dataResult.statusCode==202){
alert("Error occured ! 202"+dataResult.statusCode+dataResult.mId+dataResult.vId+dataResult.rawData+dataResult.rawDataMid+dataResult.rawDataVid);
} else if(dataResult.statusCode==203){
alert("Error occured ! 203"+dataResult.statusCode+dataResult.mId+dataResult.vId+dataResult.rawData+dataResult.rawDataMid+dataResult.rawDataVid);
}
},
error:function (xhr, ajaxOptions, thrownError){
alert('Ooops, something happened: ' + ajaxOptions + ' ' +thrownError);
}
});
}
</script>
<?php
//mysqli
$mysqli = new mysqli($db_host, $db_username, $db_password, $db_name);
if (mysqli_connect_errno())
{
die('Erreur de connexion : ' . $mysqli->connect_errno);
}
$rawData = file_get_contents("php://input");
$data = array();
parse_str($rawData, $data);
$mId = $data['markerId'];
$vId = $data['vendorId'];
################ Save & delete markers #################
if( isset($mId) && isset($vId) ) //run only if there's a post data
{
if( !empty($mId) && !empty($vId) ) //run only if there's a post data
{
$results = $mysqli->query("INSERT INTO markers_users (id, mark_id, user_id, user_actif) VALUES ('', $mId , $vId , 'oui')");
if (!$results) {
echo json_encode(array("statusCode"=>201, "mId"=>$mId, "vId"=>$vId, 'rawData' => $rawData, 'rawDataMid' => $rawData["markerId"], 'rawDataVid' => $rawData["vendorId"], "datamId"=> $data['markerId'], "datavId"=> $data['vendorId']));
} else {
echo json_encode(array("statusCode"=>200));
}
} else {
echo json_encode(array("statusCode"=>202));
}
} else {
echo json_encode(array("statusCode"=>203));
}
?>
I'm editing fullcalendar to adapt it to my needs.
First of all here is the code:
<!----HTML---->
<link href='assets/css/fullcalendar.css' rel='stylesheet' />
<link href='assets/css/fullcalendar.print.css' rel='stylesheet' media='print' />
<script src='assets/js/moment.min.js'></script>
<script src='assets/js/jquery-ui.min.js'></script>
<script src='assets/js/fullcalendar_not_min.js'></script>
<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Scegli Zona di Servizio</h4>
</div>
<div class="modal-body" id="myModalBody">
<div class="form-group">
<label for="sel1">Select list (select one):</label>
<select class="form-control" id="mySelect">
<?php
foreach($zone_servizio_array as $zona){
echo '<option value="'.$zona->getId().'">'.$zona->getNome().'</option>';
}
?>
</select>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary" onclick="save();" data-dismiss="modal">Save changes</button>
</div>
</div>
</div>
</div>
<body>
<div id='wrap'>
<div id='external-events'>
<h4>Agenti</h4>
<?php
foreach ($agenti_array as $agente){
echo '<div class=\'fc-event\'>'.$agente->getNome().' '.$agente->getCognome().'</div>';
}
?>
<p>
<img src="assets/img/trashcan.png" id="trash" alt="">
</p>
</div>
<div id='calendar_buttons' align="left">
<div class="btn-group" role="group" aria-label="..." >
<button type="button" class="btn btn-success"><span class="glyphicon glyphicon-floppy-save" aria-hidden="true"></span> Salva</button>
<button type="button" class="btn btn-danger"><span class="glyphicon glyphicon-refresh" aria-hidden="true"></span> Ripristina</button>
</div>
</div>
<div id='calendar'></div>
<div style='clear:both'></div>
<xspan class="tt">x</xspan>
</div>
</body>
Here is the Javascript:
<script>
var salva = 0; //control variable
function save(){//to change the control variable value
salva = 1;
}
function saveEvent(event, title, start, zone){
$('#myModal').modal('show');
$('#myModal').on('hidden.bs.modal', function (e) {
zona_servizio = document.getElementById('mySelect').value;
if(salva == 1){
console.log('before save event', event, title, start, zone);
$.ajax({
url: 'process.php',
data: 'type=new&title='+title+'&startdate='+start+'&zone='+zone+'&zona_servizio='+zona_servizio,
type: 'POST',
dataType: 'json',
success: function(response){
event.id = response.eventid;
$('#calendar').fullCalendar('updateEvent',event);
},
error: function(e){
console.log(e.responseText);
}
});
}else{
$('#calendar').fullCalendar('removeEvents');
getFreshEvents();
}
});
//$('#calendar').fullCalendar('updateEvent',event);
salva = 0;
console.log('end save event', event);
}
$(document).ready(function() {
zone = "01:00"; //Change this to your timezone
$.ajax({
url: 'process.php',
type: 'POST', // Send post data
data: 'type=fetch',
async: false,
success: function(s){
json_events = s;
}
});
var currentMousePos = {
x: -1,
y: -1
};
jQuery(document).on("mousemove", function (event) {
currentMousePos.x = event.pageX;
currentMousePos.y = event.pageY;
});
/* initialize the external events
-----------------------------------------------------------------*/
$('#external-events .fc-event').each(function() {
// store data so the calendar knows to render an event upon drop
$(this).data('event', {
title: $.trim($(this).text()), // use the element's text as the event title
stick: true // maintain when user navigates (see docs on the renderEvent method)
});
// make the event draggable using jQuery UI
$(this).draggable({
zIndex: 999,
revert: true, // will cause the event to go back to its
revertDuration: 0 // original position after the drag
});
});
/* initialize the calendar
-----------------------------------------------------------------*/
$('#calendar').fullCalendar({
events: JSON.parse(json_events),
//events: [{"id":"14","title":"New Event","start":"2015-01-24T16:00:00+04:00","allDay":false}],
utc: true,
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
editable: true,
droppable: true,
slotDuration: '00:30:00',
**eventReceive**: function(event){
var title = event.title;
var start = event.start.format("YYYY-MM-DD[T]HH:mm:SS");
console.log('event Receive', event, title, start, zone);
saveEvent(event, title, start, zone);
},
eventDrop: function(event, delta, revertFunc) {
var title = event.title;
var start = event.start.format();
var end = (event.end == null) ? start : event.end.format();
$.ajax({
url: 'process.php',
data: 'type=resetdate&title='+title+'&start='+start+'&end='+end+'&eventid='+event.id,
type: 'POST',
dataType: 'json',
success: function(response){
if(response.status != 'success')
revertFunc();
},
error: function(e){
revertFunc();
alert('Error processing your request: '+e.responseText);
}
});
},
eventClick: function(event, jsEvent, view) {
console.log(event.id);
var title = prompt('Event Title:', event.title, { buttons: { Ok: true, Cancel: false} });
if (title){
event.title = title;
console.log('type=changetitle&title='+title+'&eventid='+event.id);
$.ajax({
url: 'process.php',
data: 'type=changetitle&title='+title+'&eventid='+event.id,
type: 'POST',
dataType: 'json',
success: function(response){
if(response.status == 'success')
$('#calendar').fullCalendar('updateEvent',event);
},
error: function(e){
alert('Error processing your request: '+e.responseText);
}
});
}
},
eventResize: function(event, delta, revertFunc) {
console.log(event);
var title = event.title;
var end = event.end.format();
var start = event.start.format();
$.ajax({
url: 'process.php',
data: 'type=resetdate&title='+title+'&start='+start+'&end='+end+'&eventid='+event.id,
type: 'POST',
dataType: 'json',
success: function(response){
if(response.status != 'success')
revertFunc();
},
error: function(e){
revertFunc();
alert('Error processing your request: '+e.responseText);
}
});
},
eventDragStop: function (event, jsEvent, ui, view) {
if (isElemOverDiv()) {
var con = confirm('Are you sure to delete this event permanently?');
if(con == true) {
$.ajax({
url: 'process.php',
data: 'type=remove&eventid='+event.id,
type: 'POST',
dataType: 'json',
success: function(response){
console.log(response);
if(response.status == 'success'){
$('#calendar').fullCalendar('removeEvents');
getFreshEvents();
}
},
error: function(e){
alert('Error processing your request: '+e.responseText);
}
});
}
}
}
});
function getFreshEvents(){
$.ajax({
url: 'process.php',
type: 'POST', // Send post data
data: 'type=fetch',
async: false,
success: function(s){
freshevents = s;
}
});
$('#calendar').fullCalendar('addEventSource', JSON.parse(freshevents));
}
function isElemOverDiv() {
var trashEl = jQuery('#trash');
var ofs = trashEl.offset();
var x1 = ofs.left;
var x2 = ofs.left + trashEl.outerWidth(true);
var y1 = ofs.top;
var y2 = ofs.top + trashEl.outerHeight(true);
if (currentMousePos.x >= x1 && currentMousePos.x <= x2 &&
currentMousePos.y >= y1 && currentMousePos.y <= y2) {
return true;
}
return false;
}
});
process.php
<?php
define('__ROOT__', dirname(dirname(__FILE__)));
require_once __ROOT__.'/main/metodi.php';
include('config.php');
sec_session_start();
$type = $_POST['type'];
if($type == 'new')
{
$startdate = $_POST['startdate'].'+'.$_POST['zone'];
$title = $_POST['title'];
$zona_servizio = $_POST['zona_servizio'];
$insert = mysqli_query($con,"INSERT INTO calendar(`title`, `startdate`, `enddate`, `allDay`, `zona_servizio`) VALUES('$title','$startdate','$startdate','false','$zona_servizio')");
$lastid = mysqli_insert_id($con);
$_SESSION['array_last_events'][] = $lastid;
echo json_encode(array('status'=>'success','eventid'=>$lastid));
}
if($type == 'changetitle')
{
$eventid = $_POST['eventid'];
$title = $_POST['title'];
$update = mysqli_query($con,"UPDATE calendar SET title='$title' where id='$eventid'");
if($update)
echo json_encode(array('status'=>'success'));
else
echo json_encode(array('status'=>'failed'));
}
if($type == 'resetdate')
{
$title = $_POST['title'];
$startdate = $_POST['start'];
$enddate = $_POST['end'];
$eventid = $_POST['eventid'];
$update = mysqli_query($con,"UPDATE calendar SET title='$title', startdate = '$startdate', enddate = '$enddate' where id='$eventid'");
if($update)
echo json_encode(array('status'=>'success'));
else
echo json_encode(array('status'=>'failed'));
}
if($type == 'remove')
{
$eventid = $_POST['eventid'];
$delete = mysqli_query($con,"DELETE FROM calendar where id='$eventid'");
if($delete)
echo json_encode(array('status'=>'success'));
else
echo json_encode(array('status'=>'failed'));
}
if($type == 'fetch')
{
$events = array();
$query = mysqli_query($con, "SELECT calendar.id, calendar.title, calendar.startdate, calendar.enddate, zona_servizio.nome as zona_servizio, calendar.allDay FROM calendar LEFT JOIN zona_servizio on calendar.zona_servizio = zona_servizio.id");
while($fetch = mysqli_fetch_array($query,MYSQLI_ASSOC))
{
$e = array();
$e['id'] = $fetch['id'];
$e['title'] = $fetch['title'];
$e['start'] = $fetch['startdate'];
$e['end'] = $fetch['enddate'];
$e['zona_servizio'] = $fetch['zona_servizio'];
$allday = ($fetch['allDay'] == "true") ? true : false;
$e['allDay'] = $allday;
array_push($events, $e);
}
echo json_encode($events);
}
if($type == 'zone_servizio')
{
$zone = array();
$query = mysqli_query($con, "SELECT * FROM zona_servizio");
while($fetch = mysqli_fetch_array($query,MYSQLI_ASSOC))
{
$e = array();
$e['id'] = $fetch['id'];
$e['nome'] = $fetch['nome'];
$e['id_comune'] = $fetch['id_comune'];
array_push($zone, $e);
}
echo json_encode($zone);
}
?>
Explanation of the code and issue:
I'm using fullcalendar to drag and drop some events on the calendar. In the javascript this corresponds to Event receive.
After the event drop, the function saveEvent is called.
A modal is showed, with a select form.
Clicking on Save changes button, I get the selected option value and than I store the events information and this value in the DB using Ajax.
It's very linear.
When I drop the first event, everything works fine. The problem is when I drop more than one event without manually refresh the page.
Here what happen: I store the second event, but I re-store the first event too.
If I drop a third event, I re-store the first two events and the third.
I need help to understand the reason.
In the javascript I insert some console.log.
Here's the console output:
console_output
You can see at the end that the console.log "before save event" is repeated two times, with the first and second events data.
This means that at the second Event drop, the saveEvent function is called twice. So why does this happen?
I hope my question was clear. Thanks to everyone!
I resolved the issue. It was linked to the bootstrap modal.
I found this other post that helped me: link
I have a case where I want to pass a variable inside a function.
The code gives more clarity:
<?php
$id=$_POST['id'];
echo "
<script type=\"text/javascript\">
$(document).ready(function(){
function loadData(page){
$.ajax({
type: \"POST\",
url: \"loadSubscritor.php\",
dataType: \"html\",
data: ({ page:page }),
success: function(msg) {
$(\"#subscritor #container\").ajaxComplete(function(event, request, settings) {
$(\"#subscritor #container\").html(msg);
});
},
error: function(){
alert('alertErr');
}
});
}
loadData(1); // For first time page load default results
$('#subscritor #container .pagination li.active').live('click',function() {
var page = $(this).attr('p');
loadData(page);
});
$('#subscritor #go_bt').live('click',function() {
var page = parseInt($('.goto').val());
var no_of_pages = parseInt($('.total').attr('a'));
if(page != 0 && page <= no_of_pages){
loadData(page);
}else{
alert('Enter a PAGE between 1 and '+no_of_pages);
$('.goto').val(\"\").focus();
return false;
}
});
});
</script>
<h3>Subscritor</h3>
<div id=\"subscritor\">
<div id=\"container\">
<div class=\"pagination\"></div>
</div>
</div>";
?>
As shown in the code,
I would like to know how could I pass $id inside the loadData(page) function .
I get this variable from a post request made with ajax, and need to use it inside the function to pass it has variable to loadSubscritor.php
Any idea on how to do it?
EDIT 1: I guees I wasnt very clear on what I wanted, i want to do this :
function loadData(page){
$.ajax({
data: ({ page:page id:$id }),
Thanks in advance.
Well, if I understood what you are trying to achieve you could replace this :
$id=$_POST['id'];
By this :
$id = isset($_POST['id']) ? $_POST['id'] : 1;
And this :
loadData(1); // For first time page load default results
By this :
loadData($id);
For explanation, if it's first time page load, $id will be set to "1".
Else, this will come from $_POST['id'].
Inside your jquery code you can call a php variable in following way
var current_page = "<?php echo $id; ?>" ;
You can make a local variable and easily use as below:
<?php
$id=$_POST['id'];
echo "
<script type=\"text/javascript\">
var id = \"".$id."\";
$(document).ready(function(){
function loadData(page){
$.ajax
({
type: \"POST\",
url: \"loadSubscritor.php\",
dataType: \"html\",
data: ({ page:page
}),
success: function(msg)
{
$(\"#subscritor #container\").ajaxComplete(function(event, request, settings)
{
$(\"#subscritor #container\").html(msg);
});
},
error:
function()
{ alert('alertErr');
}
});
}
loadData(1); // For first time page load default results
$('#subscritor #container .pagination li.active').live('click',function(){
var page = $(this).attr('p');
loadData(id);
});
$('#subscritor #go_bt').live('click',function(){
var page = parseInt($('.goto').val());
var no_of_pages = parseInt($('.total').attr('a'));
if(page != 0 && page <= no_of_pages){
loadData(id);
}else{
alert('Enter a PAGE between 1 and '+no_of_pages);
$('.goto').val(\"\").focus();
return false;
}
});
});
</script>
<h3>Subscritor</h3>
<div id=\"subscritor\">
<div id=\"container\">
<div class=\"pagination\"></div>
</div>
</div>
";
?>
The general problem is that I cannot get back echo or return through ajax from another file.The alert(msg) is empty. Does that prevent.default stop sending the GET? I am not very fluent in programming, could you please help me in this?
I have my simple form:
<form class='findAndBlock1' method="GET" action="">
<input type='text' name="nameToBlock1" placeholder=" who do you want to block?" class='nameInput'>
<input type='submit' value="Search" class='submitInput1'>
</form>
After clicking it, the ajax script starts:
<script>
$(".submitInput1").click(function(){
event.preventDefault();
$.ajax({
type: "GET",
url: "/searchFriendsToBlock",
data: {
},
success : function(msg) {
alert(msg);
},
error : function(error) {
alert('error');
}
});
});
</script>
It is directed to the script that is routed like this:
Route::any('/searchFriendsToBlock', 'SettingsController#searchFriendsToBlock');
Here is the script that is run through ajax:
public function searchFriendsToBlock() {
$q = Input::get('nameToBlock');
if (strlen($q) < 3)
return null;
$users = DB::table('users')->where //here goes some long request
foreach ($users as $user) {
if (!$user->f_first_name_public)
$user->first_name = "";
if (!$user->f_last_name_public)
$user->last_name = "";
$user->avatar = User::getUserAvatar($user->id);
$user->id = "";
$user->type = "user";
$newArr[] = $user;
}
echo "hello";
return Response::json($newArr);
}
Use dataType parameter in ajax request as you are sending response in json format the default dataType is set to html in jQuery.ajax()
<script>
$(".submitInput1").click(function(){
event.preventDefault();
$.ajax({
type: "GET",
dataType: "json",
url: "/searchFriendsToBlock",
data: {
},
success : function(msg) {
alert(msg.type);
},
error : function(error) {
alert('error');
}
});
});
</script>
And Your script should be like this
public function searchFriendsToBlock()
{
$q = Input::get('nameToBlock');
if (strlen($q) < 3)
return null;
$users = DB::table('users')->where //here goes some long request
$response = array();
foreach ($users as $user) {
if (!$user->f_first_name_public)
$user->first_name = "";
if (!$user->f_last_name_public)
$user->last_name = "";
$user->avatar = User::getUserAvatar($user->id);
$user->id = "";
$user->type = "user";
$newArr[] = $user;
}
$response['type'] = 'sussess';
$response['data'] = $newArr;
return Response::json($response);
}
I am looking for a jQuery AJAX script alongside a PHP script that allows for the storage of information on a button click. The function defined within the jQuery should take three variables, all of which are defined pre-method call. I have the basis of operation complete but at the end of all operations - after the button is clicked and some time has passed - no data is added to the appropriate mysql database.
Here is my jQuery function "store"
<script type="text/javascript">
function store(ud, ld, tp) {
$.ajax({
url: 'http://www.exampledomain.com/folder/store.php',
type: 'POST',
data: 'ud='+ud+'&ld='+ld+'&tp='+tp
success : function() {
alert("WORKED!");
},
error : function() {
alert("DIDN'T WORK!");
},
complete : function() {
}
});
}
</script>
Here is the store.php file (very basic I know, I have also yet to secure this script via sanitizing user input)
<?php
require ('../mysqli_connect.php');
$errors = 0;
if(isset($_POST['ud']) && is_numeric($_POST['ud'])) {
$ud = $_POST['ud'];
} else {
++$errors;
}
if(isset($_POST['ld']) && is_numeric($_POST['ld'])) {
$ld = $_POST['ld'];
} else {
++$errors;
}
if(isset($_POST['tp'])) {
$tp = strip_tags(stripslashes($_POST['tp']));
} else {
++$errors;
}
if($errors == 0) {
$q = "INSERT INTO table_name (column_1, column_2, column_3, column_4) VALUES ('$ld', '$ud', NOW(), '$tp')";
mysqli_query($mysqli, $q);
} else {
echo 'There was a problem!';
}
?>
Assume that I have onclick="store(3, 3, A)" as an attribute for a certain element. How can I fix this? If I remove the onclick attribute how do I pass the necessary parameters to the jQuery function? I appreciate any and all help!
<-- EDIT -->
New jQuery & AJAX Script ...
<script type="text/javascript">
function store(ud, ld, tp) {
$.ajax({
url: 'http://www.exampledomain.com/folder/store.php',
type: 'POST',
data: 'ud='+ud+'&ld='+ld+'&tp='+tp,
error : function() {
alert("error");
},
success : function(data) {
alert(data);
},
complete : function() {
alert("complete");
}
});
}
$(function () {
$("a.rec").on("click", function () {
var $this = $(this),
ud = $this.data("ud"),
ld = $this.data("ld"),
tp = $this.data("tp");
store(ud, ld, tp);
});
});
</script>
Revised PHP
<?php
if($_SERVER['REQUEST_METHOD'] === "POST"){
require ('../mysqli_connect.php');
$errors = 0;
if(isset($_POST['ud'])) {
$ud = $_POST['ud'];
} else {
++$errors;
}
if(isset($_POST['ld'])) {
$ld = $_POST['ld'];
} else {
++$errors;
}
if(isset($_POST['tp'])) {
$tp = $_POST['tp'];
} else {
++$errors;
}
if($errors == 0) {
$q = "INSERT INTO table_name (column_1, column_2, column_3, column_4) VALUES ('$ld', '$ud', NOW(), '$tp')";
mysqli_query($mysqli, $q);
} else {
echo 'There was a problem!';
}
} else {
$url = 'http://www.exampledomain.com/error.php';
ob_end_clean();
header("Location: $url");
exit();
}
?>
Now for my HTML
<li>
<div class="sample classes">
<a class="rec" data-ud="13" data-ld="10" data-tp="SCI">
<input type="submit" title="Something" value="Something" />
</a>
</div>
</li>
However, when this button is clicked, it still does not do anything!
As you said onclick is something you are going to want to avoid. This is how you do it.
$(function () { //This function will be ran when the page loads
$(".button-class").on("click", function () { //This will run when any button is clicked
var $this = $(this),
ud = $this.data("ud"),
ld = $this.data("ld"),
tp = $this.data("tp");
store(ud, ld, tp);
});
});
HTML
<input type="button" class="button-class" data-ud="3" data-ld="3" data-tp="A"/>
I find it easier to use JSON and pass variables in an object to the server:
<script>
(function(){
var store = function (ud, lrid, type) {
var data = {
ud:ud,
lrid:lrid,
type:type
};
$.ajax({
url: 'http://www.exampledomain.com/folder/store.php',
type: 'POST',
data: data,
success : function(data) {
alert(data);
},
error : function() {
alert("DIDN'T WORK!");
},
complete : function() {
}
});
};
$('#btn').on('click', function(){
store(1,2,3);
});
}());
</script>
Use this script to test you are getting the variables on the server side:
<?php
# Put this in http://www.exampledomain.com/folder/store.php to test it works
if($_SERVER['REQUEST_METHOD'] === "POST"){
if(
isset($_POST['ud']) &&
isset($_POST['lrid']) &&
isset($_POST['type'])
)
{
$var = $_POST['ud'] . ", ".$_POST['ud'] . ", ".$_POST['type'] ." passed successfully via ajax!";
echo json_encode($var);
}
}
?>