I am trying to pass/get a specific data from one page to another page using NavParams but I always get undefined result in the console. I do not know what seems to be the problem. Here is my code:
order.ts (TS file where I want to get the data)
postOrder(ordernum) {
let headers = new Headers();
headers.append('Content-Type', 'application/json');
let data=JSON.stringify({
mode_code: this.data2code,
order_totalpayment: this.dataquantity,
order_status: this.status
});
this.http.post('http://<--My JSON API-->/xxx/api.php/ordered?transform=1',data,headers)
.map(res => res.json())
.subscribe(res => {
console.log("Success Order No.: "+res);
this.ordernum = res;
let data2=JSON.stringify({
order_no: this.ordernum,
prod_id: this.dataid,
order_subtotal: this.dataquantity
});
this.http.post('http://xxxx/xxx/api.php/order_list?transform=1',data2,headers)
.map(resp => resp.json())
.subscribe(resp => {
console.log("Order List No.: "+resp);
this.nav.setRoot(ConfirmorderPage, { ordernum: ordernum });
}, (err) => {
this.showPopup("Oops!", "Something went wrong.");
});
}, (err) => {
this.showPopup("Oops!", "Something went wrong.");
});
}
In the code, what I am trying to get is the this.ordernum data. So that I use this codes: postOrder(ordernum) this.nav.setRoot(ConfirmorderPage, { ordernum: ordernum });
order.html (HTML file in where I did pass the data to another page)
<div">
<div padding>
<p>Your Order Number is {{ordernum}}</p>
</div>
</div>
<div style="margin: 10px;">
<button ion-button block color="orange" (click)="postOrder(ordernum)" >Place Order</button>
</div>
</div>
the data I wanted was the ordernum so that I put it in the click function (click)="postOrder(ordernum)"
confirmorder.ts (TS file where I want to pass the data ordernum from the orderpage)
constructor(public navCtrl: NavController, public navParams: NavParams) {
this.order = this.navParams.get('ordernum');
console.log(this.order);
}
I used this.navParams.get('ordernum') to get the data from the orderpage and
I pass the ordernum data to the this.order variable but when I tried to show it in the console, I am getting undefined result. I have no idea what is wrong with my code. Hope you guys can help me. Thank you in advance.
this.nav.setRoot(ConfirmorderPage, { ordernum: ordernum });
Here in your object, both key and value are the value of variable ordernum. Your key needs to be a string so use quotes.
Also use this to ensure you point to the correct variable (you seem to have a class variable as well as a parameter of name ordernum?).
Do:
this.nav.setRoot(ConfirmorderPage, { 'ordernum': this.ordernum });
Related
I am Working at a VueJS Webapplication with a c# WebAPI in the background. I made already one endpoint but I cant get it to work. The body of the response is always null. When i check the debug section on the network tab, i can see the message i want to get in the preview section, but I cant get it to show on the page.
VueJS component:
<template>
<div class="dashboard">
<button type="button" id="get-joke" #click="fetchAPIData">Get a Joke!!</button>
<div v-if="responseAvailable == true">
<hr>
<p>
<i>{{result}}</i>
</p>
<hr>
</div>
</div>
</template>
<script>
export default {
name: 'Dashboard',
props: {
msg: String
},
components: {
},
Data() {
result: null,
responseAvailable: null
},
methods: {
fetchAPIData() {
this.responseAvailable = false;
fetch("https://localhost:44322/api/values", {
"mode": "no-cors",
"method": "GET",
})
.then(response => {
alert(response); //checking if i get something
return response.json();
})
.then(response => {
this.result = response.body;
this.responseAvailable = true;
})
.catch(err => {
var error = err;
return error;
});
}
}
};
</script>
C# API Controller (returning a JSON string of a list of Objects) :
using System;
using Microsoft.AspNetCore.Mvc;
using MO_Backend.Services;
using MO_Backend.APIServices;
namespace MO_Backend.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
private readonly O_UserService _oUserService;
public ValuesController(O_UserService oUserService)
{
_oUserService = oUserService;
}
// GET: api/values
[HttpGet]
public String Get()
{
OnlineCheckService occ = new OnlineCheckService(_oUserService);
return occ.GetRobotState();
}
}
}
Does anyone know what im doing wrong or an alternative to what im trying to do?
The problem is the no-cors mode in your http request. This results in an opaque request, which means you get a response, but you cannot use the data. You need to use cors and set the response headers in your backend accordingly.
I have this code
(Pay attention to the HTML class 'symbolTicket "')
<template>
<div class="chart">
<span class="symbolTicket">
{{getTicket()}}
</span>
<div class="chartContent">
</div>
<!-- <div class="chartContent"> end -->
</div>
<!-- <div class="chart"> end -->
</template>
<script>
import axios from 'axios';
export default{
data() {
return {
};
},
methods: {
getTicket: function () {
return axios.get("http://localhost:2000/" , {
params: {
foo: 'SELECT * FROM eur_usd WHERE primary_key = 2;'
}
})
.then(function (response) {
console.log(response.data.ticket);
return response.data.ticket;
})
.catch(function (error) {
console.log(error);
});
},
},
}
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
I need to somehow get the value out of the query.
P.S. The result of the current solution can be seen on the screen.
From the top you can see what value is returned. (Object instead of data)
From the bottom of the console log - we see that the answer itself is working (no errors.)
It is this data that needs to be displayed inside the tag.
The standard way to do this would be to display a data property in the template.
<span class="symbolTicket">
{{ ticket }}
</span>
data () {
return {
ticket: null
}
}
Then load the value from the created hook:
created () {
this.getTicket()
},
methods: {
getTicket () {
return axios.get("http://localhost:2000/" , {
params: {
foo: 'SELECT * FROM eur_usd WHERE primary_key = 2;'
}
})
.then(response => {
const ticket = response.data.ticket;
// Update the data property
this.ticket = ticket;
console.log(ticket);
return ticket;
})
.catch(function (error) {
console.log(error);
});
}
}
The method getTicket is making an asynchronous request to the server so there's no way it can return the ticket directly. All it can return is the corresponding promise. The template needs the value synchronously, so relying on the return value from getTicket can't work.
You may also need to handle the case where ticket is null. During the initial rendering the request to the server won't have completed, so ticket will still be null.
If you're happy using async/await the getTicket method can be simplified but it won't change the overall flow described above. You still need a separate data property to hold the result.
I am trying to use Vue.js for my front end to call Stripe and create a token which then is sent to my backend. I have tested everything using plain HTML/JS and it all works fine, my issue comes in trying to use Vue.js I think my issue might be in how I am binding the stripe public key. Below is my code, and I have zero output to speak of, I get just redriected to the same page but wth ? at the end of the URL. Nothing else, console shows nothing and no error message or anything send to my back end.
template code
There is more but not related
<div class="col-md-8">
<card class='stripe-card col-md-8'
:class='{ complete }'
:stripe='stripeKey'
:options='stripeOptions'
#change='complete = $event.complete'
/>
<button class='pay-with-stripe' #click='pay' :disabled='!complete'>Submit Payment Details</button>
<br>
</div>
script section with relavent added
import { Card, createToken } from 'vue-stripe-elements-plus'
import axios from 'axios';
export default {
components: { Card },
data() {
return {
errorMessage: null,
successMessage: null,
complete: false,
stripeKey: process.env.VUE_APP_STRIPE_PUB_KEY,
stripeOptions: {
// see https://stripe.com/docs/stripe.js#element-options for details
hidePostalCode: true
},
current: {
stripe: {
plan: null,
last4: null
}
},
}
},
methods: {
pay () {
createToken().then(result => {
axios.post('/billing/updateCard', {
token: result.token,
})
.then(res => {
if(res.data.success == true) {
this.successMessage = res.data.message
console.log(res.data.message)
}
if(res.data.success == false) {
this.errorMessage = res.data.message // Display error message from server if an error exists
}
})
.catch((err) => {
if(err) console.log(err)
if(err) this.$router.push('/company/settings?success=false')
})
});
}
}
}
</script>
I have checked that the API key is actually in the data value by doing <p>{{ stripeKey }}</p> and seeing the value show up. So yes the key is there and the key is valid (tested copy/paste into my HTML/JS test)
created(){
this.key=process.env.VUE_APP_STRIPE_KEY;
}
try this, i used this piece of code in my project and it worked... the issue maybe is that your key is not yet initialized when card us rendered idk. maybe key isnt issue at all. try this and let me know if works and we will debug it together.
Hi friends i am using laravel 5.6 with vue.js for crud function . I want to get the posts which i just posted in posts section without reloading the whole page again. I have written this code but these codes are sending the data to the console but not to the posts view section .
My app.js looks like this
const app = new Vue({
el: '#app',
data: {
msg: 'Update new Post:',
content:'',
posts:[]
},
ready:function(){
this.created();
},
created(){
axios.get('http://{mylink}/home/post')
.then(response=>{
console.log(response.data);//show if success
this.posts = response.data; // putting posts into array
})
.catch(function (error) {
console.log(error.response);
});
},
methods:{
addPost(){
axios.post('http://{mylink}/home/addPost', {
content:this.content
})
.then(function(response){
console.log('Data updated');
if (response.status == 200) {
alert('Your post has been updated');
app.posts=reponse.data;
}
})
.catch(function(error){
console.log(error.response);
});
}
}
});
my controllers looks like this
public function posts(){
$posts=DB::table('posts')
->leftJoin('users','users.id','posts.user_id')
->leftJoin('profiles','profiles.user_id','posts.user_id')
->get();
return view('home',compact('posts'));
}
public function addPost(Request $request){
$content = $request->content;
$createPost=DB::table('posts')
->insert(['content'=>$content,'user_id'=>Auth::user()->id,
'status'=>0,'created_at'=>date("Y-m-d H:i:s"),'updated_at'=>date("Y-m-d H:i:s")]);
if($createPost){
$posts_json = DB::table('posts')
->leftJoin('users','users.id','posts.user_id')
->leftJoin('profiles','profiles.user_id','posts.user_id')
->orderBy('posts.created_at','DESC')->take(2)
->get();
return $posts_json;
}
}
Routes looks like this
Route::post('/home/addPost','PostController#addPost')->name('home.addPost');
Route::get('/home/post',function(){
$posts_json = DB::table('posts')
->leftJoin('users','users.id','posts.user_id')
->leftJoin('profiles','profiles.user_id','posts.user_id')
->orderBy('posts.created_at','DESC')
->get();
return $posts_json;
});
and my view looks like this
<div v-for="post in posts">
<div class="card">
<div class="card-body">
<blockquote class="blockquote mb-0">
<p>#{{post.content}}</p>
<footer class="blockquote-footer">Status By <cite title="Source Title">#{{post.name}}</cite> <img src="{{url('/')}}/img/" alt="Card image cap" height="30px" width="30px" style="border-radius:50%;"></footer>
</blockquote>
</div>
</div>
</div>
I see many problems to your code but if the problem is only in addPost (you said that there is the problem) method then replace it with the follow:
addPost(){
axios.post('http://{mylink}/home/addPost', {
content:this.content
})
.then(response => {
console.log(response.data);
if (response.status == 200) {
alert('Your post has been updated');
this.posts = reponse.data;
}
})
.catch(error =>{
console.log(error.response);
});
}
also if you replace your method with the method that i posted you will be able to see what response you get from backend since i console logged it.Then you will see if you get a desired response
As noted in your comments above, this is an issue with authorization. I'll leave my old answer here for posterity, but including the status code from the start of the question would be good next time.
I believe your 'this' context is invalid when used inside the callback like that. Try something like this (edit) just realized you wanted the addPosts section:
addPost(){
let vm = this;
axios.post('http://{mylink}/home/addPost', {
content:this.content
})
.then(function(response){
console.log('Data updated');
if (response.status == 200) {
alert('Your post has been updated');
vm.posts=reponse.data;
}
})
.catch(function(error){
console.log(error.response);
});
}
I want to know how to create PHP to get data for show home.html
and I get `Error data is not defined
I don't know this correct? please check this. I have not idea to create PHP, I want to set $path to keep my URL.
<ion-content>
<ion-list inset>
<ion-item>
<ion-label>Username</ion-label>
<ion-input [(ngModel)]="data.username" type="text"></ion-input>
</ion-item>
</ion-list>
<div padding>
<button ion-button block (click)="getRepos()">Search</button>
</div>
<ion-card *ngFor="let repo of foundRepos" >
<ion-card-header>
{{ repo.data.name }}
</ion-card-header>
<ion-card-content>
{{ repo.data.description }}
</ion-card-content>
</ion-card>
</ion-content>
.
import { Component } from "#angular/core";
import { NavController } from 'ionic-angular';
import { Http } from '#angular/http';
#Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
public foundRepos;
constructor(public http: Http) {
this.data = {}; >>>>>>>data is not defined
data.username = ''; >>>>>data is not defined
this.http = http;
}
getRepos() {
var link = 'http://localhost/github.php';
var data = JSON.stringify({username: this.data.username}); <<<<this.data.username (data is not defined)
this.http.get(link, data) <<<<data is not defined
.subscribe(data => {
this.foundRepos = data.json();
},
err => console.error(err),
() => console.log('getRepos completed')
);
}
}
github.php
<?php
$postdata = file_get_contents("php://input");
if (isset($postdata)) {
$request = json_decode($postdata);
$username = $request->username;
if ($username != "") {
$path = "https://api.github.com/users/".$username."/repos";
echo $path ;
}
else {
echo "Empty username parameter!";
}
}
else {
echo "Not called properly with username parameter!";
}
?>
Ah I see.
In your php you're retrieving a value called $postdata. So I assume you want to send the username from your ionic 2 application to your php file.
2 options, you should try them both because I do not understand php so I'm not sure what the right solution is.
But I do know what the problem is. You're making an http.get() call, and you're passing 2 arguments in this. link and data. The GET method is for getting data from your link, not giving it. The http.get takes 2 parameters, the url, in your case named link, and an HttpHeaders object, so not data.
Solution with parameter in http.get
So, as mentioned above, http.get() can't send your data. Unless you add it as a parameter in your URL. Then your typescript would look like this (note: backticks instead of ' ', makes string concatination easier):
var link = `http://localhost/github.php?username=${this.data.username}`;
this.http.get(link).subscribe(data) { .... }
And in php replace
$username = $response->username
with
$username = $_GET['username']
So final typscript looks like this (since php get request returned 403, Github probably disallowed it)
getRepos() {
var link = `localhost/…${this.data.username}`;
this.http.get(link)
.subscribe(data => {
let repoUrl = data.text();
this.http.get(repoUrl).subscribe(githubResponse => {
this.foundRepos = githubResponse.json();
});
},
err => console.error(err),
() => console.log('getRepos completed')
);
}
If anyone is seeking detailed explanation to why we came to this answer, pleek look in the chat below
You have not declared data variable in the class.
export class HomePage {
public foundRepos;
public data;//here
constructor(public http: Http){
this.data = {};
this.data.username = '';//to refer to data in any function always use 'this'
}
//other functions