React JS - unable to update text after IMG onclick event - javascript

I am trying to update the input text field ( Start time ) after the onClick={this.populateDate}. But I get the default value passed to the AJAX call to PHP.
https://jsfiddle.net/adwantgoutam/rg68Lyfk/
<?php header('Access-Control-Allow-Origin: *');
echo "Hello World";
$stime= $_GET['first_name'];
$etime= $_GET['last_name'];
$xyz= $_GET['start_time'];
echo "\n";
echo $stime;
echo "\n";
echo $etime;
echo "\n";
echo $xyz;
?>
Output :
Hello world!
John
Doe
03/11/2016 ( not the updated one after we click date through image onclick ).
var Hello = React.createClass({
render() {
return (
<form onSubmit={this.handleSubmit}>
<input value={this.state.first_name} onChange={this.setFirstName} placeholder="First name"/><br/>
<input value={this.state.last_name} onChange={this.setLastName} placeholder="Last name"/><br/>
<input value={this.state.start_time} onChange={this.setStartTime} placeholder="Start Time" id="demo1" name="stime"/>
<img src="https://rainforestnet.com/datetimepicker/sample/images2/cal.gif" onClick={this.populateDate}/><br/>
<button type="submit">Submit</button>
</form>
)
},
handleSubmit(event) {
event.preventDefault();
var data = this.state;
$.ajax({
type: "GET",
crossDomain: true,
url: "http://localhost:8082/PFT/login.php",
data: data,
success: function(data){
alert(data);
//$('#resultip').html(data);
},
error:function(data)
{
alert("Data sending failed");
}
});
},
populateDate(){
NewCssCal('demo1','yyyyMMdd','dropdown',true,'24',true);
},
getInitialState() {
return {
first_name: "John",
last_name: "Doe",
start_time: "03/11/2016",
};
},
setStartTime(event) {
console.log( event.target.value)
this.setState({start_time: event.target.value});
}
});
ReactDOM.render(
<Hello />,
document.getElementById('container')
);
I have attached my code in jsfiddle and above is the PHP script. I am not sure where exactly or how to process this. Any help is highly appreciated. Thanks.

