PHP: parse data from UPS xml SOAP response - php

I've successfully implemented the UPS tracking API but the response is a complex xml file and I only need basic data from it. I need the status descriptions, dates and times and the delivery address.
<soapenv:Envelope
xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
<soapenv:Header/>
<soapenv:Body>
<trk:TrackResponse
xmlns:trk="http://www.ups.com/XMLSchema/XOLTWS/Track/v2.0">
<common:Response
xmlns:common="http://www.ups.com/XMLSchema/XOLTWS/Common/v1.0">
<common:ResponseStatus>
<common:Code>1</common:Code>
<common:Description>Success</common:Description>
</common:ResponseStatus>
<common:TransactionReference>
<common:CustomerContext>track order</common:CustomerContext>
</common:TransactionReference>
</common:Response>
<trk:Shipment>
<trk:InquiryNumber>
<trk:Code>01</trk:Code>
<trk:Description>ShipmentIdentificationNumber</trk:Description>
<trk:Value>1ZA474A76843297635</trk:Value>
</trk:InquiryNumber>
<trk:ShipperNumber>A474A7</trk:ShipperNumber>
<trk:ShipmentAddress>
<trk:Type>
<trk:Code>01</trk:Code>
<trk:Description>Shipper Address</trk:Description>
</trk:Type>
<trk:Address>
<trk:AddressLine>GRANGEFIELD IND EST</trk:AddressLine>
<trk:City>LEEDS</trk:City>
<trk:PostalCode>LS28 6QW</trk:PostalCode>
<trk:CountryCode>GB</trk:CountryCode>
</trk:Address>
</trk:ShipmentAddress>
<trk:ShipmentAddress>
<trk:Type>
<trk:Code>02</trk:Code>
<trk:Description>ShipTo Address</trk:Description>
</trk:Type>
<trk:Address>
<trk:AddressLine>75086</trk:AddressLine>
<trk:AddressLine>ROCKLINE INDUSTRIES LTD</trk:AddressLine>
<trk:AddressLine>HEMING ROAD</trk:AddressLine>
<trk:City>REDDITCH</trk:City>
<trk:PostalCode>B98 0DH</trk:PostalCode>
<trk:CountryCode>GB</trk:CountryCode>
</trk:Address>
</trk:ShipmentAddress>
<trk:ShipmentWeight>
<trk:UnitOfMeasurement>
<trk:Code>KGS</trk:Code>
</trk:UnitOfMeasurement>
<trk:Weight>1.00</trk:Weight>
</trk:ShipmentWeight>
<trk:Service>
<trk:Code>011</trk:Code>
<trk:Description>UPS Standard</trk:Description>
</trk:Service>
<trk:ReferenceNumber>
<trk:Code>16</trk:Code>
<trk:Value>757142/1</trk:Value>
</trk:ReferenceNumber>
<trk:ReferenceNumber>
<trk:Code>17</trk:Code>
<trk:Value>75086</trk:Value>
</trk:ReferenceNumber>
<trk:PickupDate>20230118</trk:PickupDate>
<trk:Package>
<trk:TrackingNumber>1ZA474A76843297635</trk:TrackingNumber>
<trk:PackageServiceOption>
<trk:Type>
<trk:Code>030</trk:Code>
<trk:Description>Hazardous Materials</trk:Description>
</trk:Type>
</trk:PackageServiceOption>
<trk:Activity>
<trk:ActivityLocation>
<trk:Address>
<trk:AddressLine>THE WASHFORD INDUSTRIAL EST</trk:AddressLine>
<trk:City>REDDITCH</trk:City>
<trk:PostalCode>B98 0DH</trk:PostalCode>
<trk:CountryCode>GB</trk:CountryCode>
</trk:Address>
<trk:Code>M4</trk:Code>
<trk:Description>Reception</trk:Description>
<trk:SignedForByName>DAWN</trk:SignedForByName>
</trk:ActivityLocation>
<trk:Status>
<trk:Type>D</trk:Type>
<trk:Description>Delivered</trk:Description>
<trk:Code>9E</trk:Code>
</trk:Status>
<trk:Date>20230119</trk:Date>
<trk:Time>095320</trk:Time>
<trk:Document>
<trk:Type>
<trk:Code>04</trk:Code>
<trk:Description>POD Letter</trk:Description>
</trk:Type>
<trk:Content>PCFET0NUWVBFIEhUTUwgUFVCTElDICItLy9XM0MvL0RURCBIVE1MIDQuMCBUcmFuc2l0aW9uYWwvL0VOIj48SFRNTD48SEVBRD48TUVUQSBIVFRQLUVRVUlWPSJDb250ZW50LVR5cGUiIENPTlRFTlQ9InRleHQvaHRtbDsgY2hhcnNldD1JU08tODg1OS0xIj48VElUTE0RZPjwvSFRNTD4=</trk:Content>
<trk:Format>
<trk:Code>03</trk:Code>
<trk:Description>HTML</trk:Description>
</trk:Format>
</trk:Document>
</trk:Activity>
<trk:Activity>
<trk:ActivityLocation>
<trk:Address>
<trk:City>Tamworth</trk:City>
<trk:CountryCode>GB</trk:CountryCode>
</trk:Address>
<trk:Description>Reception</trk:Description>
</trk:ActivityLocation>
<trk:Status>
<trk:Type>I</trk:Type>
<trk:Description>Out For Delivery</trk:Description>
<trk:Code>OF</trk:Code>
</trk:Status>
<trk:Date>20230119</trk:Date>
<trk:Time>052200</trk:Time>
</trk:Activity>
<trk:Activity>
<trk:ActivityLocation>
<trk:Address>
<trk:City>Tamworth</trk:City>
<trk:CountryCode>GB</trk:CountryCode>
</trk:Address>
<trk:Description>Reception</trk:Description>
</trk:ActivityLocation>
<trk:Status>
<trk:Type>I</trk:Type>
<trk:Description>Arrived at Facility</trk:Description>
<trk:Code>AR</trk:Code>
</trk:Status>
<trk:Date>20230119</trk:Date>
<trk:Time>013700</trk:Time>
</trk:Activity>
<trk:Activity>
<trk:ActivityLocation>
<trk:Address>
<trk:City>Preston</trk:City>
<trk:CountryCode>GB</trk:CountryCode>
</trk:Address>
<trk:Description>Reception</trk:Description>
</trk:ActivityLocation>
<trk:Status>
<trk:Type>I</trk:Type>
<trk:Description>Departed from Facility</trk:Description>
<trk:Code>DP</trk:Code>
</trk:Status>
<trk:Date>20230118</trk:Date>
<trk:Time>233000</trk:Time>
</trk:Activity>
<trk:Activity>
<trk:ActivityLocation>
<trk:Address>
<trk:City>Preston</trk:City>
<trk:CountryCode>GB</trk:CountryCode>
</trk:Address>
<trk:Description>Reception</trk:Description>
</trk:ActivityLocation>
<trk:Status>
<trk:Type>I</trk:Type>
<trk:Description>Arrived at Facility</trk:Description>
<trk:Code>AR</trk:Code>
</trk:Status>
<trk:Date>20230118</trk:Date>
<trk:Time>214500</trk:Time>
</trk:Activity>
<trk:Activity>
<trk:ActivityLocation>
<trk:Address>
<trk:City>Leeds</trk:City>
<trk:CountryCode>GB</trk:CountryCode>
</trk:Address>
<trk:Description>Reception</trk:Description>
</trk:ActivityLocation>
<trk:Status>
<trk:Type>I</trk:Type>
<trk:Description>Departed from Facility</trk:Description>
<trk:Code>DP</trk:Code>
</trk:Status>
<trk:Date>20230118</trk:Date>
<trk:Time>204000</trk:Time>
</trk:Activity>
<trk:Activity>
<trk:ActivityLocation>
<trk:Address>
<trk:City>Leeds</trk:City>
<trk:CountryCode>GB</trk:CountryCode>
</trk:Address>
<trk:Description>Reception</trk:Description>
</trk:ActivityLocation>
<trk:Status>
<trk:Type>I</trk:Type>
<trk:Description>Origin Scan</trk:Description>
<trk:Code>OR</trk:Code>
</trk:Status>
<trk:Date>20230118</trk:Date>
<trk:Time>163413</trk:Time>
</trk:Activity>
<trk:Activity>
<trk:ActivityLocation>
<trk:Address>
<trk:CountryCode>GB</trk:CountryCode>
</trk:Address>
<trk:Description>Reception</trk:Description>
</trk:ActivityLocation>
<trk:Status>
<trk:Type>M</trk:Type>
<trk:Description>Shipper created a label, UPS has not received the package yet.</trk:Description>
<trk:Code>MP</trk:Code>
</trk:Status>
<trk:Date>20230118</trk:Date>
<trk:Time>162032</trk:Time>
</trk:Activity>
<trk:PackageWeight>
<trk:UnitOfMeasurement>
<trk:Code>KGS</trk:Code>
</trk:UnitOfMeasurement>
<trk:Weight>1.00</trk:Weight>
</trk:PackageWeight>
<trk:ReferenceNumber>
<trk:Code>19</trk:Code>
<trk:Value>757142/1</trk:Value>
</trk:ReferenceNumber>
<trk:ReferenceNumber>
<trk:Code>19</trk:Code>
<trk:Value>75086</trk:Value>
</trk:ReferenceNumber>
</trk:Package>
</trk:Shipment>
</trk:TrackResponse>
</soapenv:Body>
</soapenv:Envelope>
The following code does seem to extract partial data but I don't see how to get the whole records out. Ideally I'd like to extract the records in a html table.
$sxe = new SimpleXMLElement($client->__getLastResponse());
$sxe->registerXPathNamespace('trk', "http://www.ups.com/XMLSchema/XOLTWS/Track/v2.0");
$codes = $sxe->xpath('//trk:AddressLine');
foreach ($codes as $c) {
echo "$c" . "</br>";
}

