I have selectbox and I using XMLHttpRequest to load values to second selectbox also I am using JQuery selectmenu. The problem is after I select an item from first selectbox the second selectbox changing but won't initialize JQuery selectmenu. Any suggestion?
var xmlHTTP;
function GetXmlHttpObject()
{
xmlHTTP=null;
try
{
xmlhttp=new XMLHttpRequest();
}
catch (e)
{
try
{
xmlhttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
}
}
function getAdultRoom(room_id)
{
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
if(xmlhttp == null)
{
alert("Your browser not support the AJAX");
return;
}
var $element = jQuery.noConflict();
var url = "ajax_fetch_room.php?room_id="+$element('#room_type').val()+"&side_check_in_date="+$element('#side_check_in_date').val()+"&side_check_out_date="+$element('#side_check_out_date').val();
xmlhttp.onreadystatechange=function()
{
if(xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("roomadult").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET",url,true);
xmlhttp.send(null); }
I figure it out. I added $('select').selectmenu(); to onreadystatechange
xmlhttp.onreadystatechange=function()
{
if(xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("roomadult").innerHTML=xmlhttp.responseText;
$('select').selectmenu();
}
}
Related
I have setup the Square SDK but I am having issue now, It is not taking the custom Input field value in processor file.
Here are my Codes,
<!DOCTYPE html>
<html>
<head>
<link href="css/app.css" rel="stylesheet" />
<script
type="text/javascript"
src="https://sandbox.web.squarecdn.com/v1/square.js"
></script>
<script>
const appId = 'sandbox-XXXXX-XXXXXXXXX';
const locationId = 'XXXXXXXXXXXXXX';
async function initializeCard(payments) {
const card = await payments.card();
await card.attach('#card-container');
return card;
}
async function createPayment(token) {
const body = JSON.stringify({
locationId,
sourceId: token,
});
const paymentResponse = await fetch('payment-process.php', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body,
});
if (paymentResponse.ok) {
return paymentResponse.json();
}
const errorBody = await paymentResponse.text();
throw new Error(errorBody);
}
async function tokenize(paymentMethod) {
const tokenResult = await paymentMethod.tokenize();
if (tokenResult.status === 'OK') {
return tokenResult.token;
} else {
let errorMessage = `Tokenization failed with status: ${tokenResult.status}`;
if (tokenResult.errors) {
errorMessage += ` and errors: ${JSON.stringify(
tokenResult.errors
)}`;
}
throw new Error(errorMessage);
}
}
// status is either SUCCESS or FAILURE;
function displayPaymentResults(status) {
const statusContainer = document.getElementById(
'payment-status-container'
);
if (status === 'SUCCESS') {
statusContainer.classList.remove('is-failure');
statusContainer.classList.add('is-success');
} else {
statusContainer.classList.remove('is-success');
statusContainer.classList.add('is-failure');
}
statusContainer.style.visibility = 'visible';
}
document.addEventListener('DOMContentLoaded', async function () {
if (!window.Square) {
throw new Error('Square.js failed to load properly');
}
let payments;
try {
payments = window.Square.payments(appId, locationId);
} catch {
const statusContainer = document.getElementById(
'payment-status-container'
);
statusContainer.className = 'missing-credentials';
statusContainer.style.visibility = 'visible';
return;
}
let card;
try {
card = await initializeCard(payments);
} catch (e) {
console.error('Initializing Card failed', e);
return;
}
// Checkpoint 2.
async function handlePaymentMethodSubmission(event, paymentMethod) {
event.preventDefault();
try {
// disable the submit button as we await tokenization and make a payment request.
cardButton.disabled = true;
const token = await tokenize(paymentMethod);
const paymentResults = await createPayment(token);
displayPaymentResults('SUCCESS');
console.debug('Payment Success', paymentResults);
} catch (e) {
cardButton.disabled = false;
displayPaymentResults('FAILURE');
console.error(e.message);
}
}
const cardButton = document.getElementById('card-button');
cardButton.addEventListener('click', async function (event) {
await handlePaymentMethodSubmission(event, card);
});
});
</script>
</head>
<body>
<form id="payment-form">
<div id="card-container"></div>
<input type="hidden" name="amount" value="500">
<button id="card-button" type="button">Pay $1.00</button>
</form>
<div id="payment-status-container"></div>
</body>
</html>
And The Next Processing file is payment-process.php
<?php
require 'vendor/autoload.php';
use Square\SquareClient;
use Square\Environment;
use Square\Exceptions\ApiException;
use Square\Models\Money;
use Square\Models\CreatePaymentRequest;
use Square\Models\createPayment;
$client = new SquareClient([
'accessToken' => 'EAAAEKE_XXXXXXXXXXXXXXXXXXXXXXXXvs3LXwg0A8TTX2dN5cR5u',
'environment' => Environment::SANDBOX,
]);
$payments_api = $client->getPaymentsApi();
$data = json_decode(file_get_contents('php://input'), true);
$amount = $_POST['amount'];
$amount = $amount * 100;
$money = new Money();
$money->setAmount($amount);
$money->setCurrency('AUD');
$Current_User = 78;
$TransactionID = 'BZ_'.$Current_User.'-'.rand(0000,9999);
$create_payment_request = new CreatePaymentRequest($data['sourceId'], $TransactionID, $money);
$create_payment_request->setNote('Description of Amount');
$response = $payments_api->createPayment($create_payment_request);
if ($response->isSuccess()) {
echo json_encode($response->getResult());
} else {
echo json_encode($response->getErrors());
}
?>
I have tried it with $data['input'] as well as $_POST['amount']
But it always give error of INVALID_AMOUNT_MONEY But If I put the same amount directly in variable $amount = 500; It works perfect.
It is not taking value from the Payment form.
I have this code, now what I want is to set a 3 seconds timeout on it before making the other request again.
function check(num, separator, id) {
var url = "some url"
var xmlhttp;
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var xdata = xmlhttp.responseText;
if (xdata.match("OK")) {
$("#success").append(xdata);
}
else {
$("#error").append(xdata);
}
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
I want to create loader for each http call and dismiss it when reponse is there....tried some code.....which shows sometimes mulitple loaders on each other...snap is there of code..
interceptor.ts
intercept(request: HttpRequest < any >, next: HttpHandler): Observable < HttpEvent < any >> {
request = request.clone({
headers: request.headers.set('Accept', 'application/json')
});
this.commonServices.showLoader();
return next.handle(request).pipe(
map((event: HttpEvent<any>) => {
if (event instanceof HttpResponse) {
this.commonServices.hideLoader();
}
return event;
}),
catchError((error: HttpErrorResponse) => {
this.commonServices.hideLoader();
if (error.status === 401) {
this.storage.clear();
this.router.navigate(['login']);
if (error.error.success === false) {
this.commonServices.forToast("Login failed");
} else {
//this.router.navigate(['login']);
}
}
return throwError(error);
}));
}
CommonService.service.ts
async showLoader() {
if (!this.loader) {
this.loader = await this.loadingController.create({ message: 'Loading' });
}
await this.loader.present();
}
async hideLoader() {
if (this.loader) {
await this.loader.dismiss();
this.loader = null;
}
}
I try to find network disconnected issue. I have tried multiple ways. Still i didn't get the solution. I could not achieve with status code.
Here is my sample code:
var headers = new Headers();
headers.append('Content-Type', 'application/json');
headers.append('Authorization', 'Bearer ' + this.token);
this.http.get('http://someurl/'+userId,{headers:headers})
.map(res => res.json())
.subscribe(
data => {
console.log(data);
},
error => {
console.log(error);
if(error.status == 500) {
this.dashResponse = false;
this.notFoundResponse = false;
this.serverErrorResponse = true;
}
else if(error.status == 404)
{
this.dashResponse = false;
this.notFoundResponse = true;
this.serverErrorResponse = false;
}
else if(error.status == 401)
{
this.router.navigate(['/login']);
alert('Un Authorized');
this.refresh();
}
else
{
this.dashResponse = false;
this.notFoundResponse = false;
this.serverErrorResponse = true;
}
}
);
Can any one solve my problem ?. Thanks in Advance.
I Found the solution for my Question.
Here is the solution:
Import HostListener
import { Component, OnInit, HostListener,OnDestroy } from '#angular/core';
Put this code in to your AppComponent
export class AppComponent implements OnInit,OnDestroy {
//Offline Event
#HostListener('window:offline', ['$event'])
OfflineEvent(event: Event) {
console.log(event);
//do something.....
}
//Online event
#HostListener('window:online', ['$event'])
OnlineEvent(event: Event) {
console.log(event);
//do something.....
}
}
You can display whatever you want to show using HostListener.
I'm trying to use $.getJSON inside PhantomJS but impossible to get the result of it. Any solution? I can not simply load or includeJs directly. The page has to be called from the same domain.
So I want to open a page and do the call from there.
Here is my current code which is not working:
var jqueryUrl = "https://code.jquery.com/jquery-latest.min.js";
page.open("http://www.example.com/", function(status) {
if (status === "success") {
page.includeJs(jqueryUrl, function() {
var result = page.evaluate(function() {
$.getJSON('http://www.example.com/someJson', function(data) {
return data;
});
});
console.log(result);
phantom.exit();
});
} else {
phantom.exit(1);
}
});
Thanks for any help!
You need to use page.onCallback with a combination with window.callPhantom because you are making an HTTP request in phantomjs context and the result needs to be returned only after the request is done.
I haven't tested exactly this code, but it should be something like this:
var jqueryUrl = "https://code.jquery.com/jquery-latest.min.js";
page.open("http://www.example.com/", function(status) {
if (status === "success") {
page.onCallback(function(data) {
// got the data!
console.log(data);
phantom.exit();
});
page.includeJs(jqueryUrl, function() {
page.evaluate(function() {
$.getJSON('http://www.example.com/someJson', window.callPhantom);
});
});
} else {
phantom.exit(1);
}
});