Please help me, in my code, Ajax and SweetAlert worked perfectly, but now I get the error on pressing submit:
The Google chrome console shows below error:
Resource interpreted as Stylesheet but transferred with MIME type
application/javascript:
"http://localhost:8000/js/jquery-3.3.1.min.js".
Any help is greatly appreciated.
Code
<link rel="stylesheet" type="text/css" href="{!! asset('js/jquery-3.3.1.min.js') !!}">
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/1.1.3/sweetalert.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/1.1.3/sweetalert.min.js"></script>
<script src="//code.jquery.com/jquery-3.3.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
var id1 ={!! $data !!};
var hasil;
var saldo ={{$results}};
$('#jumlahUang').keyup(function () {
var yeah1 = parseInt($('#jumlahUang').val());
var yeah = parseInt($('#jenisTransaksi').val());
if (yeah == 1) {
hasil = saldo + yeah1;
} else {
hasil = saldo - yeah1;
}
if (hasil < 0) {
swal("Error", "SALDO ANDA KURANG");
} else {
$('#debugg').val(hasil);
}
});
$('#formInput').submit(function (e) {
e.preventDefault();
var id1 ={!! $data !!};
var link = "/nambahTransaksi/" + id1.id;
swal({
title: "Konfirmasi transaksi",
text: "proses transaksi?",
type: "info",
showCancelButton: true,
confirmButtonColor: "#1da1f2",
confirmButtonText: "Yakin, dong!",
closeOnConfirm: false,
showLoaderOnConfirm: true,
}, function () { //apabila sweet alert d confirm maka akan mengirim data ke simpan.php melalui proses ajax
$.ajax({
url: link,// ini salah anjing
type: 'get',
data: $('#formInput').serialize(), //serialize() untuk mengambil semua data di dalam form
dataType: "HTML",
success: function () {
setTimeout(function () {
swal({
title: "transaksi berhasil dilakukan",
text: "Terimakasih",
type: "success"
}, function () {
window.location.href = "/detailTransaksi";
});
}, 2000);
},
error: function (xhr, ajaxOptions, thrownError) {
setTimeout(function () {
swal("Error", "Tolong cek kembali SALDO anda");
}, 2000);
}
});
});
});
})
</script>
you have to use this js files,i hope its work for you.
<script src="{{ asset('assets/global/plugins/jquery.min.js') }}" type="text/javascript"></script>
<script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>
example
$("#sub").click(function() {
var startDate = $('#fromDate').val();
var endDate = $('#toDate').val();
if (startDate !='')
{
if(endDate == '')
{
swal("Error!", "Please Select To Date field", "error");
return false;
}
}
else
{
swal("Error!", "Please Select From Date field", "error");
return false;
}
if(startDate > endDate)
{
//alert("Please Select To Date Grater Than"+startDate);
swal("Error!", "Please Select To Date Grater Than "+startDate, "error");
return false;
} });
You have this line set to be a stylesheet but it is actually a .js file.
<link rel="stylesheet" type="text/css" href="{!! asset('js/jquery-3.3.1.min.js') !!}">
Try using:
<script src="{!! asset('js/jquery-3.3.1.min.js') !!}"></script>
Also, why are you including JQuery twice? Just move your second declaration to the top, the line that says:
<script src="//code.jquery.com/jquery-3.3.1.min.js"></script>
It needs to be declared before you add SweetAlert because SweetAlert is dependent on it.
EDIT: This is only a partial answer. OP still has another issue outside of this. Wanted to leave this up however as it was useful in solving part 1 of his problem.
Related
I'm trying to show an error div in a form and hide it when I make a key in the text field. The problem is given when I import the Jquery library in the JSP and in the JS I declare the Jquery function. I do not run the submit form and in the Chrome console, Firefox, IE shows me a parseerror error. In the comes to enter the AJAX call (I added a console.log ()). I tried to comment the dataType line and even change the type of json to text in the AJAX call and it still gives me a parseerror. If I do not comment the dataType line does not enter the AJAX call. It stays in the $.ajax
This image is the console output of the code I left here.
JSP code:
spring:url value="/resources/js/jquery-3.4.1.js" var="jqueryJs" />
<script src="${jqueryJs}"></script>
<%-- <script type="text/javascript" src="/openiam-ui-static/js/common/jquery/jquery-1.9.1.min.js"></script>--%>
<script type="text/javascript" src="/openiam-ui-static/js/common/openiam.common.js"></script>
<%--<script type="text/javascript" src="/openiam-ui-static/moment/moment-with-locales.min.js"></script>--%>
<script type="text/javascript" src="/openiam-ui-static/bootstrap/js/bootstrap.min.js"></script>
<script type="text/javascript" src="/openiam-ui-static/bootstrap/js/bootbox.min.js"></script>
<script type="text/javascript" src="/openiam-ui-static/bootstrap/js/bootstrap-notify.js"></script>
<script type="text/javascript" src="/openiam-ui-static/bootstrap-ui/js/bootstrap-toggle.min.js"></script>
JS code:
jQuery(document).ready(function($) {
$("#error").hide();
$("#otp-form").submit(function(event) {
event.preventDefault();
sendOTP();
});
// $("#smsCode").on("input",function(){
// if($("#smsCode").val().length < 1){
// $("#error").hide();
// }else{
// $("#error").show();
// }
// });
});
function sendOTP() {
$("#error").empty().hide();
var otpToken = {};
otpToken["smsCode"] = $("#smsCode").val();
otpToken["authToken"] = $("#authToken").val();
otpToken["postbackURL"] = $("#postbackURL").val();
$.ajax({
url : "otpToken",
type : "POST",
//dataType : "json",
data : JSON.stringify(otpToken),
success : function(data) {
console.log("SUCCESS: ", data);
if(data.code == 200) {
var redirectURL = data.redirectURL;
if(redirectURL != null && redirectURL != undefined && redirectURL.length > 0) {
window.location.href = redirectURL;
}
console.log(data);
} else if(data.code == 103) {
//Account Locked
} else {
$("#error").empty().hide();
$("#error").show();
$("#error").append("<a href='#' class='close' data-dismiss='alert' aria-label='close'>×</a>");
$.each(data.errorList, function(idx, val) {
$("#error").append($(document.createElement("div")).text(val.message));
});
}
},
error : function(e) {
console.log("ERROR: ", e);
},
done : function(e) {
console.log("DONE");
disableButtons(false);
}
});
}
This image is the console output of the code with decomposed dataType.
A button in my view needs to be created depending on a state.
Index.cshtml:
<html>
<head>
<script src="~/scripts/jquery-3.3.1.js"></script>
<script src="~/scripts/jquery-3.3.1.min.js"></script>
<script type="text/javascript">
$("#send_request_button").on('click', function () {
$.ajax({
url: "SendRequest",
method: "GET",
}).done(function (request_result) {
if (request_result != null && request_result == '1') {
alert("Attempting button disabling");
#*attempt 1*#
#*$(this).prop("disabled", true);*#
#*attempt 2*#
$(this).attr("disabled", "disabled");
}else {
alert("Could not disable Button");
}
});
});
</script>
</head>
<body>
<div>
#{
if (ViewBag.ButtonFlag != null && ViewBag.ButtonFlag)
{
Response.Write("<text id=\"send_request_text\"></text>");
Response.Write("<input id=\"send_request_button\" type=\"button\" value=\"Send Insert Request\"/>");
}
}
}
</body>
</html>
This is giving the button correctly and it is clicked, the expected result after the successful jquery ajax, which is in this case 1, is received. But none of the two attempts to disable the dynamic button is producing the expected result.
Try this instead of $(this) use element id to select in done() It is because the scope of using 'this' keyword won't be available if used in other function:
$("#send_request_button").on('click', function () {
$.ajax({
url: "SendRequest",
method: "GET",
}).done(function (request_result) {
if (request_result != null && request_result == '1') {
alert("Attempting button disabling");
#*attempt 1*#
#*$(this).prop("disabled", true);*#
#*attempt 2*#
$("#send_request_button").attr("disabled", "disabled");
}else {
alert("Could not disable Button");
}
});
});
I have a form that requires 'authorization' - where the user needs to enter one of the authorization codes stored in a database to be able to submit the form (basically a password). I'm trying to use AJAX with PHP to both display (using Bootstrap's feedback glyphicons) a tick or cross depending on whether or not the user entered a valid value and allow or prevent form submission. If the user did not enter a valid value, form submission is prevented.
My code below currently isn't working, any help would be greatly appreciated.
HTML:
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/1000hz-bootstrap-validator/0.11.5/validator.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/1000hz-bootstrap-validator/0.11.5/validator.min.js"></script>
<form name="auth_form" id="auth_form" method="post" action="action.php">
<p>Please enter authorisation code.</p>
<div class="form-group has-feedback" name="auth_code" id="auth_code">
<input class="form-control" id="auth_code_input" autocomplete="new-password" name="auth_code_input" type="password" required>
<span class="form-control-feedback glyphicon" id="statusIcon"></span>
</div>
<button class="btn btn-success btn-ok" name="Submit" id="submit" type="Submit">Submit</button>
</form>
JS:
<script>
$(document).ready(function() {
// Validate on blur and display 'cross' icon in span if invalid, tick if valid
$('#auth_code_input').blur(function() {
if (!ValidateInput()) {
e.preventDefault();
}
});
// Validate on submit and prevent form submission if invalid
$('#auth_form').on('submit', function(e) {
if (!ValidateInput()) {
e.preventDefault();
}
})
});
// AJAX to check the auth-code server-side
function ValidateInput() {
var given_code = document.getElementById('auth_code_input').value;
$.ajax({
url: 'checkauth.php',
type: 'POST',
data: given_code
});
.done(function(response) {
var response = valid;
if valid = '1' {
$('#statusIcon').removeClass('glyphicon-remove').addClass('glyphicon-ok');
IsValid = true;
} else {
$('#statusIcon').removeClass('glyphicon-ok').addClass('glyphicon-remove');
IsValid = false;
}
}
.fail(function() {
IsValid = false;
$('#auth_code_input').val('Something went wrong, please try again.');
});
return IsValid;
});
</script>
checkauth.php
<?php
error_reporting(E_ALL);
ini_set( 'display_errors', 1);
$given_code = $_REQUEST['given_code'];
include 'pdo_config.php';
$valid = '0';
try {
$conn = new PDO($dsn, $user, $pass, $opt);
$stmt = $conn->prepare("SELECT instructor_id, auth_code FROM tbl_instructors WHERE auth_code = :given_code;");
$stmt->bindParam(':given_code', $given_code);
$stmt->execute();
$row = $stmt->fetchColumn();
if ($row == 1) { // row equals one, means auth-code corresponds to an instructor and is valid
$valid = '1';
} else {
$valid = '0';
}
echo valid;
}
catch (PDOException $e) {
echo "Error: " . $e->getMessage();
}
found some errors in your js, function ValidateInput() {, plz update your code from below one.
function ValidateInput() {
var given_code = document.getElementById('auth_code_input').value;
$.ajax({
url: 'checkauth.php',
type: 'POST',
data: given_code
});
.done(function(response) {
if (response == '1') {
$('#statusIcon').removeClass('glyphicon-remove').addClass('glyphicon-ok');
IsValid = true;
} else {
$('#statusIcon').removeClass('glyphicon-ok').addClass('glyphicon-remove');
IsValid = false;
}
}
.fail(function() {
IsValid = false;
$('#auth_code_input').val('Something went wrong, please try again.');
});
return IsValid;
});
if it still not work, then plz add async: true in your ajax call like this,
$.ajax({
url: 'checkauth.php',
type: 'POST',
data: given_code,
async: true
});
It will work definitely
I have code that checks whether the address is ok and sends it. After sending the information appears that the message was sent.
When I give the wrong email address format - appears the message.
Then when I give the correct address - the message you sent is not working.
What is wrong?
jQuery code:
<script type="text/javascript">
{literal}
function validateEmail(email) {
return /^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/.test(email);
}
{/literal}
$(document).ready(function() {
$('#mybtn').click(function() {
var sEmail = $('#email').val();
if ($.trim(sEmail).length == 0) {
alert('Please input your email');
//e.preventDefault();
}
if (validateEmail(sEmail)) {
$('#contact').submit(function() {
$.ajax({
url : '/contact/process',
data : $('#contact').serialize(),
type: "POST",
success : function(){
$('form').find('#name, #email, #message').val('');
$('#messageAfterSend').addClass('alert alert-success').text("Thank you for send email").slideUp(3200);
}
});
return false;
});
}
else {
$('#messageAfterSend').addClass('alert alert-success').text("Invalid email.").slideUp(3200);
$('form').find('#email').val('');
}
});
});
</script>
<script type="text/javascript">
function validateEmail(email) {
return /^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/.test(email);
}
$(document).ready(function() {
$('#contact').on('submit', function(e) {
e.preventDefault();
$.ajax({
url : '/contact/process',
data : $(this).serialize(),
type: "POST",
success : function(){
$('form').find('#name, #email, #message').val('');
$('#messageAfterSend').addClass('alert alert-success').text("Thank you for send email").slideUp(3200);
}
});
});
$('#mybtn').on('click', function(e) {
e.preventDefault();
var sEmail = $('#email').val();
if ($.trim(sEmail).length == 0) {
alert('Please input your email');
}
if (validateEmail(sEmail)) {
$('#contact').trigger('submit');
} else {
$('#messageAfterSend').addClass('alert alert-success').text("Invalid email.").slideUp(3200);
$('form').find('#email').val('');
}
});
});
Try this way, first set listener on your contact form, second listen for event on "send button"
If it's "simple form" you could just put everything in on('submit') listener
Fiddle
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.