Related

Getting error response while sending email from ionic using PHPMailer

I am trying to create a reset password page in ionic where the user enter his email ,to reset the password of his account on my application.
The thing is that I want to send a response from php telling the user if the email was sent to his email or not depending on values sent from php to ionic. The thing that is happening is that the email is sent but it is showing me a response error.
Here is my typescript code:
async sendEmail() {
var regEmail = /^([a-zA-Z0-9\.-_]+)#([a-zA-Z0-9-]+).([a-z]{2,20})$/;
if (!regEmail.test(this.resetPasswordForm.value.email)) {
this.showToast("Invalid email");
return;
}
const loading = await this.load.create({
message: 'Please wait...'
});
loading.present();
this.auth.sendEmailVerification(this.resetPasswordForm.value).subscribe((data) => {
console.log(data);
if (data == "sent") {
this.showAlert("Great!", "We have sent you an email, check your inbox.");
this.resetPasswordForm.reset();
}
else if (data == "notfound") {
this.showAlert("Error!", "This email was not found.");
} else if (data == "error") {
this.showAlert("Oupss!", "An error occured and email could not be sent.");
}
}, (err) => {
console.log(err);
this.showAlert("Error!", err.message);
});
loading.dismiss();
}
The php code:
<?php
session_start();
require("headers.php");
require("connection.php");
$userData=file_get_contents("php://input");
$request=json_decode($userData);
$to=$request->email;
// Import PHPMailer classes into the global namespace
// These must be at the top of your script, not inside a function
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;
// Load Composer's autoloader
require 'phpmailer/src/PHPMailer.php';
require 'phpmailer/src/SMTP.php';
require 'phpmailer/src/Exception.php';
$con=connect();
$checkUser="SELECT count(*) from users where email='$to'";
$res=mysqli_query($con,$checkUser);
$row=mysqli_fetch_array($res);
if($row[0]==1){
// Instantiation and passing `true` enables exceptions
$mail = new PHPMailer(true);
try {
$randomNumber=mt_rand(100000,999999);
$_SESSION["random"]=$randomNumber;
//Server settings
$mail->SMTPDebug = 2; // Enable verbose debug output
$mail->isSMTP(); // Send using SMTP
$mail->Host = 'smtp.gmail.com'; // Set the SMTP server to send through
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = ''; // SMTP username
$mail->Password = ''; // SMTP password
$mail->SMTPSecure = 'tls'; // Enable TLS encryption; `PHPMailer::ENCRYPTION_SMTPS` encouraged
$mail->Port = 587; // TCP port to connect to, use 465 for `PHPMailer::ENCRYPTION_SMTPS` above
//Recipients
$mail->setFrom('no-reply#gmail.com','charbelalam755#gmail.com');
$mail->addAddress($to); // Add a recipient
print json_encode("sent");
// Attachments
// $mail->addAttachment('/var/tmp/file.tar.gz'); // Add attachments
// $mail->addAttachment('/tmp/image.jpg', 'new.jpg'); // Optional name
// Content
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = "Password reset email for account: ".$to;
$mail->Body = "Your confirmation code to reset your password is: ".$randomNumber;
//$mail->AltBody =;
$mail->send();
} catch (Exception $e) {
print json_encode("error");
}
}else print json_encode("notfound");
mysqli_close($con);
?>
Here is the error that I am getting:
HttpErrorResponse {headers: HttpHeaders, status: 200, statusText: "OK", url: "http://127.0.0.1/interactive-contact-list/sendEmail.php", ok: false, …}
error:
error: SyntaxError: Unexpected number in JSON at position 6 at JSON.parse (<anonymous>) at XMLHttpRequest.onLoad (http://localhost:8100/vendor.js:7290:51) at ZoneDelegate.invokeTask (http://localhost:8100/polyfills.js:3505:35) at Object.onInvokeTask (http://localhost:8100/vendor.js:64524:33) at ZoneDelegate.invokeTask (http://localhost:8100/polyfills.js:3504:40) at Zone.runTask (http://localhost:8100/polyfills.js:3273:51) at ZoneTask.invokeTask [as invoke] (http://localhost:8100/polyfills.js:3586:38) at invokeTask (http://localhost:8100/polyfills.js:4727:18) at XMLHttpRequest.globalZoneAwareCallback (http://localhost:8100/polyfills.js:4764:25)
message: "Unexpected number in JSON at position 6"
stack: "SyntaxError: Unexpected number in JSON at position 6↵ at JSON.parse (<anonymous>)↵ at XMLHttpRequest.onLoad (http://localhost:8100/vendor.js:7290:51)↵ at ZoneDelegate.invokeTask (http://localhost:8100/polyfills.js:3505:35)↵ at Object.onInvokeTask (http://localhost:8100/vendor.js:64524:33)↵ at ZoneDelegate.invokeTask (http://localhost:8100/polyfills.js:3504:40)↵ at Zone.runTask (http://localhost:8100/polyfills.js:3273:51)↵ at ZoneTask.invokeTask [as invoke] (http://localhost:8100/polyfills.js:3586:38)↵ at invokeTask (http://localhost:8100/polyfills.js:4727:18)↵ at XMLHttpRequest.globalZoneAwareCallback (http://localhost:8100/polyfills.js:4764:25)"
__proto__: Error
constructor: ƒ SyntaxError()
arguments: (...)
caller: (...)
length: 1
name: "SyntaxError"
prototype: Error {name: "SyntaxError", message: "", constructor: ƒ}
__proto__: ƒ Error()
[[Scopes]]: Scopes[0]
message: ""
name: "SyntaxError"
__proto__:
constructor: ƒ Error()
message: ""
name: "Error"
toString: ƒ toString()
__proto__: Object
text: ""sent"2020-12-27 13:33:10 SERVER -> CLIENT: 220 smtp.gmail.com ESMTP s6sm56953899wro.79 - gsmtp<br>↵2020-12-27 13:33:10 CLIENT -> SERVER: EHLO 127.0.0.1<br>↵2020-12-27 13:33:11 SERVER -> CLIENT: 250-smtp.gmail.com at your service, [2a00:6920:f0ef:dc7f:e42f:c0d7:fb12:ac22]250-SIZE 35882577250-8BITMIME250-STARTTLS250-ENHANCEDSTATUSCODES250-PIPELINING250-CHUNKING250 SMTPUTF8<br>↵2020-12-27 13:33:11 CLIENT -> SERVER: STARTTLS<br>↵2020-12-27 13:33:11 SERVER -> CLIENT: 220 2.0.0 Ready to start TLS<br>↵2020-12-27 13:33:11 CLIENT -> SERVER: EHLO 127.0.0.1<br>↵2020-12-27 13:33:11 SERVER -> CLIENT: 250-smtp.gmail.com at your service, [2a00:6920:f0ef:dc7f:e42f:c0d7:fb12:ac22]250-SIZE 35882577250-8BITMIME250-AUTH LOGIN PLAIN XOAUTH2 PLAIN-CLIENTTOKEN OAUTHBEARER XOAUTH250-ENHANCEDSTATUSCODES250-PIPELINING250-CHUNKING250 SMTPUTF8<br>↵2020-12-27 13:33:11 CLIENT -> SERVER: AUTH LOGIN<br>↵2020-12-27 13:33:11 SERVER -> CLIENT: 334 VXNlcm5hbWU6<br>↵2020-12-27 13:33:11 CLIENT -> SERVER: [credentials hidden]<br>↵2020-12-27 13:33:11 SERVER -> CLIENT: 334 UGFzc3dvcmQ6<br>↵2020-12-27 13:33:11 CLIENT -> SERVER: [credentials hidden]<br>↵2020-12-27 13:33:11 SERVER -> CLIENT: 235 2.7.0 Accepted<br>↵2020-12-27 13:33:11 CLIENT -> SERVER: MAIL FROM:<no-reply#gmail.com><br>↵2020-12-27 13:33:11 SERVER -> CLIENT: 250 2.1.0 OK s6sm56953899wro.79 - gsmtp<br>↵2020-12-27 13:33:11 CLIENT -> SERVER: RCPT TO:<charbelalam756#gmail.com><br>↵2020-12-27 13:33:11 SERVER -> CLIENT: 250 2.1.5 OK s6sm56953899wro.79 - gsmtp<br>↵2020-12-27 13:33:11 CLIENT -> SERVER: DATA<br>↵2020-12-27 13:33:11 SERVER -> CLIENT: 354 Go ahead s6sm56953899wro.79 - gsmtp<br>↵2020-12-27 13:33:11 CLIENT -> SERVER: Date: Sun, 27 Dec 2020 13:33:10 +0000<br>↵2020-12-27 13:33:11 CLIENT -> SERVER: To: charbelalam756#gmail.com<br>↵2020-12-27 13:33:11 CLIENT -> SERVER: From: "charbelalam755#gmail.com" <no-reply#gmail.com><br>↵2020-12-27 13:33:11 CLIENT -> SERVER: Subject: Password reset email for account: charbelalam756#gmail.com<br>↵2020-12-27 13:33:11 CLIENT -> SERVER: Message-ID: <i0AwjHlt0fMW4cRQ1rpg8Qys7xyFLZyf2MKe365Y#127.0.0.1><br>↵2020-12-27 13:33:11 CLIENT -> SERVER: X-Mailer: PHPMailer 6.1.7 (https://github.com/PHPMailer/PHPMailer)<br>↵2020-12-27 13:33:11 CLIENT -> SERVER: MIME-Version: 1.0<br>↵2020-12-27 13:33:11 CLIENT -> SERVER: Content-Type: text/html; charset=iso-8859-1<br>↵2020-12-27 13:33:11 CLIENT -> SERVER: <br>↵2020-12-27 13:33:11 CLIENT -> SERVER: Your confirmation code to reset your password is: 805919<br>↵2020-12-27 13:33:11 CLIENT -> SERVER: <br>↵2020-12-27 13:33:11 CLIENT -> SERVER: .<br>↵2020-12-27 13:33:12 SERVER -> CLIENT: 250 2.0.0 OK 1609075990 s6sm56953899wro.79 - gsmtp<br>↵2020-12-27 13:33:12 CLIENT -> SERVER: QUIT<br>↵2020-12-27 13:33:12 SERVER -> CLIENT: 221 2.0.0 closing connection s6sm56953899wro.79 - gsmtp<br>↵"
__proto__:
constructor: ƒ Object()
hasOwnProperty: ƒ hasOwnProperty()
isPrototypeOf: ƒ isPrototypeOf()
propertyIsEnumerable: ƒ propertyIsEnumerable()
toLocaleString: ƒ toLocaleString()
toString: ƒ ()
valueOf: ƒ valueOf()
__defineGetter__: ƒ __defineGetter__()
__defineSetter__: ƒ __defineSetter__()
__lookupGetter__: ƒ __lookupGetter__()
__lookupSetter__: ƒ __lookupSetter__()
get __proto__: ƒ __proto__()
set __proto__: ƒ __proto__()
headers: HttpHeaders
lazyInit: () => {…}
lazyUpdate: null
normalizedNames: Map(0) {}
__proto__: Object
message: "Http failure during parsing for http://127.0.0.1/interactive-contact-list/sendEmail.php"
name: "HttpErrorResponse"
ok: false
status: 200
statusText: "OK"
url: "http://127.0.0.1/interactive-contact-list/sendEmail.php"
__proto__: HttpResponseBase
constructor: class HttpErrorResponse
__proto__: Object
I am using print json_encode("") to send response from php to ionic, it's working everywhere except this one.
Here's your problem:
$mail->SMTPDebug = 2;
PHPMailer's debug output is not JSON compatible, so turn it off:
$mail->SMTPDebug = 0;
You an of course turn it into JSON by injecting your own debug output callback, but I doubt that's what you want to do.
When debugging things like this, always look at the actual response you're getting from the server in your browser dev tools – if you had looked at that you would have seen the PHPMailer debug output in the responses.

How to show data by ID in TableView from JSON

I get the data from JSON and also can show it in UITableView, but can I show the data where id is = 1 for example? just like SQL? Thanks for help in advance. Here is my code. I have 2 TableViews, first one holds 3 users and the 2nd one should have that user Information, but when I click on one user it shows all the information from all users.
import UIKit
struct User: Codable {
let firstName: String
let lastName: String
let email: String
let userid: String
enum CodingKeys: String, CodingKey {
case firstName = "first_name"
case lastName = "last_name"
case email = "email"
case userid = "user_id"
}
}
class tableViewCellLabels: UITableViewCell {
#IBOutlet var lbl_firstName: UILabel!
#IBOutlet var lbl_lastName: UILabel!
#IBOutlet var lbl_email: UILabel!
#IBOutlet var lbl_userid: UILabel!
}
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
#IBOutlet weak var tableview1: UITableView!
#IBOutlet var tableview2: UITableView!
private var dataSource = [User]() {
didSet {
self.tableview1.reloadData()
}
}
override func viewDidLoad() {
super.viewDidLoad()
self.tableview1.dataSource = self
self.tableview1.delegate = self
let url = URL(string: "https://test.netperformers.de/users")
URLSession.shared.dataTask(with: url!, completionHandler: { [weak self] (data, response, error) in
guard let data = data, error == nil else {
print(error?.localizedDescription ?? "An error occurred")
return
}
DispatchQueue.main.async {
self?.dataSource = try! JSONDecoder().decode([User].self, from: data)
}
}).resume()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
tableview1.reloadData()
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataSource.count
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if tableView == tableView{
print(dataSource[indexPath.row]) // your clicked user data
}else{
// Second Tableview Click Event here
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "groupCell", for: indexPath) as! tableViewCellLabels
let user = self.dataSource[indexPath.row]
cell.lbl_firstName.text = user.firstName
cell.lbl_lastName.text = user.lastName
cell.lbl_userid.text = user.userid
return cell
}
func tableView1(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if tableView == tableView{
print(dataSource[indexPath.row]) // your clicked user data
}else{
// Second Tableview Click Event here
}
}
}
You do not need a 2nd UITableVIew to show a single User, its not the correct purpose of this ui control, instead you can do one of followings:
Show UIAlertController with the user information
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let user = self.dataSource[indexPath.row]
let alertController = UIAlertController(title: user.firstName + " " + user.lastName, message: user.email, preferredStyle: .alert)
let action = UIAlertAction(title: "OK", style: .default)
alertController.addAction(action)
self.present(alertController, animated: true, completion: nil)
}
Create a UIViewController to have a UI that matches your needs, following is a basic example
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let user = self.dataSource[indexPath.row]
let userVC = UserViewController(user: user)
self.navigationController?.pushViewController(userVC, animated: true)
}
class UserViewController: UIViewController {
private let user: User
init(user: User) {
self.user = user
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = .white
let nameLabel = UILabel()
nameLabel.text = self.user.firstName + " " + self.user.lastName
nameLabel.translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview(nameLabel)
let emailLabel = UILabel()
emailLabel.text = self.user.email
emailLabel.translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview(emailLabel)
let safeAreaGuide = self.view.safeAreaLayoutGuide
NSLayoutConstraint.activate([
nameLabel.topAnchor.constraint(equalTo: safeAreaGuide.topAnchor, constant: 16.0),
nameLabel.leadingAnchor.constraint(equalTo: safeAreaGuide.leadingAnchor, constant: 16.0),
nameLabel.trailingAnchor.constraint(equalTo: safeAreaGuide.trailingAnchor, constant: 16.0),
emailLabel.topAnchor.constraint(equalTo: nameLabel.bottomAnchor, constant: 8.0),
emailLabel.leadingAnchor.constraint(equalTo: safeAreaGuide.leadingAnchor, constant: 16.0),
emailLabel.trailingAnchor.constraint(equalTo: safeAreaGuide.trailingAnchor, constant: 16.0)
])
}
}
If you just need a specific user you can filter the dataSource like this:
dataSource.first(where: { $0.userid == "1" })
Make use of section Header. So all section headers will list the users. In cell for row for each section you can show the information for that particular user. Also you can manage the height of the row for managing the show hide functionality.
Let me know if this helps.
You can do it with a filter array before reloading the tableview.
private var dataSource = [User]() {
didSet {
dataSource = dataSource.filter({ (item) -> Bool in
return item.userid == "3" // put your filter query here
})
self.tableview.reloadData()
}
}
Click Event
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if tableView == YourFirstTable {
print(dataSource[indexPath.row]) // your clicked user data
} else {
// Second Tableview Click Event here
}
}