I have gone through the date picker library you are using. To make this code work you'll have to add componentDidMount as follows.
componentDidMount(){
document.getElementById('demo1').onchange= this.setStartTime;
}
Then you need to modify you setStartTime function as follows
setStartTime() {
this.setState({start_time: document.getElementById('demo1').value});
}
Because the library is triggering change event programatically(as the value is being changed programmatically). Hence you'll not get the event object.
Though doing so will make your code work, my suggestion will be to use any react library for date-time picker(if you don't have the dependency to use this only) which provide proper configuration as per your requirement. Also try to use refs instead of document.getElement.... which is the react way of interacting with dom.

Related

Element UI autocomplete no results

I use in my project element UI autocomplete component.
When the input raises no result, I want to show a no results message.
In other projects I had it as an option in the suggest box (which is NOT selectable):
However, with element-ui autocomplete, after the searching icon disappears, the drop-down disappears as well:
With this component I do not manage to do so. Any idea?
My code looks like this:
Template:
<el-form ref="addressForm" :inline="true" :model="formData">
<el-form-item prop="city">
<el-autocomplete
class="inline-input"
v-model="formData.cityInput"
:fetch-suggestions="getCities"
placeholder="City"
:trigger-on-focus="false"
:clearable="true"
#select="handleSelectCity"
#clear="clearCity"
size="small"
></el-autocomplete>
</el-form-item>
:
:
<el-form-item>
<el-button type="primary" #click="onSubmit" size="small">
Search
</el-button>
</el-form-item>
</el-form>
Script:
export default {
data() {
return {
formData: {
cityInput: "",
city: "",
:
:
},
}
},
methods: {
getCities(query, callback) {
this.clearCity();
// Ajax call to obtain results for autocomplete
axios.get(
"/cities", {
query: query
})
.then(
response => {
callback(response.data);
}
);
},
handleSelectCity(item) {
this.formData.city = item.value;
},
clearCity() {
this.formData.city = "";
},
:
:
:
}
};
PHP code: (Laravel)
public function getCities($query)
{
$res = DB::connection('mainDb')
->table('offices')
->where('city', 'like', $query . '%')
->select('city AS value')
->distinct()
->get();
return $res;
}
You can achieve this behaviour with v-select. There is a filtering option so you can either select option or type it down with autocomplete.
There are two attributes to control "no-result" case: no-match-text when filtering gave no result and no-data-text when there is no options in select.
I tried el-select and it works good with "no matched data".But its remote-method function isn't smart enough without callback parameter if you want to pass a function to it from outside component.
So,I have to try codepen.io/boussadjra/pen/ZEGvGNm, use the blur method to clear no matched data, and it works like the el-select.

How to use php for loop to create FilePond instances, and use plugins

I want to use a php for loop to create some file inputs with FilePond.
Each instance needs to have its own unique url, and use the plugins initiated. I have got the actual file uploads working, although the plugins don't seem to be getting used.
<?php
foreach ($objArray as $value) {
$inputNumber2++;
?>
<input name="input_<?= $inputNumber2; ?>_images[]" id="input_<?= $inputNumber2; ?>_images" class="filepond" type="files" multiple />
<script>
document.addEventListener('DOMContentLoaded', function() {
window['input<?= $inputNumber2; ?>Images'] = FilePond.create(
document.querySelector('#input_<?= $inputNumber2; ?>_images'),
{
server: {
url: '<?= Config::get('URL'); ?>',
process: 'upload/images/input_<?= $inputNumber2; ?>_images',
revert: 'upload/revert',
load: 'files/',
},
<?php
if (isset($value->imageArray) && count($value->imageArray) > 0) {
echo 'files: [';
foreach ($value->imageArray as $imageName) {
echo '{
source: "'.$imageName.'",
options: {
type: "local",
file: {
name: "'.$imageName.'",
type: "image/jpeg"
}
}
},';
}
echo '],';
}
?>
}
);
});
</script>
<?php } ?>
...
<script>
document.addEventListener('DOMContentLoaded', function() {
FilePond.registerPlugin(
FilePondPluginFileValidateType,
FilePondPluginImageExifOrientation,
FilePondPluginImagePreview,
FilePondPluginImageTransform,
FilePondPluginImageCrop,
FilePondPluginImageResize
);
FilePond.setOptions({
acceptedFileTypes: ['image/*'],
labelIdle: 'Add images or <span class="filepond--label-action"> Browse </span>',
imagePreviewMaxHeight: 100,
imagePreviewZoomFactor: 1,
});
});
</script>
I'm probably doing it wrong - how should I be doing it?
Also, it is picking up and using the custom label so some settings it is getting.
This line:
document.querySelector('#input_<?= $inputNumber2; ?>_images')
Returns a field with the id input_<?= $inputNumber2; ?>_images. But you've only assigned the name attribute to your input field. I suspect adding the id attribute to the input will solve the issue.
OR you can change the selector to:
document.querySelector('input[name="input_<?= $inputNumber2; ?>_images"]')

autocomplete and multiple function using ajax in laravel

