Send push notifications thorugh GCM in progessive web apps - javascript

this is my code to send push notification in progressive web app.It works property when i click on button sendRequest() function is called and notification sent properly. but push event is not fired.is there anything wrong in this code
function sendRequest(){
navigator.serviceWorker.ready
.then(function(registration) {
registration.pushManager.getSubscription()
.then(function (subscription) {
curlCommand(subscription);
var root = 'http://jsonplaceholder.typicode.com/posts';
var title="Push Notification";
$(document).ready(function () {
$.ajax({
url: root,
beforeSend: function(xhr) { xhr.setRequestHeader("Content-Type","application/json");},
type: 'POST',
contentType: 'application/json',
crossDomain: true,
dataType: 'json',
processData: false,
data: JSON.stringify(subscription),
success: function (data) {
reg.showNotification(title, {
body: 'Hello',
icon: 'images/icon.png',
tag: 'my-tag'
});
console.log(data);
},
error: function(){
alert("Cannot get data");
}
});
});
});
});
}

Related

bootstrap notify ajax succes response

<script>
$(document).ready(function(){
$(document).on('change', '#avatar', function(){
var property = document.getElementById("avatar").files[0];
var form_data = new FormData();
form_data.append("avatar", property);
$.ajaxSetup({
beforeSend: function(xhr, type) {
if (!type.crossDomain) {
xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'));
}
},
});
$.ajax({
url: '{{ url('app()->getLocale())/profile') }}',
method: "POST",
data: form_data,
contentType: false,
cache: false,
processData: false,
success:function(response){
window.location.href = window.location.href;
$.notify({
message: 'Hello World'
},{
// settings
type: 'danger'
});
}
})
});
});
</script>
How can I do this so that when the image is finished uploading and the image is refreshed to display a message using $ .notify? I tried everything I found on the internet, but to no available...

Send FormData through Ajax POST method return 403

I write an application with speech recognition. All I want is to record some speech and send it to server where I will convert it into text. And I have a problem with sending that sound file. I record voice using p5.js library and when I try to download it there is no problem.
The problem is when I try to send it to server using ajax.
script.js
function toggleRecording(e) {
if (e.classList.contains("recording")) {
recorder.stop();
e.classList.remove("recording");
sendAudioToServer(soundFile)
} else {
e.classList.add("recording");
recorder.record(soundFile);
}
}
function sendAudioToServer(soundFile)
{
var data = new FormData();
data.append('fname', 'test.wav');
data.append('data', soundFile);
console.log(soundFile);
console.log(data);
$.ajax({
type: 'POST',
url: '/recognizeCommand',
data: data,
dataType: 'jsonp',
processData: false,
contentType: false,
success: function(data) {
alert("works!");
},
error: function() {
alert("not works!");
}
})
Java controller
#PostMapping("/recognizeCommand")
public #ResponseBody String recognizeCommand(#RequestParam MultipartFile mpf) {
try {
byte[] bytes = mpf.getBytes();
SpeechRecognitionApplication.logger.info(bytes);
} catch (IOException e) {
e.printStackTrace();
}
return "finish";
}
When I stop recording regardless to toggleRecording function it should stop recording and send it to server. And there is a problem with sendAudioToServer function. Here is the result from Chrome console:
I'm not sure but there is probably problem with FormData. As you can see when I printed it in console it's empty. Founded some similar questions here but there is no solution to solve my problem.
EDIT:
After add dataType: 'jsonp'
There is that error:
EDIT 2:
After adding csrf token:
Please add csrf tokens as this.
<meta name="_csrf" th:content="${_csrf.token}"/>
<meta name="_csrf_header" th:content="${_csrf.headerName}"/>
In header:
var token = $("meta[name='_csrf']").attr("content");
var header = $("meta[name='_csrf_header']").attr("content");
Set headers.
$.ajax({
type: 'POST',
url: '/recognizeCommand',
data: data,
dataType: 'json',
processData: false,
contentType: false,
beforeSend: function(xhr) {
// here it is
xhr.setRequestHeader(header, token);
},
success: function(data) {
alert("works!");
},
error: function() {
alert("not works!");
}
})
Try adding debug point here.
SpeechRecognitionApplication.logger.info(bytes);
Try adding dataType: 'jsonp' to your $.ajax call like,
$.ajax({
type: 'POST',
url: '/recognizeCommand',
data: data,
dataType: 'jsonp',
processData: false,
contentType: false,
success: function(data) {
alert("works!");
},
error: function() {
alert("not works!");
}
})
Hope this helps!