401 (Unauthorized) with Laravel default vuejs setup

I'm getting a 401 when trying to access the laravel api from vuejs using axios.
It's the Laravel 5.4 out-of-the-box setup so I have no idea why it doesn't work.
Here is my code:
// routes -> api.php
Route::middleware('auth:api')->get('/user', function (Request $request) {
return request->user();
});
// axios request
axios.get('/api/user').then(function (response) {
console.log(response);
console.log(response.status);
});
Request contains all the token stuff.. I think.
X-CSRF-TOKEN:uAW2t..
X-Requested-With:XMLHttpRequest
X-XSRF-TOKEN:eyJpdiI..
All response by request:
General
Request URL:http://localhost/public/api/user
Request Method:GET
Status Code:401 Unauthorized
Remote Address:[::1]:80
Response Headers
view source
Cache-Control:no-cache, private
Connection:Keep-Alive
Content-Length:28
Content-Type:application/json
Date:Wed, 22 Mar 2017 09:35:49 GMT
Keep-Alive:timeout=5, max=92
Server:Apache/2.4.23 (Win64) PHP/5.6.25
X-Powered-By:PHP/5.6.25
X-RateLimit-Limit:60
X-RateLimit-Remaining:57
Request Headers
view source
Accept:*/*
Accept-Encoding:gzip, deflate, sdch, br
Accept-Language:nl-NL,nl;q=0.8,en-US;q=0.6,en;q=0.4
Connection:keep-alive
Cookie:XSRF-TOKEN=eyJpdiI6IjNBVHdDNWdsTnBYT3FUT1E5d1IxTmc9PSIsInZhbHVlIjoiY05JYW9LdDB3ek5FVjRWYkVEM21NQlFEQnNPdHI0Rk5MdWhKbFcrZU1qWFB5MGIyXC9oR1RQNGJkdTB6RmZ3SFp1OU04S0RpazYzZW5ZNUhVMng1VCtnPT0iLCJtYWMiOiIyZTQ5ZDdlYTgwYmMzZTYxYjMzMjljMmNlMDJlYWFlNTNkNzJkZmY5ZGVlMTQ5ZjlmZDM4NTYzOTc1MjIwYzhkIn0%3D; laravel_session=eyJpdiI6IkhcLzJKRDVDTHRDN1FWUjZicDdZaVJnPT0iLCJ2YWx1ZSI6IlJoTkVQWUQ5OWZuYUo4bmF1eHRMYWFlamZramhtTkpmMnYwbUlaaTV3ZENuWFJQZW9IcDZxbU5EQjJXSDY2a01WMHpjeHU3Uk9UOG44MzN3NmgxK2NBPT0iLCJtYWMiOiI4OWM1ZWI3YjIzMDg5MTAwYjc0YmZmZDE4OTY3MjU5OTNkZDdjYjY2MjU3NmFlNTE3NDE2NTVjYzBhY2Y4MzJmIn0%3D
DNT:1
Host:localhost
Referer:http://localhost/public/
User-Agent:Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36
X-CSRF-TOKEN:uAW2tI8bags0CaQaYBKmbfdExoCVDnZlJb1sW9f4
X-Requested-With:XMLHttpRequest
X-XSRF-TOKEN:eyJpdiI6IjNBVHdDNWdsTnBYT3FUT1E5d1IxTmc9PSIsInZhbHVlIjoiY05JYW9LdDB3ek5FVjRWYkVEM21NQlFEQnNPdHI0Rk5MdWhKbFcrZU1qWFB5MGIyXC9oR1RQNGJkdTB6RmZ3SFp1OU04S0RpazYzZW5ZNUhVMng1VCtnPT0iLCJtYWMiOiIyZTQ5ZDdlYTgwYmMzZTYxYjMzMjljMmNlMDJlYWFlNTNkNzJkZmY5ZGVlMTQ5ZjlmZDM4NTYzOTc1MjIwYzhkIn0=
If you authorising user to use api you have to have a token either in url or in authorisation header key. That token should be from api_token column in users table.
var token = 'exampleToken';
axios.get(
'/api/user?api_token=' + token, // here
{
headers:
{
'Authorization':'Bearer ' + token // or here
}
}
).then(...)
axios.get('/api/user',{headers:{
'Accept':'application/json',
'Authorization':'Bearer ' + window.localStorage.getItem('token_name_here')
'cache-control':'no-cache'
}).then(...)...

Not getting json response from online server

So I came over this tutorial right here https://www.youtube.com/watch?v=mdAXqQoADt8 (last part of it) everything is working absolutly fine when I'm refering to my local server.
Now I switched it up to an online server/database to test if it works the same way. Also here everything is working fine except of the json response in the onPostExecute Method. I'm getting no messages from registration or login anymore. I really can't figure out how to solve this problem and I don't understand why it doesn't work the same way when I switch it up to an online server/database.
Hope anyone here can help me with that. I'll post some code below, maybe somebody can figure it out without doing the whole tutorial.
Thankful for any help!
#Override
protected void onPostExecute(String json) {
try {
Log.d("JSON-String",json+"");
progressDialog.dismiss();
JSONObject jsonObject = new JSONObject(json);
JSONArray jsonArray = jsonObject.getJSONArray("server_response");
JSONObject JO = jsonArray.getJSONObject(0);
String code = JO.getString("code");
String message = JO.getString("message");
if (code.equals("reg_true"))
{
showDialog("Registrierung erfolgt.", message, code);
}
else if (code.equals("reg_false"))
{
showDialog("Registrierung fehlgeschlagen", message, code);
}
else if(code.equals("login_true"))
{
Intent intent = new Intent(activity, Talkscreen.class); //SPÄTER WIEDER RAUSNEHMEN
activity.startActivity(intent);
activity.finish();
}
else if (code.equals("login_false"))
{
showDialog("Login fehlgeschlagen", message,code);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
It seems you're getting wrong JSON string from the server.
2905-2905/com.appmac.ron.testapp W/System.err: org.json.JSONException: Value <h3>DB< of type java.lang.String cannot be converted to JSONObject
04-23 12:35:53.172 2905-2905/com.appmac.ron.testapp W/System.err: at org.json.JSON.typeMismatch(JSON.java:111)
04-23 12:35:53.172 2905-2905/com.appmac.ron.testapp W/System.err: at org.json.JSONObject.<init>(JSONObject.java:160)
04-23 12:35:53.172 2905-2905/com.appmac.ron.testapp W/System.err: at org.json.JSONObject.<init>(JSONObject.java:173)
04-23 12:35:53.172 2905-2905/com.appmac.ron.testapp W/System.err: at com.appmac.ron.testapp.ServerKlassen.BackgroundTask.onPostExecute(BackgroundTask.java:172)
04-23 12:35:53.172 2905-2905/com.appmac.ron.testapp W/System.err: at com.appmac.ron.testapp.ServerKlassen.BackgroundTask.onPostExecute(BackgroundTask.java:39)
04-23 12:35:53.172 2905-2905/com.appmac.ron.testapp W/System.err: at android.os.AsyncTask.finish(AsyncTask.java:651)
04-23 12:35:53.172 2905-2905/com.appmac.ron.testapp W/System.err: at android.os.AsyncTask.-wrap1(AsyncTask.java)
04-23 12:35:53.172 2905-2905/com.appmac.ron.testapp W/System.err: at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:668)
04-23 12:35:53.172 2905-2905/com.appmac.ron.testapp W/System.err: at android.os.Handler.dispatchMessage(Handler.java:102)
04-23 12:35:53.172 2905-2905/com.appmac.ron.testapp W/System.err: at android.os.Looper.loop(Looper.java:148)
04-23 12:35:53.172 2905-2905/com.appmac.ron.testapp W/System.err: at android.app.ActivityThread.main(ActivityThread.java:5417)
04-23 12:35:53.172 2905-2905/com.appmac.ron.testapp W/System.err: at java.lang.reflect.Method.invoke(Native Method)
04-23 12:35:53.172 2905-2905/com.appmac.ron.testapp W/System.err: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
04-23 12:35:53.172 2905-2905/com.appmac.ron.testapp W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Above error shows that String could not be converted to JSON object.
Check the server code for any bug.

Phonegap Consuming Web Service PHP

The next problem is try to consume a web service. I try with plugins and pure xml but the result still be "NULL".
The code is this.
function soap(imei,clave)
{
var divToBeWorkedOn = "#res";
var webServiceURL = '';
var parameters = '<?xml version="1.0" encoding="utf-8"?> \
<soap:Envelope xmlns:xsi=" http://www.w3.org/2001/XMLSchema-instance " xmlns:xsd=" http://www.w3.org/2001/XMLSchema " xmlns:soap=" http://schemas.xmlsoap.org/soap/envelope/"> \
<soap:Body> \
<registra_imei> \
<request> \
<imei>'+imei+'</imei> \
<clave>'+clave+'</clave> \
</request> \
</registra_imei> \
</soap:Body> \
</soap:Envelope>';
$.ajax({
type: "Post",
url: webServiceURL,
data: parameters,
contentType: "text/xml; charset=\"utf-8\"",
dataType: "xml",
success: function(msg) {
alert("funciono "+msg);
},
error: function(e){
alert("error");
}
});
}
The Web services is a simple SOAP PHP. Just I need send the variables and then get a response that will be a code (1, 2 or 3).
The requeriment from the event "registra_imei" are this:
Name: registra_imei
Binding: SOAPBinding
Endpoint:
SoapAction: urn:soapwsdl#registra_imei
Style: rpc
Input:
use: encoded
namespace: urn:soapwsdl
encodingStyle: http://schemas.xmlsoap.org/soap/encoding/
message: registra_imeiRequest
parts:
imei: xsd:string
clave: xsd:string
Output:
use: encoded
namespace: urn:soapwsdl
encodingStyle: http://schemas.xmlsoap.org/soap/encoding/
message: registra_imeiResponse
parts:
return: xsd:int
Namespace: urn:soapwsdl
Transport: http://schemas.xmlsoap.org/soap/http
Documentation: Registra imei
My comment is too long to post it into the comment area.
So, using SoapUI i simulated a call to your WSDL and i got this as a RAW response:
HTTP/1.1 200 OK
Date: Tue, 14 Apr 2015 19:44:24 GMT
Server: LiteSpeed
X-Powered-By: PHP/5.4.39
Access-Control-Allow-Origin: *
Access-Control-Allow-Credentials: true
Access-Control-Allow-Methods: PUT, GET, POST, DELETE, OPTIONS
Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept
Set-Cookie: PHPSESSID=870fgce5tm1ep8get75066i491; path=/
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Pragma: no-cache
Content-Type: text/html; charset=utf-8
Content-Length: 0
This is the SOAP request:
<soapenv:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:urn="urn:soapwsdl">
<soapenv:Header/>
<soapenv:Body>
<urn:registra_imei soapenv:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
<imei xsi:type="xsd:string">65656565</imei>
<clave xsi:type="xsd:string">123</clave>
</urn:registra_imei>
</soapenv:Body>
</soapenv:Envelope>
RAW request:
POST http://soap.movilaccesscloud.cl/serversoap.php/ HTTP/1.1
Accept-Encoding: gzip,deflate
Content-Type: text/xml;charset=UTF-8
SOAPAction: "urn:soapwsdl#registra_imei"
Content-Length: 508
Host: soap.movilaccesscloud.cl
Proxy-Connection: Keep-Alive
User-Agent: Apache-HttpClient/4.1.1 (java 1.5)
Apparently, the error is in the back-end of your webservice. Check your PHP code, if possible please share part of the code.
I repeat, my intention was to put the comment in the proper area, but as you can see it´s too long.
:)

Categories