I am new to laravel framework. I want to complete a important task in my app.
In that app they have modules like invoices,quotes,payment,customers. for particular customers they have multiple invoices with status of sent and partially paid.
Here is the receipt page, on type of customer name it will get autosuggestion from customer table. Onclick of cutomer name it will get invoice details from (invoice table) based on customer id,and need to show on table below that customer name textbox, onclick of table invoice it will open modal which means if the particular customer has unpaid invoice they need to record payment else proceed with normal receipt creation.
I try the code like this, But I am not getting proper output please anyone help me to get out of this issue.
<input type="text" name="customername" required="required" id="cust" placeholder="Customer Name" class="form-control col-md-7 col-xs-12 typeahead"/>
$( function() {
$( "#cust" ).autocomplete({
//source: "http://www.duminex.com/client/search",
source: "{{route('search.client')}}",
select: function( event, ui ) {
get_invoices(ui.item.id);
$('#id').val(ui.item.id);
$('#clientAddress').val(ui.item.address);
}
});
} );
function get_invoices(client_id)
{
$.ajax({
method: 'GET',
url: "{{route('client.details')}}"
}).done(function(data){
alert(data);
});
}
routes
Route::get('/client/search',[
'uses'=>'ClientsController#search',
'as'=>'search.client'
]);
Route::get('/client/search2', 'ClientsController#search2')->name('client.details');
Controller
public function search(Request $request)
{
$s= Input::get('term');
$clients = Client::select("id" ,"user_id", "companyname", "companyaddress" , "billingAddress")->where('companyname','like','%'.$s.'%')->where('user_id',Auth::user()->id)->get();
if(count($clients) == 0){
$searchResult[] = "No Item found";
}
else{
foreach ($clients as $key => $value) {
$searchResult[] = ['id' => $value->id, 'value' => $value->companyname , 'email' => $value->companyaddress , 'address' => $value->billingAddress];
}
}
return $searchResult;
}
public function search2(Request $request)
{
$clients = Invoice::select("invoiceNo")->where('status',['sent,Partially paid'])->where('client_id',$request->client_id)->get();
if(count($clients) == 0){
$searchResult[] = "No Item found";
}
else{
foreach ($clients as $key => $value) {
$searchResult[] = ['invoiceNo' => $value->invoiceNo];
}
}
return $searchResult;
}
Thanks in advance. Please anyone to help me get out of this issue.
You are not passing any data to the ajax so thats why you are not getting any result.
Try below code :
function get_invoices(client_id) {
$.ajax({
method: 'GET',
data : {
client_id: client_id
},
url: "{{route('client.details')}}"
}).done(function(data){
alert(data);
});
}

Integrating stripe payments (JS and PHP) with a custom amount (JS variable)

I've been trying to figure this out for days with no luck.
I'm trying to implement Stripe Payments Checkout into my website. The payment amount is on the payments page as a JS variable. I was able to get Basic Checkout working, but apparently that can't use a custom amount, or send any data to the PHP processing page (email, and some order attributes). I've been trying to use the Custom Checkout but I can't figure it out. Any help?
So far I have this in config.php:
<?php
require_once('vendor/autoload.php');
$stripe = array(
"secret_key" => "MY SECRET KEY IS HERE",
"publishable_key" => "MY PUBLISHED KEY IS HERE"
);
\Stripe\Stripe::setApiKey($stripe['secret_key']);
?>
and this is in a file called process.php:
<?php
require_once('./config.php');
$token = $_POST['stripeToken'];
$input = $_POST["totalprice"];
$customer = \Stripe\Customer::create(array(
'email' => 'customer#example.com',
'source' => $token
));
$charge = \Stripe\Charge::create(array(
'customer' => $customer->id,
'amount' => $input,
'currency' => 'usd'
));
echo $input;
?>
And in the initial PHP file I have:
<?php require_once('./config.php'); ?>
<form action="process.php" method="POST">
<script
src="https://checkout.stripe.com/checkout.js" class="stripe-button"
data-key="MY PUBLIC TEST KEY IS HERE"
data-amount= amt * 100
data-name="Test Name"
data-description="Widget"
data-image="/img/logo.jpg"
data-locale="auto"
>
<form type=hidden name="totalprice" value=amt*100 action="process.php" method="POST">
</script>
</form>
With that said though, I've had a bunch of other code I've tried before that hasn't worked, so this current code probably should be scrapped. I'd really appreciate any help I can get!
Well, following is the sample code of Custom Integration.
<script src="https://checkout.stripe.com/checkout.js"></script>
<button id="customButton">Purchase</button>
<script>
var handler = StripeCheckout.configure({
key: 'pk_test_6pRNASCoBOKtIshFeQd4XMUh',
image: 'https://stripe.com/img/documentation/checkout/marketplace.png',
locale: 'auto',
token: function(token) {
// You can access the token ID with `token.id`.
// Get the token ID to your server-side code for use.
}
});
document.getElementById('customButton').addEventListener('click', function(e) {
// Open Checkout with further options:
handler.open({
name: 'Stripe.com',
description: '2 widgets',
zipCode: true,
amount: 2000
});
e.preventDefault();
});
// Close Checkout on page navigation:
window.addEventListener('popstate', function() {
handler.close();
});
</script>
The source code is given on this page
So is that what you are looking for?

