i try to post with axios from an array to an api php file and get the responses one by one not just one request. I read something about axios.all() but can't figure it out i am new to javascript.
<div id="app">
<center>
<div id="area">
<textarea v-model="sent" name="sent" id="sent" cols="30" rows="10" class="form-control">
</textarea>
<br>
<button v-on:click="insert" class="btn btn-default">Send</button>
</div>
<div id="good" v-for="message of messages">
<span><h2>Good</h2></span>
{{ message }}
</div>
</center>
</div>
And here is the vuejs code.
<script>
new Vue({
el:'#app',
data:{
sent:[],
messages:[]
},
methods:{
insert:function (){
const vm = this;
splitz.forEach(function(entry){
axios.post('/one.php', {
sent: vm.entry
}).then(response => {
vm.messages.push(response.data.onefinal) ;
console.log(response.data);
}
).catch(function(error){ console.log(error); });
}
}
},
computed:{
splitz: function () {
return this.sent.split('\n')
}
}
});
</script>
You can do it this way:
// Create an array of post requests from splitz array
var requests = splitz.map(entry => axios.post('/one.php', { sent: this.entry }))
// Send all requests using axios.all
axios.all(requests)
.then(results => results.map(response => response.data.onefinal))
.then(newMessages => {
console.log('New Messages:', newMessages)
this.messages.push.apply(this.messages, newMessages)
})
Edit: to send the requests one by one:
insert: function() {
var vm = this;
function sendRequest(arr, i) {
var entry = arr[i];
axios.post('/one.php', { sent: entry }).then(function (response) {
vm.messages.push(response.data.onefinal);
if (i < arr.length - 1) {
sendRequest(arr, ++i);
}
})
.catch(function (error) {
console.log(error);
});
}
sendRequest(this.splitz, 0);
}
Related
site.js file
"use strict";
var connection = new signalR.HubConnectionBuilder().withUrl("/radioHub").build();
function processData( ) {
fetch("https://shazam.p.rapidapi.com/songs/detect", {
"method": "POST",
"headers": {
"content-type": "text/plain",
"x-rapidapi-host": "shazam.p.rapidapi.com",
"x-rapidapi-key": "1ab???"
},
"body": "Generate one on your own for testing and send the body with the content-type as text/plain"
})
.then(response => {
console.log(response);
})
.catch(err => {
console.error(err);
});
}
document.getElementById("radioPlayer").disabled = true;
connection.on("ReceiveRadio", function (radio, shazam) {
var li = document.createElement("li");
document.getElementById("songNameList").appendChild(li);
li.textContent = `${radio} return ${shazam}`;
});
connection.start().then(function () {
document.getElementById("radioPlayer").disabled = true;
var radio = document.getElementById("radioPlayer").value;
var shazam = processData();
console.log(shazam)
connection.invoke("SendRadio", radio, shazam).catch(function (err) {
return console.error(err.toString());
});
}).catch(function (err) {
return console.error(err.toString());
});
Hub.cs file
using Microsoft.AspNetCore.SignalR;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace SignalRCoreServer.Hubs
{
public class ViewHub : Hub
{
public async Task SendRadio(string radio ,string shazam)
{
await Clients.Others.SendAsync("ReceiveRadio",radio, shazam);
}
}
}
index.cshtml
#page
<div class="radio-container">
<div class="radio-header">
</div>
<div class="radio-body">
<div class="shine"></div>
<div class="current-song">
current song
</div>
<div class="row">
<div class="col-2"> </div>
<audio id="radioPlayer" src="https://us4.internet-radio.com/proxy/douglassinclair?mp=/stream;" autoplay="autoplay"></audio>
</div>
</div>
</div>
<script src="~/js/signalr/dist/browser/signalr.js"></script>
<script src="~/js/site.js"></script>
In order to learn the names of the songs playing on the radio, I try to send data to shazam api using the signalR library.
There are hub.cs site.js and index.cshtml files.
(null return null)
result on screen.
it can play song but i couldn't send it to shazam correctly.
What should I do to get the right results?
I'm starting with vue.js and firebase and I have a chat system using firebase. I get all the users’ id that have sent messages to me. So in my database I get their data and list with a v-for.
After listing them I get their messages from FB to list in a message box below each user.
Everything is working fine but I cannot get sent messages instantly after sending them.
I made a workaround with push() to append each sent message to data property but I'd like to know if there is a better way to do that with vue.js.
I've tested with plain javascript (separately with one message box) and the chat is updated on every sent message.
Is there a way to make this work without replacing all data object or calling all the listing process again? I tried with Vue's Reactivity but I could not make it work as expected.
<div v-if="isLoading == true" id="loading"><img class="loading" src="../assets/img/loading.gif" /></div>
<div v-if="isLoading == false" class="row messages-row" v-for="(item, index) in memberData" :key="index">
<div class="col-md-4 col-12">
<div class="messages-profile-infos">
<div class="messages-profile-infos-img img-fluid" v-bind:style="{'background-image': 'url(http://localhost/backend/imgs/'+item.memberProfileImg + ')' }"></div>
<div class="messages-profile-infos-text">
<p>{{ item.memberName }} {{ item.memberLastname }}</p>
<p>{{ item.memberCity }} - {{ item.memberState }}</p>
</div>
</div>
</div>
<div class="col-md-2 col-12">
<div class="messages-btns">
<button class="btn trade-btn" #click="showConversation(item.memberID)">Messages</button>
</div>
</div>
<div class="col-md-6 col-12">
<div class="messages-status">
<a class="btn border btn-circle text-uppercase confirm-service-btn" href="javascript:void(0);">
Confirm
</a>
<a class="btn border btn-circle text-uppercase cancel-service-btn" href="javascript:void(0);">Cancel</a>
</div>
</div>
<!-- conversation box -->
<div v-if="memberBox == item.memberID" class="conversation-container" :id="item.memberID">
<div v-for="(tour, index) in item.tours" :key="index" id="tourOnConversation" class="tourOnConversation">
<span>Tour:</span>
<span><strong>{{ tour.title }}</strong></span>
</div>
<div id="messages-container" class="messages-container" :key="item.memberID">
<div v-for="message in item.messages" class="d-flex" :class="[message.uid != myID ?'justify-content-start':'justify-content-end']">
<span class="badge badge-pill" :class="[message.uid != myID ?'badge-primary':'badge-secondary']">{{ message.message }}</span>
</div>
</div>
<div class="message-typing-container">
<form id="messages_form" action="" method="POST">
<div class="typing-container">
<input id="message" v-model="messages" type="text" class="message-typing" autocomplete="off" />
<input class="send-message" type="submit" value="Send" #click="sendMessage(item.memberID, item.tour)" />
</div>
</form>
</div>
</div>
<hr />
</div>
var firebaseConfig = {
apiKey: "xxxxxxxxxxxxxxxxxxxxxxxxx",
authDomain: "xxxxxxxxxxxxxxxxxxxxx",
databaseURL: "xxxxxxxxxxxxxxxxxxxxx",
projectId: "xxxxxxxxxxxxx",
storageBucket: "xxxxxxxxxxxxxxxxxxx",
messagingSenderId: "xxxxxxxxxxxxx",
appId: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
};
firebase.initializeApp(firebaseConfig);
let app = new Vue({
el: "#app",
data() {
return {
memberData: {},
myMessages: [],
memberMessages: [],
myID: userID,
messages: "",
messageBox: 0,
conversation: {},
isLoading: true,
memberBox: 0,
};
},
created: function () {
this.getAllMessages();
},
methods: {
scrollBox: function () {
let messagebox = document.querySelector("#messages-container");
messagebox.scrollTop = messagebox.scrollHeight;
},
getAllMessages: function () {
let distinct = "";
firebase
.firestore()
.collection("messages")
.where("memberID", "==", `${this.myID}`)
.orderBy("date")
.onSnapshot((res) => {
let members = [];
res.forEach((doc) => {
members.push(doc.data().uid);
});
distinct = Array.from(new Set(members));
this.getUserToTalk(distinct);
});
},
getMyMessages: function (memberID) {
let myMessages = [];
firebase
.firestore()
.collection("messages")
.where("uid", "==", `${this.myID}`)
.where("memberID", "==", `${memberID}`)
.orderBy("date")
.onSnapshot((res) => {
res.forEach((doc) => {
myMessages.push(doc.data());
});
});
return myMessages;
},
getMessages: function (memberID) {
let messages = [];
firebase
.firestore()
.collection("messages")
.where("uid", "==", `${memberID}`)
.where("memberID", "==", `${this.myID}`)
.orderBy("date")
.onSnapshot((res) => {
res.forEach((doc) => {
messages.push(doc.data());
});
});
return messages;
},
getUserToTalk: function (memberID) {
axios
.post("http://localhost/backend/getMemberToTalk.php", {
token: token,
whoToTalkTo: memberID,
})
.then((response) => {
// console.log(response.data);
if (response.data != "Error receiving data") {
let joinedData = [];
response.data.forEach((res) => {
let messages = this.getMessages(res.memberID);
let myMessages = this.getMyMessages(res.memberID);
// console.log(messages);
// console.log(myMessages);
let conversation = [];
let data = {};
setTimeout(() => {
conversation = [...messages, ...myMessages];
conversation.sort(function (a, b) {
return a.date - b.date;
});
// console.log(conversation);
if (conversation.length > 0) {
data = {
memberID: res.memberID,
memberProfileImg: res.memberProfileImg,
memberName: res.memberName,
memberLastname: res.memberLastname,
memberCity: res.memberCity,
memberState: res.memberState,
messages: conversation,
tour: conversation[0].tour,
};
this.isLoading = false;
} else {
this.isLoading = true;
this.getAllMessages();
}
joinedData.push(data);
}, 2000);
});
// console.log(joinedData);
this.memberData = joinedData;
console.log(this.memberData);
} else {
console.log(response.data);
}
})
.catch((error) => {
console.log(error);
});
},
sendMessage: function (memberID, tourID) {
$("#messages_form").on("submit", (e) => {
e.preventDefault();
let message = this.messages;
if (!message.trim()) return;
let postmessage = {
uid: JSON.stringify(this.myID),
memberID: JSON.stringify(memberID),
message: message,
date: Date.now(),
tour: "2",
};
// console.log(message);
this.messages = "";
this.memberData.forEach((res) => {
console.log(res.messages);
if (memberID == res.memberID) res.messages.push(postmessage);
});
console.log(this.memberData);
firebase.firestore().collection('messages').add({
uid: JSON.stringify(this.myID),
memberID: JSON.stringify(memberID),
message: message,
date: Date.now(),
tour: tourID
}).then(res => {
// console.log('Message sent: ' + res.message);
}).catch(e => console.log(e));
});
},
showConversation: function (memberID) {
// console.log(memberID);
// let id = $('.conversation-container').attr('id');
this.memberBox = memberID;
if (this.memberBox == memberID) {
$(".conversation-container").toggle("fast");
}
},
},
mounted() {},
});
i need to update the follow an unfollow button after axios request
<template>
<div v-if="isnot">
<a href="#" #click.prevent="unfellow" v-if="isfollowing" >unFellow</a>
<a href="#" #click.prevent="fellow" v-else >Fellow</a>
</div>
</template>
My Methods
fellow () {
axios.post(`/#${this.follower}/follow/`)
},
unfellow () {
axios.post(`/#${this.follower}/unfollow/`)
},
}
A basic example:
fellow () {
var self = this;
axios.post(`/#${this.follower}/follow/`)
.then(function (response) {
self.isfollowing = true;
})
.catch(function (error) {
console.log( error.response.data);
});
},
Axios has a series of methods you can execute after the response arrives. In the case of a post call your structure can be something like this
axios.post(YOUR ROUTE)
.then(function (response) {
//executes after getting a successful response
// here you can change your 'isfollowing' variable accordingly
})
.catch(function (error) {
//executes after getting an error response
});
Fast way:
<template>
<div v-if="isnot">
<a href="#" #click.prevent="fellowUnfellow" v-if="isfollowing" >{{isfollowing ? "unFellow" : "Fellow"}}</a>
</div>
</template>
fellowUnfellow () {
axios.post(`/#${this.follower}/follow/`).then(function (r) {
this.isfollowing = !this.isfollowing;
})
}
I've looked at all the threads that already exist on this topic and have not been able to come up with a solution for my case.
I have multiple forms rendering with the help of Handlebars like this:
<ul>
{{#each listRecords}}
<form id="form{{id}}" action="/expand-list-records-save/{{../listId}}/{{id}}" method="POST">
<div class="record-box">
<li>{{recordTitle}} by {{artistName}} ({{releaseYear}})
<br>
<div>
<label>Paste media embed code here:</label>
<textarea class="form-control form-control-lg" name="embeddedmedia" cols="30" rows="10">{{embeddedMedia}}</textarea>
</div>
<br>
<br>
</li>
</div>
</div>
</form>
{{/each}}
</ul>
<input id="submit" class="btn btn-secondary btn-block" type="submit" value="Submit embed code" >
<script>
$(document).ready(() => {
$('#submit').click(function submitAllForms() {
for (var i=0; i < document.forms.length; i++) {
console.log(`submitting ${document.forms[i].id}`)
document.forms[i].submit();
}
})
})
</script>
my Node.js + Express.js route looks like this
router.route('/expand-list-records-save/:listId/:recordId')
.post((req, res) => {
// console.log(req)
Record.findOne({
where: {
id: req.params.recordId
}
}).then(result => {
// console.log(req.body)
result.update({
embeddedMedia: req.body.embeddedmedia
})
}).then(() => {
console.log("sending list to view")
sendListDataToView({ params: {id: req.params.listId} }, res, 'view-list')
})
})
I'm having a few problems. First of all, this logic only executes a POST request for the item that the very last form on the page is for. Why is it that the console.log works for every single instance in my loop when iterating through all the document forms? From what I know, I think I need to use AJAX here somehow to execute all the POST requests. And the second main thing that I don't think is giving me problems at this point, but will once I get the first issue solved, is that my route is not written to handle a batch of requests like I need it to.
UPDATE
Upon a recommendation in comments, I decided try and write an Ajax request to post all of the forms to a separate route which will handle it from there. How do I pass an array of forms to the data parameter? I get the Uncaught RangeError: Maximum call stack size exceeded error this way:
$(document).ready(() => {
$('#submit').click(function submitAllForms() {
$.ajax({
type: 'POST',
url: window.location.origin + $('h3')[0].innerText,
data: document.forms,
success: (data) => {
console.log(data)
}
})
})
})
After going through some other examples, I tried rewriting original submit script like this. And, in this case, it does not pick up the action attribute.
$(document).ready(() => {
$('#submit').click(function submitAllForms() {
$('form').each(() => {
var that = $(this);
$.post(that.attr('action'), that.serialize())
})
})
})
So, I have finally come up with a solution, if anyone is interested. Perhaps not prettiest, but it works.
<script>
$(document).ready(() => {
$('#submit').click(function submitAllForms() {
var counter = 0;
var totalForms = $('form').length;
$('form').each((i, form) => {
const redirectIfDone = () => {
if (counter === totalForms) {
alert("all forms updated successfully")
window.location.replace(window.location.origin + '/list/' + $('h3')[0].innerText)
}
}
if (!($(form).find('textarea').val())) {
counter++
redirectIfDone();
return true;
} else {
$.ajax({
type: 'POST',
url: $(form).attr('action'),
data: $(form).serialize(),
success: (data) => {
counter++;
redirectIfDone();
}
})
}
})
})
})
</script>
Virtually no changes to the route. Overall, I'm still interested in seeing other possible solutions.
router.route('/expand-list-records-save/:listId/:recordId')
.post((req, res) => {
Record.findOne({
where: {
id: req.params.recordId
}
}).then(result => {
result.update({
embeddedMedia: req.body.embeddedmedia
})
res.end()
})
})
I am using vue.js 2 with webpack template. i am new to vue.js.
i want to bind DOM after data is received in ajax call.
here in my code contains v-for in which the response html is need to bind with v-html="tHtml[index]" every time after data is received from api call.
What can be used to re-bind or refresh view/DOM as we use $scope.$apply() in angularjs.
home.vue
<template>
<div class="row" id="home">
<h3 v-if="msg"><span class="label label-warning">{{msg}}</span></h3>
</div>
<div v-for="obj in tdata">
<div v-html="tHtml[$index]"></div>
</div>
</div>
</template>
<script>
import appService from '../service'
import bus from '../service/bus'
export default {
created() {
appService.checkAuth();
console.log("service appService val: "+appService.user.authenticated);
//called after vue has been created
bus.$on('eventBusWithTopic', (data) => { //fetch event bus on ready to get data
//alert("event fetched! "+data.user_id);
console.log("event fetched! "+data.user_id);
this.searchedTopic = data.topic;
this.user_id = data.user_id;
bus.$off('eventBusWithTopic'); //un-bind event after use
//check details
})
},
data() {
return {
searchedTopic: '',
user_id: '',
tdata: {},
tHtml: []
}
},
methods: {
getdata(){
console.log("dfd "+this.user_id);
appService.getdata(this, this.user_id, this.searchedTopic).success((res) => {
//console.log(" res: "+JSON.stringify(res));
this.tdata = res.data;
if(this.tdata.length > 0){
//**GET HTML** // <<--==--==--==
for(var i=0;i<this.tdata.length;i++){
this.getTemplate(this.tdata[i].id_str);
}
}
if(res.success == 0)
this.msg = res.message;
}).error((e) => console.log("error while getting data: "+JSON.stringify(e)))
},
getTemplate(id){
this.$http.get("https://uqkcgyy8wb.execute-api..*****../user/"+id+"/getHtml", (resp) => {
//return resp.data.html;
this.tHtml[this.tHtml.length] = resp.data.html;
console.log(this.tHtml);
}).error((e) => console.log("error while getting html: "+JSON.stringify(e)))
}
}
}
</script>