Angular 6 :
import {Injectable} from '#angular/core';
import { HttpClient } from '#angular/common/http';
#Injectable()
export class GetData {
constructor( private http: HttpClient ) { }
post( ) {
data = [ {username : 'test',password : '1234' }];
return this.http.post('login.php' , data );
}
}
PHP : login.php
<?php
$username = $_POST['username'];
$password = $_POST['password'];
?>
How can i get data from Angular 6 that is [Object] into $username , $password
**
"$_POST" and "$_REQUEST" is not available for me.
**
Try this:
import {Injectable} from '#angular/core';
import { HttpClient,HttpParams } from '#angular/common/http';
#Injectable()
export class GetData {
constructor( private http: HttpClient ) { }
post( ) {
let data= new HttpParams()
.append("username", "test")
.append("password", "1234")
return this.http.post('login.php' , data );
}
}
For some reason Angular seems to send POSTs that end up in php://input instead of $_POST, and then you can json_decode them into an object and use them.
On the Angular side - I'm just tossing data at the server, I care not about the response... tried getting it going without the whole subscribe() thing but it wouldn't POST at all for me at that point... Note taht there is a private http: Http in the constructor for the TS file/component/class this is in...
postChatMessage(room: string, user: string, msg: string, timestamp: number) {
var cmsg = new ChatMessage(room, msg, user, timestamp);
return this.http.post(BASEURL + "/chat", cmsg)
.subscribe(
(v) => {},
response => {},
() => {}
);
}
The PHP on the back end that handles the POST that sends - yes, I'm being lazy and just storing the whole JSON string sent plus a few other things, but easier for me to deal with for a quick school thing -
if (($_SERVER['REQUEST_METHOD'] == "POST") &&
(strpos($_SERVER['REQUEST_URI'], "/json_service/chat") === 0)) {
$d = file_get_contents("php://input");
$d = json_decode($d);
$d->timestamp = time();
$q = "insert into json_chat values(?,?,?,?)";
$a = array(null, time(), $d->room, json_encode($d));
$res = executeQuery($q, $a);
print(json_encode(array($res[0]))); // boolean fwiw
exit;
}
Related
I am trying to fetch some data from server using json in my flutter app. This is the function I am using.
List<String> userFriendList = ["No Friends"];
Future<http.Response> _fetchSampleData() {
return http.get('//link/to/server/fetcher/test_fetcher.php');
}
Future<void> getDataFromServer() async {
final response = await _fetchSampleData();
if (response.statusCode == 200) {
Map<String, dynamic> data = json.decode(response.body);
userLvl = data["lvl"].toString();
userName = data["name"];
userFriendList = List();
userFriendList = data["friendlist"];
} else {
// If the server did not return a 200 OK response,
// then throw an exception.
print('Failed to load data from server');
}
}
I get the usrLvl and userName right. But for userFriendList, I get the following error:
[ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: type 'List<dynamic>' is not a subtype of type 'List<String>'
Code on the server end (test_fetcher.php) :
<?php
$myObj->name = "JohnDoe";
$myObj->lvl = 24;
$friends = array("KumarVishant", "DadaMuni", "BabuBhatt", "BesuraGayak", "BabluKaneria", "MorrisAbhishek", "GoodLuckBaba", "ViratKohli", "LeanderPaes");
$myObj->friendlist = $friends;
header('Content-Type: application/json');
$myJSON = json_encode($myObj);
echo $myJSON;
?>
This is a cast error: List<dynamic> != List<String>
You can convert / cast your list in several ways.
I advise you to use this library to simplify your json / Dart object conversion
: https://pub.dev/packages/json_serializable
json_serializable will generate the conversion methods (fromJson and toJson) and take care of everything.
It's easier and safer than doing it manually.
Just what the error says. The userFriendList is of type List you have it as List.
List<String> userFriendList = ["No Friends"];
Should be
List<dynamic> userFriendList = [];
Or a different list entirely if this doesn't work for you.
The error explains it. The fetched data from the server api is decoded to type List<dynamic> and you declared userFriendList to be of type List<String>. What you need to do is change the type of userFriendList from
List<String> userFriendList = ["No Friends"];
to:
List<dynamic> userFriendList = [];
So I tried to connect my android app with the database that I stored in Phpmyadmin. I am using Volley since a lot of people recommend this. I followed some tutorials and finally got this code:
lateinit var etLoginEmail : EditText
lateinit var etLoginPass : EditText
lateinit var btnLog_in : Button
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_login)
if(android.os.Build.VERSION.SDK_INT > 9){
StrictMode.setThreadPolicy(StrictMode.ThreadPolicy.Builder().permitAll().build())
}
etLoginEmail = findViewById(R.id.etLoginEmail) as EditText
etLoginPass = findViewById(R.id.etLoginPass) as EditText
btnLog_in = findViewById(R.id.btnLog_in) as Button
btnLog_in.setOnClickListener {
if (etLoginEmail?.text.isNullOrEmpty()) {
etLoginEmail?.error = "Email must be filled"
} else if (etLoginPass?.text.isNullOrEmpty()) {
etLoginPass?.error = "Password must be filled"
} else{
doLogin(etLoginEmail.text.toString(), etLoginPass.text.toString())
}
}
}
fun doLogin(userEmail: String, userPass: String){
val stringRequest = object : StringRequest(Request.Method.POST, "http://localhost/my_app/login.php",
Response.Listener<String> { response ->
Toast.makeText(applicationContext, response.toString(), Toast.LENGTH_LONG).show()
try {
val obj = JSONObject(response)
startActivity(Intent(this, TabbedHome::class.java))
finish()
Toast.makeText(applicationContext, obj.getString("message"), Toast.LENGTH_LONG).show()
} catch (e: JSONException) {
e.printStackTrace()
Toast.makeText(applicationContext, "please try again", Toast.LENGTH_LONG).show()
}
},
object : Response.ErrorListener {
override fun onErrorResponse(volleyError: VolleyError) {
Toast.makeText(applicationContext, volleyError.message, Toast.LENGTH_LONG).show()
}
}) {
#Throws(AuthFailureError::class)
override fun getParams(): Map<String, String> {
val params = HashMap<String, String>()
params.put("user_email", userEmail)
params.put("user_pass", userPass)
return params
}
}
VolleySingleton.instance?.addToRequestQueue(stringRequest)
}
I imported these Volley tools on my Login.kt class
import com.android.volley.AuthFailureError
import com.android.volley.Request
import com.android.volley.VolleyError
import com.android.volley.toolbox.StringRequest
import com.android.volley.Response
However, the volley code is not working when I run the app on my device. I also don't get any error in the logcat. When I clicked the button, it didn't do anything. Not even showing any error message. Only some error like this E/ANDR-PERF-MPCTL: Invalid profile no. 0, total profiles 0 only
I tried my php code on postman and it works like a champ. This is my php code:
<?php
session_start();
require_once 'connection.php';
if($_SERVER["REQUEST_METHOD"]=="POST"){
$user_email = $_POST["user_email"];
$user_pass = $_POST['user_pass'];
}
if ((empty($user_email)) || (empty($user_pass))) {
$response->success = 0;
$response->message = "Field must be filled";
die(json_encode($response));
}
$query = mysqli_query($con, "SELECT * FROM tb_user WHERE user_email='$user_email'");
$row = mysqli_fetch_array($query);
$result = $mysqli->query($row);
$followingdata = $result->fetch_assoc();
$_SESSION['user_id'] = $row['user_id'];
if (password_verify($user_pass, $row['user_pass'])) {
if (!empty($row)){
$response = new usr();
$response->success = 1;
$_SESSION['user_id'] = $_POST['user_id'];
$response->message = "Welcome ".$row['user_name'];
$response->user_id = $row['user_id'];
$response->user_name = $row['user_name'];
$_SESSION['user_id'] = $row['user_id'];
$user_id = $row['user_id'];
die(json_encode($response));
}
} else {
$response->success = 0;
$response->message = "Email or pass is in correct";
die(json_encode($response));
}
mysqli_close($con);
?>
I tried to search some problems that looks like mine all over the Internet but still couldn't find the answer to my problem. I also already put this code on my AndroidManifest.xml below the <manifest> tag and right before the <application> tag.
<uses-permission android:name="android.permission.INTERNET"/>
And this is the dependency that I imported.
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
implementation 'android.arch.lifecycle:extensions:1.1.1'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
implementation 'com.android.volley:volley:1.1.0'
implementation 'com.squareup.retrofit2:retrofit:2.1.0'
implementation 'com.squareup.retrofit2:converter-gson:2.1.0'
implementation 'com.google.code.gson:gson:2.6.1'
implementation 'com.squareup.okhttp3:okhttp:3.2.0'
implementation "com.squareup.retrofit2:adapter-rxjava2:2.3.0"
implementation "com.squareup.retrofit2:converter-moshi:2.0.0"
implementation "io.reactivex.rxjava2:rxandroid:2.0.1"
implementation 'com.squareup.okhttp3:logging-interceptor:3.4.1'
implementation 'com.android.support:design:28.0.0'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}
I imported more than 1 dependencies to pass the data because I tried it all and nothing has worked...
Can someone please tell me what did I do wrong? Any help will be really appreciated. Thank you so much!!!
At php side you are decoding json but at android side you are passing parameters as form-data.
So, either change php-side code to receive form-data or pass data in raw-form (as JSON) at Android side.
To receive form-data with POST request try below_code:
if($_SERVER["REQUEST_METHOD"]=="POST"){
$user_email = $_POST["user_email"];
$user_pass = $_POST['user_pass'];
}
With above code you can get posted form-data at PHP.Now you can do whatever you want with the data.
I am making an android application where I need to fetch data from an online database. The online database has 3 columns, Date, Time and Varchar(255).
Here is my PHP code:
<?php
require "connection.php";
if($result = mysqli_query($conn, "select * from `xuberance_updates`")) {
while($row = mysqli_fetch_assoc($result)) {
echo $row["date"].",".$row["time"].",".$row["updates"].";";
}
}
?>
And here is my kotlin code in android:
class RefreshTask(private val alertDialog: AlertDialog) :
AsyncTask<String, Void, String>() {
override fun onPreExecute() {
...
alertDialog.show()
...
}
override fun doInBackground(vararg params: String?): String? {
val url = URL("https://.../show_update.php")
val httpURLConnection = url.openConnection() as HttpURLConnection
httpURLConnection.doInput = true
httpURLConnection.doOutput = true
httpURLConnection.requestMethod = "POST"
httpURLConnection.connect()
val reader = BufferedReader(InputStreamReader(httpURLConnection.inputStream, "UTF-8"))
var line = reader.readLine()
val result = StringBuilder()
while (line != null) {
result.append(line)
line = reader.readLine()
}
reader.close()
httpURLConnection.disconnect()
return result.toString()
}
override fun onPostExecute(result: String?) {
alertDialog.dismiss()
...
}
...
}
When I start the AsyncTask, The dialog appears. But it never gets dismissed. The onPostExecute(result: String?) method is never reached. How to fix this?
Edit: Sometimes, It successfully reaches the onPostExecute(result: String?) method. But most of the times, I need to wait for 2 or more minutes to get to that method.
Use this library to make network calls. Very simple yet efficient.
http://loopj.com/android-async-http/
this should be culprit
while (line != null) {
result.append(line)
line = reader.readLine()
}
I have a problem about service in Angular2/4.
I keep getting
ERROR SyntaxError: Unexpected token ' in JSON at position 0.
This is my backend using CI.
This is my controller book.php:
//get book from database
function list_book_get()
{
//call method get_list_book() in model m_book
$dataBook = $this->m_book->get_list_Book();
//if dataBook exist
if($dataBook != null) {
$output['status'] = true;
$output['data'] = $dataBook;
} else { // if dataBook not exist
$output['status'] = false;
$output['message'] = "empty";
}
//send response
$this->response(json_encode($output));
}
The model in CI:
function get_list_book() {
return $this->db->get('book')->result();
}
And this is my service in Angular 4:
import { Injectable } from '#angular/core';
import { Http } from '#angular/http';
import 'rxjs/add/operator/map' ;
#Injectable()
export class BookService {
constructor(private http: Http) {
}
books=[];
getBooks(){
return this.http.get("http://localhost/restserver/book/list_book.php")
.map(res => res.json());
}
}
That is my json from CI:
'{"status":true,"data":
[{"id":"1","title":"SAINS","author":"ERLANGGA","isbn":"089928778"},
{"id":"2","title":"Geography","author":"ERLANGGA","isbn":"089182372"},
{"id":"3","title":"Math","author":"Srilangka","isbn":"091283181"},
{"id":"4","title":"test","author":"test","isbn":"1283798127"},
{"id":"5","title":"AAAA","author":"BBB","isbn":"91092301290"},
{"id":"6","title":"BBB","author":"CCC","isbn":"01920192"}]}'
I assume that quotation mark (') in my json that make my apps error.
How to remove that quotations?
Proper way to send json reponse from CI Controller is :
function list_book_get()
{
...
return $this->output
->set_content_type('application/json')
->set_output(json_encode($output));
}
You are getting json in single quotes bcoz (means as string) , you
haven't defined the content type.
I recently started delving into custom classes in AS3 (to hone my best-practices coding habits), and wanted to create a database class that allows a user to first instantiate a class that contains all the information necessary for methods within the class to add, delete, modify (etc) rows in a MySQL table (via PHP). Of course, this involves using URLRequest, URLLoader and so forth. My question is whether anyone as figured a way how to return data from a method specifically containing that var data without relying upon the method essentially dispatching an event (then having to create a listener rather than having that built into the class). For example,
var myDB:dataBase = new dataBase("dbase","table","username","pword");
//this creates an instance of a database class with methods like:
trace(myDB.fetch(1)); //gets first row of table as a delimited string
OR
if (myDB.delete(1)) {}
//returns Boolean true if delete of row 1 was successful
I found the answer below that contained a way to create a class that returns an event:
Combining URLRequest, URLLoader and Complete Event Listener In Actionscript 3.0?
but I want the method to return a string containing data from the database or a boolean confirmation, not to dispatch an event listener. Here is an example of the class I made:
package com.customClasses {
import flash.net.URLLoader;
import flash.net.URLRequest;
import flash.net.URLVariables;
import flash.net.URLLoaderDataFormat;
import flash.net.URLRequestMethod;
import fl.events.DataChangeEvent;
import flash.events.Event
public class dataBase {
public var dbs:String = "";
public var usr:String = "";
public var pwd:String = "";
public var tab:String = "";
var returnData:String = "";
// Constructor
public function dataBase(dbs:String, usr:String, pwd:String, tab:String) {
this.dbs = dbs;
this.usr = usr;
this.pwd = pwd;
this.tab = tab;
}
public function fetch(idn:uint, par:String):String {
var returnData:String = "blank";
var vUrlReq:URLRequest = new URLRequest ("dBase.php");
var vUrlVars:URLVariables = new URLVariables();
function onLoadVarsComplete(event:Event): void {
//retrieve success variable from our PHP script:
if(event.target.data.msg == "success") {
var rawData:URLVariables = new URLVariables( event.target.data );
returnData = rawData.fromPHP;
} else {
returnData = "failed!";
}
}
vUrlReq.method = URLRequestMethod.POST;
vUrlVars.dir=dbs; // name of table affected
vUrlVars.alpha=usr; // username
vUrlVars.beta=pwd; // password
vUrlVars.dbase=tab; // name of table affected
vUrlVars.func="fetch"; // function for php script to use
vUrlVars.idnum=idn; //if >0 search for record with that id
vUrlReq.data = vUrlVars;
var vLoader:URLLoader = new URLLoader (vUrlReq);
vLoader.addEventListener("complete", onLoadVarsComplete);
vLoader.dataFormat = URLLoaderDataFormat.VARIABLES;
vLoader.load(vUrlReq);
return (returnData);
}
returnData returns "blank"... so I realize my method is not working as intended. I also realize there my be some scope issues with the returnData string, and that I am using a nested function (probably a no-no). Otherwise, any thoughts?
To do what you want, you can use a callback function or a DataEvent listener, like this :
DB.as :
package {
import flash.net.*;
import flash.events.*;
public class DB extends EventDispatcher {
public static const DATA_LOADED = 'data_loaded';
public function DB() {
}
public function getDataUsingDataEvent(file_path:String):void {
var url_loader:URLLoader = new URLLoader();
url_loader.addEventListener(
Event.COMPLETE,
function(e:Event):void
{
var event:DataEvent = new DataEvent(DATA_LOADED, true, false, url_loader.data);
dispatchEvent(event);
}
)
url_loader.load(new URLRequest(file_path));
}
public function getDataUsingCallback(file_path:String, callback:Function):void {
var url_loader:URLLoader = new URLLoader();
url_loader.addEventListener(
Event.COMPLETE,
function(e:Event):void
{
callback(url_loader.data);
}
)
url_loader.load(new URLRequest(file_path));
}
}
}
And then :
var db:DB = new DB();
db.addEventListener(
DB.DATA_LOADED,
function(event:DataEvent):void {
trace(event.data);
}
)
db.getDataUsingDataEvent('file_path');
db.getDataUsingCallback(
'file_path',
function(data:String):void {
trace(data);
}
)
Hope that can help.
As you've stated it, this can't be done in AS3. You cannot wait for an asynchronous operation (such as URLLoader/load()) before returning the function and continuing script execution.
What you can do, if you'd prefer not to use addEventListener() so much, is pass through callbacks, or implement method chaining of promises. These patterns are not necessarily better than using events, and have their own problems, but let you write code that is arguably more readable as a sequence. These patterns are common in Javascript (which has the same asynchronous behavior as ActionScript), for example jQuery. Beware of "callback hell" and "train wrecks". These techniques aim to make things simpler to write but sometimes make things more error prone.