Polymer Iron-Form response

I'm using Polymer's Iron-Form component to submit this form I have created, but the problem is that the response from the php script won't output to the actual html. I'm stuck on how to do this and have tried many different things. What am I doing wrong? Here's my scrpits:
<dom-module id="user-signup">
<template>
<form is="iron-form" id="formGet" method="post" action="/core/register.php">
<paper-input char-counter autoValidate="true" error-message="{{item.error_name}}" label="Username" maxlength="25" required name="username"></paper-input>
<paper-input char-counter error-message="{{error_displayn}}" label="Display Name" maxlength="35" required name="displayname"></paper-input>
<paper-input char-counter error-message="{{error_password}}" label="Password" maxlength="25" required type="password" name="password"></paper-input>
<paper-input char-counter error-message="{{error_password}}" label="Confrim Password" maxlength="25" required type="password" name="cfmpassword"></paper-input>
<gold-email-input class="paper-input-input" label="Email" required name="email" auto-validate error-message="{{error_email}}"></gold-email-input>
<br />
<br>
<paper-button raised onclick="clickHandler(event)"><iron-icon icon="check"></iron-icon>Submit</paper-button>
</form>
</template>
<script>
function clickHandler(event) {
Polymer.dom(event).localTarget.parentElement.submit();
}
Polymer({
is: 'user-signup',
properties: {
error_name: {
type: String,
value:"Username Is Invalid!"
},
error_displayn: {
type: String,
value:"Display Name Is Invalid!"
},
error_password: {
type: String,
value:"Password Is Invalid!"
},
error_email: {
type: String,
value:"Email Is Invalid!"
}
},
listeners: {
'iron-form-response': 'formResponse',
'iron-form-submit': 'formSubmit',
'iron-form-error': 'formError'
},
formSubmit: function(event) {
var pmn = document.querySelector('#waitForResponse');
pmn.setAttribute("opened", "true");
console.log("Form was submitted");
},
formResponse: function(event) {
setTimeout(function(){
var pmn = document.querySelector('#waitForResponse');
pmn.removeAttribute("opened");
}, 5000)
console.log('There was a response');
var response = event.detail;
alert(response);
},
formError: function(event) {
console.log('Form Error, no actual response');
setTimeout(function(){document.querySelector('#errorToast').show();
var pmn = document.querySelector('#waitForResponse');
pmn.removeAttribute("opened");
}, 5000)
}
});
</script>
</dom-module>
Now the listeners work and when there is a response from the php page, the alert pops up but it says: [Object object]. Here is the php script:
<?php
$data[] = array(
"id" => $id,
"error_name" => $error_name,
"success" => true
);
echo 'dd';
?>
I have tried to echo $data as json but what didn't work either. I've tried to search it on Google and Stack but haven't found anything. What am I doing wrong?
according to the docs you have binded your listeners to a host element and not to form itself.
maybe this will help:
listeners: {
'formGet.iron-form-response': 'formResponse',
'formGet.iron-form-submit': 'formSubmit',
'formGet.iron-form-error': 'formError'
}
whats the model object, that your successful login call on php would return?
you could use the following, cosume the json coming back inside JS promise
$myPhpCallLogon.then(function(user) {
user.firstName...
user.id...
user.email...
var polyListUser = document.querySelector('#userView');
set watch vars in polyListUser element....
}
and then user your template to get the name,id, email etc into the dom of your element that displays the user.

Categories