My client won't reload after ajax put even with .then and location.reload

I can't get the client to console.log or reload after this ajax PUT. The put goes through to the database fine. I just need it to reload to see the new results.
$(".devour").on("click", function(event) {
event.preventDefault();
var id = { id: $(this).attr("id") };
$.ajax("/", {
type: "PUT",
data: id,
}).then(function() {
console.log("Updated Burger");
location.reload();
});
});
can you try like this
$.ajax({
type: 'PUT',
url: 'http://example.com/api',
contentType: 'application/json',
data: JSON.stringify(data), // access in body
})
.then(
()=>console.log("success"),
()=>console.log("FAIL"));//check for fail may be issue
or try more explicit order way
$.ajax({
type: 'PUT',
url: 'http://example.com/api',
contentType: 'application/json',
data: JSON.stringify(data), // access in body
}).done(function () {
console.log('SUCCESS');
}).fail(function (msg) {
console.log('FAIL');
}).always(function (msg) {
console.log('ALWAYS');
});

How to create the confirm box (modal popup) in asp.net MVC?

How to create the confirm box (modal popup) after i click this button:
<button id="sellButton" onclick="sendRequest(#item.Id)">Sell</button>
HERE POPUP MODAL (YES/NO)
When user will confirm, then this should happen
<script>
function sendRequest(id)
{
var request =
{
"itemId": id
};
$.ajax({
url: '/It/Sell',
data: JSON.stringify(request),
type: 'POST',
dataType: "html",
contentType: 'application/json; charset=utf-8',
error: function (err) {
alert('Error: ' + err.statusText);
},
success: function (result) {
$('#Table').html(result);
},
async: true,
processData: false
});
};
</script>
if(confirm('are you sure?')){
var request =
{
"itemId": id
};
$.ajax({
url: '/It/Sell',
data: JSON.stringify(request),
type: 'POST',
dataType: "html",
contentType: 'application/json; charset=utf-8',
error: function (err) {
alert('Error: ' + err.statusText);
},
success: function (result) {
$('#Table').html(result);
},
async: true,
processData: false
});
}
Have look at jquery.confirm. It should be able to solve your problem.
If you want to have nice modal confirm box with simple implementation i would recommend Bootstrap3 Dialog
Import necessary files to your project. And
function sendRequest(id)
{
BootstrapDialog.confirm('Are you sure you want to continue?', function(result){
if(result) {
//Send Ajax Request
}
});
}
More Info : https://nakupanda.github.io/bootstrap3-dialog/

Is it possible to send entire form including the files to server using jquery/ajax?

Is it possible to submit entire form (all the fields including fileupload) to server (webmethod or handler etc) using Jquery/Ajax? If yes, how?
ASPX:
$.ajax({
type: "POST",
url: "SupplierBidding.aspx/SubmitBid",
data: JSON.stringify({ id: $('#txtbidderid').val(), bidamt: $('#txtbidamt').val() }),
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
success: function (data, status) {
span.fadeIn("slow", function () {
span.text(data.d).fadeOut('slow');
});
},
failure: function (data) {
alert(data.d);
},
error: function (data) {
alert(data.d);
setTimeout(function () {
btn.prop('disabled', false);
}, 3000);
}
});
}
WebMethod:
[WebMethod]
public static string SubmitBid(string id, string bidamt)
{
//code
return "";
}
I would like to replace data: JSON.stringify({ id: $('#txtbidderid').val(), bidamt: $('#txtbidamt').val() }) with entire form including files also.
You can use Formdata.
FormData Docs
Code example.
var fdata = new FormData();
fdata.append( 'file', input.files[0] );
$.ajax({
url: 'http://yourserver.com/upload.php',
data: fdata,
contentType: false,
processData: false,
type: 'POST',
success: function(data){
console.log('siceess')
}
});
Did you try jQuery Form plugin?
It handles file uploads.
Worked for me before.

Categories

Resources