Unable to post to PHP server via Axios in React Native - php

I am unable to post data to the PHP server. I am using Axios.
I can post successfully using Postman, but I can't from my React Native application.
What am I doing wrong?
<TouchableOpacity
style={{ fontSize: 18, color: 'white' }}
containerStyle={{
padding: 8,
marginLeft: 70,
marginRight: 70,
height: 40,
borderRadius: 6,
backgroundColor: 'mediumseagreen'
}}
onPress={() => {
axios.post('url', {
"Reason": this.state.newTodo,
"BranchRef": this.props.branch,
"AppointmentDate": this.props.date,
"ToSeeRef": 369,
"PatientRef": 63,
"AppointmentTimeID": this.props.appointmentTime,
"AppointmentPlatform": 2,
"Completed": 0
}, {
"headers": {
"Accept": 'application/json',
'Content-Type': 'application/json',
}
}).then((response) => {
console.log("reactNativeDemo", "response get
details:" + response.data);
})
.catch((error) => {
console.log("axios error:", error);
});
}}
>
See error message below
axios error: [Error: Request failed with status code 500]

https://postman-echo.com/ - use postman echo to check if there is problem with your client or with the server. It might be a server problem, not from you :-/

Do not enter the Axios function in the render, separate it in different functions and the 'url' variable do you define it as global or inside render?
try :
postData = async () => {
 axios.post ('your url', {
   "Reason": this.state.newTodo,
   "BranchRef": this.props.branch,
   "AppointmentDate": this.props.date,
   "ToSeeRef": 369,
   "PatientRef": 63,
   "AppointmentTimeID": this.props.appointmentTime,
   "AppointmentPlatform": 2,
   "Completed": 0
 }, {
   "headers": {
     "Accept": 'application / json',
     'Content-Type': 'application / json',
   }
 }). then ((response) => {
   console.log ("reactNativeDemo", "response get
                                      details: "+ response.data);
 })
 .catch ((error) => {
   console.log ("axios error:", error);
 });
}
then
on
onPress = {this.postData}

After checking my php/webserver logs, I was able to resolve this by changing the date format on my app.
I am using react-native-datepicker and the date format was different from what the server was expecting.
<DatePicker
date={this.state.date}
mode="date"
format="YYYY-MM-DD"
confirmBtnText="Confirm"
cancelBtnText="Cancel"
customStyles={{
dateIcon: {
position: 'absolute',
left: 0,
top: 4,
marginLeft: 0
},
dateInput: {
marginLeft: 36,
borderWidth: 0,
right: 0,
color: "grey"
}
}}
onDateChange={(date) => { this.setState({ date:
date }); }}
/>

Related

Highcharts Data Not Showing on Ajax Call

I am working on Highcharts using PHP/MYSQL. Data is showing properly in each chart but I tried to change one chart to ajax call in order to reduce page load.
I am generating multiple series data from PHP and displaying them back in the required format but data is not showing(I alerted the data it's coming).
Below is the code of ajax call:
function project_wise_lab(from_date, to_date) {
$.ajax({
type: "POST",
url: 'dashboard/project_wise_labtest',
data: {
from_dte: from_date,
to_dte: to_date
},
success: function(response) {
Highcharts.chart('subcontainer7', {
chart: {
type: 'line',
height: 230,
},
credits: {
enabled: false
},
title: {
text: null
},
xAxis: {
categories: ['Oct 2020', 'Nov 2020', 'Dec 2020', 'Jan 2021', 'Feb 2021', 'Mar 2021', 'Apr 2021', 'May 2021']
},
yAxis: {
min: 0,
title: {
// text: 'Total fruit consumption'
},
stackLabels: {
enabled: false,
style: {
fontWeight: 'bold',
color: ( // theme
Highcharts.defaultOptions.title.style &&
Highcharts.defaultOptions.title.style.color
) || 'gray'
}
}
},
legend: {
align: 'center',
verticalAlign: 'bottom',
backgroundColor: Highcharts.defaultOptions.legend.backgroundColor || 'white',
borderColor: '#CCC',
// borderWidth: 1,
shadow: false
},
tooltip: {
/* headerFormat: '<b>{point.x}</b><br/>',
pointFormat: '{series.name}: {point.y}<br/>Total: {point.stackTotal}'
*/
},
plotOptions: {
column: {
stacking: 'normal',
dataLabels: {
// enabled: true
}
}
},
colors: [
'#4a7fbb',
'#be4c48',
'#97b954',
'#7d6096'
],
series: response
});
console.log(response);
},
error: function(xhr, status, error) {
console.error(xhr);
}
});
}
I have alerted the response and the data is showing in the below format:
{ name : 'FKI',data : [10591,10576,9309,8422,9586,11171,9327,9384] },{ name : 'FKR',data : [4740,3105,2690,3598,3686,4930,3711,3859] },{ name : 'FHR',data : [17190,12757,10837,11944,14083,15748,12544,12494] },{ name : 'FUL',data : [1308,937,1002,1086,1452,1419,1248,1362] },{ name : 'FSW',data : [9535,9102,8689,8420,9941,10915,7273,6930] },{ name : 'FWP',data : [47437,42198,43012,44979,47377,55400,46520,41682] },{ name : 'FGR',data : [2112,1366,1619,1664,2387,2355,1633,1215] }
New Response after update:
[{"name":"FKI","data":{"01-OCT-20":"10591","01-NOV-20":"10576","01-DEC-20":"9309","01-JAN-21":"8422","01-FEB-21":"9586","01-MAR-21":"11171","01-APR-21":"9332","01-MAY-21":"9384"}},{"name":"FKR","data":{"01-OCT-20":"4740","01-NOV-20":"3105","01-DEC-20":"2690","01-JAN-21":"3598","01-FEB-21":"3686","01-MAR-21":"4930","01-APR-21":"3711","01-MAY-21":"3859"}},{"name":"FHR","data":{"01-OCT-20":"17190","01-NOV-20":"12757","01-DEC-20":"10837","01-JAN-21":"11944","01-FEB-21":"14083","01-MAR-21":"15748","01-APR-21":"12544","01-MAY-21":"12494"}},{"name":"FUL","data":{"01-OCT-20":"1308","01-NOV-20":"937","01-DEC-20":"1002","01-JAN-21":"1086","01-FEB-21":"1452","01-MAR-21":"1419","01-APR-21":"1248","01-MAY-21":"1362"}},{"name":"FSW","data":{"01-OCT-20":"9535","01-NOV-20":"9102","01-DEC-20":"8689","01-JAN-21":"8420","01-FEB-21":"9941","01-MAR-21":"10915","01-APR-21":"7273","01-MAY-21":"6930"}},{"name":"FHP","data":{"01-OCT-20":"47437","01-NOV-20":"42198","01-DEC-20":"43012","01-JAN-21":"44979","01-FEB-21":"47377","01-MAR-21":"55400","01-APR-21":"46520","01-MAY-21":"41682"}},{"name":"FGR","data":{"01-OCT-20":"2112","01-NOV-20":"1366","01-DEC-20":"1619","01-JAN-21":"1664","01-FEB-21":"2387","01-MAR-21":"2355","01-APR-21":"1633","01-MAY-21":"1215"}}]
The chart is showing empty, kindly help and let me know to get the issue resolve?
Thanks
You appear to have two problems...
jQuery is interpreting your response as plain text (a string) where Highcharts expects actual JS objects
Your response is not valid JSON so you can't interpret it as such on the client-side. Rule #1 when creating JSON responses is... never roll your own JSON.
I recommend getting PHP to generate valid JSON and respond with the correct Content-type
// Ensure jQuery (or any consumer) knows the response is JSON
header("Content-type: application/json");
// Create a data structure representing the series data
$data = [];
foreach ($project as $key => $value) {
$data[] = [
"name" => $key,
"data" => array_values($value) // you just want the values here, not the keys
];
}
// Respond with JSON
echo json_encode($data);
exit;
Then in your client-side code, you can simply use
series: response
as response will now be a valid JS array
You can also make sure jQuery treats the response as JSON by adding
dataType: "json",
to your $.ajax() options but with the right Content-type response header, jQuery should not need this.
Just an FYI, alert() is terrible for viewing data. The best option would be to use your browser's debugger. The second best option is to use console.log()

Unable to load Chart.js data from getJSON / PHP?

I am trying to add chart data from PHP file.
Chart is drawn when I add the values manually - data: [28,20,2,7],
But chart doesn't appear, when I add the data from PHP file.
Where am I going wrong here?
How can I add these values from PHP output?
My PHP code:
echo json_encode(array($rectotals,$recX,$recXS,$recXM));
Php file output (this looks OK):
[28,20,2,7]
Here is how i get the data:
$.getJSON("chartdata.php").then(function(chart_data1){
alert(chart_data1);
})
Alert result (This is also OK):
localhost:63342 says 28,20,2,7
My chartjs script:
<canvas id="myChart" width="400" height="340"></canvas>
<script>
$.getJSON("chartdata.php").then(function(chart_data){
alert(chart_data);
})
//setTimeout(function() { alert(db_data1); }, 2000);
var ctx = document.getElementById('myChart');
var myChart = new Chart(ctx, {
type: 'pie',
data: {
labels: ['Total', 'Size X', 'Size XS', 'Size SM],
datasets: [{
data: chart_data,
backgroundColor: [
'rgba(54, 162, 235, 1)',
'rgb(255,99,132)',
'rgba(255, 159, 64, 1)',
'rgb(255,206,86)'
],
borderColor: [
'rgba(54, 162, 235, 1)',
'rgba(255, 99, 132, 1)',
'rgb(255,159,64)',
'rgba(255, 206, 86, 1)'
],
borderWidth: 0.5,
}]
},
options: {
responsive: true,
animation: {
duration: 2800,
easing: 'easeInOutQuad',
},
layout: {
padding: {
left: 0,
right: 0,
top: 15,
bottom: 0
}
},
cutoutPercentage : 75,
legend: {
display: false,
position: 'bottom',
fullWidth: true,
}
}
});
</script>
var ctx = document.getElementById("myChart").getContext("2d");
let myChart = null;
function getConfig(chart_data){
return ({
type: "pie",
data: {
labels: ["Total", "Size X", "Size XS", "Size SM"],
datasets: [
{
data: chart_data,
backgroundColor: [
"rgb(54,162,235)",
"rgb(255,99,132)",
"rgba(255, 159, 64, 1)",
"rgb(255,192,33)"
],
borderColor: [
"rgb(255,255,255)",
"rgb(255,255,255)",
"rgb(255,255,255)",
"rgb(255,255,255)"
],
hoverBackgroundColor: ['#373739', '#373739', '#373739', '#373739'],
}
]
},
options: {
responsive: true,
animation: {
duration: 0, //2800, I remove animation time
easing: "easeInOutQuad"
},
tooltips: {
mode: 'nearest'
},
layout: {
padding: {
left: 0,
right: 0,
top: 15,
bottom: 0
}
},
cutoutPercentage: 66,
legend: {
display: false,
position: "bottom",
fullWidth: true
}
}
});
}
function getJSON(){
// emulate fetch
return new Promise(resolve => {
const chart_data = [
Math.random() * 50,
Math.random() * 50,
Math.random() * 50,
Math.random() * 50
];
resolve(chart_data)
})
}
function update(){
getJSON().then(data => {
myChart.data.datasets[0].data = data;
myChart.update();
});
}
function initializeChart() {
getJSON().then(data => {
myChart = new Chart(ctx, getConfig(data));
});
}
initializeChart();
document.getElementById('update_chart').addEventListener('click', update, false);
<html>
<head>
<title>Parcel Sandbox</title>
<meta charset="UTF-8" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<div>
<button id="update_chart">Update Records</button>
</div>
<canvas id="myChart" width="50" height="40"></canvas>
</body>
</html>
Query.getJSON() makes an asynchronous HTTP request. Once the result arrives, the chart has already been created and the obtained data has no effect on the chart.
To solve this, place the chart creation inside the then callback as follows.
$.getJSON("chartdata.php").then(function(chart_data) {
var ctx = document.getElementById('myChart');
var myChart = new Chart(ctx, {
type: 'pie',
...
});

while using json data shows Uncaught SyntaxError: Unexpected token var

I want to get data from an url("http://localhost/icx/test/link.html") contains json data. the data contains is like
[{
"call_time": "0",
"total_inc_traffic": "1363.10",
"total_out_traffic": "88.70"
}, {
..............
.............
}]
the json data "total_inc_traffic" is to be shown in the bar chart y axix
<div id="HT_IGW"></div>
<script src="https://cdn.jsdelivr.net/npm/apexcharts#latest"></script>
<script>
var options = {
chart: {
height: 255,
type: 'bar',
},
plotOptions: {
bar: {
horizontal: false,
columnWidth: '55%',
endingShape: 'rounded'
},
},
dataLabels: {
enabled: false
},
stroke: {
show: true,
width: .5,
colors: ['transparent']
},
series: [{
name: 'Traffic In',
data: [
var ourRequest =new XMLHttpRequest();
ourRequest.open('GET','http://localhost/icx/test/link.html');
ourRequest.onload = function(){
var ourData = JSON.parse(ourRequest.responseText);
let result2 = ourData.map(v => Number(v.total_inc_traffic));
console.log(result2);
};
ourRequest.send();
]
}, {
name: 'Traffic Out',
data: [76, 85, 111, 98, 87, 115, 91, 114, 94,76, 85, 111, 98, 87, 115, 91, 114, 94,76, 85, 111,77, 98, 87]
},
],
xaxis: {
categories: ['1', '', '3', '', '5', '', '7', '', '9','','11', '', '13', '', '15', '', '17', '', '19','','21','','23',''],
},
yaxis: {
},
fill: {
opacity: 1
},
tooltip: {
y: {
formatter: function (val) {
return " " + val + " Calls"
}
}
}
}
var chart = new ApexCharts(
document.querySelector("#HT_IGW"),
options
);
chart.render();
</script>
<script>
var ourRequest =new XMLHttpRequest();
ourRequest.open('GET','http://localhost/icx/test/link.html');
ourRequest.onload = function(){
var ourData = JSON.parse(ourRequest.responseText);
let result = ourData.map(v => Number(v.call_time));
console.log(result);
let result2 = ourData.map(v => Number(v.total_inc_traffic));
console.log(result2);
let result3 = ourData.map(v => Number(v.total_out_traffic));
console.log(result3);
};
ourRequest.send();
</script>
</body>
</html>
I expected the output to be shown in the bar graph data, but it gives error data
My error is this
My expectation is
Can anyone help ??
You have an array initializer in a property definition with statements in it:
series: [{
name: 'Traffic In',
data: [
var ourRequest =new XMLHttpRequest();
ourRequest.open('GET','http://localhost/icx/test/link.html');
ourRequest.onload = function(){
var ourData = JSON.parse(ourRequest.responseText);
let result2 = ourData.map(v => Number(v.total_inc_traffic));
console.log(result2);
};
ourRequest.send();
]
You can't do that. With an array initializer ([...]) you can only have expressions in it separated with commas. The expressions are evaluated to create the values to put in the array.
It's not clear to me what you're trying to do there, but that code probably belongs after the big object initializer creating the options object.
You cannot put a code block (the part starting with "var ourRequest") inside array initializer.
If you need the data obtained from ajax call to become the options.series.data property, you need to either create the options object after the ajax call is done, or create the options without that property and add to it when the ajax call is finished.
Anyway if the server that provides the json endpoint is the same as the one that is rendering the page, you should be able to render that information there right when the page is rendered, bypassing need to call any additional ajax request.
As long as you dont want to also call it to update the information without re-rendering the entire page.

select multi image from gallery for send to server with react-native

I try to send multi selected image and upload them to server. I can use react-native-image-picker to select one image and transfer this to base64 and save on state after that send it to the server. but I want multi-select from the gallery and to send them to server . may anyone help me to do that? first, how can I select the multi image and save data of that image to state? second, how can I send that state to save PHP server? third how to show that to the client in the app? in below you can see my cod. thanks
import React, { Component } from 'react';
import { StyleSheet, Text, View, PixelRatio, TouchableOpacity, Image, TextInput, Alert } from 'react-native';
import ImagePicker from 'react-native-image-picker';
import {
handleAndroidBackButton,
removeAndroidBackButtonHandler
} from '../component/androidBackButton';
import RNFetchBlob from 'rn-fetch-blob';
import { ScrollView } from 'react-native-gesture-handler';
class testImage extends Component {
constructor(props) {
super(props);
this.state = {
ImageSource1: null,
ImageSource2: null,
ImageSource3: null,
data: [],
Image_TAG: ''
};
}
componentDidMount() {
handleAndroidBackButton(() => { this.props.navigation.navigate('AuthLoading') });
}
componentWillUnmount() {
removeAndroidBackButtonHandler();
}
selectPhotoTapped(num) {
const options = {
quality: 1.0,
maxWidth: 500,
maxHeight: 500,
storageOptions: {
skipBackup: true
}
};
ImagePicker.showImagePicker(options, (response) => {
console.log('Response = ', response);
if (response.didCancel) {
console.log('User cancelled photo picker');
}
else if (response.error) {
console.log('ImagePicker Error: ', response.error);
}
else if (response.customButton) {
console.log('User tapped custom button: ', response.customButton);
}
else {
let source = { uri: response.uri };
switch (num) {
case '1':
this.setState({
ImageSource1: source,
data: [...this.state.data, response.data],
});
break;
case '2':
this.setState({
ImageSource2: source,
data: [...this.state.data, response.data],
});
break;
case '3':
this.setState({
ImageSource3: source,
data: [...this.state.data, response.data],
});
break;
default:
break;
}
}
});
}
uploadImageToServer2 = () => {
alert(this.state.data)
}
uploadImageToServer = () => {
RNFetchBlob.fetch('POST', 'http://192.168.2.102/Project/upload_image.php', {
Authorization: "Bearer access-token",
otherHeader: "foo",
'Content-Type': 'multipart/form-data',
}, [
{ name: 'image', filename: 'image.png', type: 'image/png', data: this.state.data[0] },
{ name: 'image', filename: 'image.png', type: 'image/png', data: this.state.data[1] },
{ name: 'image', filename: 'image.png', type: 'image/png', data: this.state.data[2] },
{ name: 'image_tag', data: this.state.Image_TAG }
]).then((resp) => {
var tempMSG = resp.data;
tempMSG = tempMSG.replace(/^"|"$/g, '');
Alert.alert(tempMSG);
}).catch((err) => {
// ...
})
}
render() {
return (
<ScrollView>
<View style={styles.container}>
<TouchableOpacity onPress={()=>this.selectPhotoTapped('1')}>
<View style={styles.ImageContainer}>
{this.state.ImageSource1 === null ? <Text>Select a Photo</Text> :
<Image style={styles.ImageContainer} source={this.state.ImageSource1} />
}
</View>
</TouchableOpacity>
<TouchableOpacity onPress={()=>this.selectPhotoTapped('2')}>
<View style={styles.ImageContainer}>
{this.state.ImageSource2 === null ? <Text>Select a Photo</Text> :
<Image style={styles.ImageContainer} source={this.state.ImageSource2} />
}
</View>
</TouchableOpacity>
<TouchableOpacity onPress={()=>this.selectPhotoTapped('3')}>
<View style={styles.ImageContainer}>
{this.state.ImageSource3 === null ? <Text>Select a Photo</Text> :
<Image style={styles.ImageContainer} source={this.state.ImageSource3} />
}
</View>
</TouchableOpacity>
<TouchableOpacity onPress={()=>this.uploadImageToServer2()} activeOpacity={0.6} style={styles.button} >
<Text style={styles.TextStyle}> U2242D IMAGE TO SERVER </Text>
</TouchableOpacity>
<TouchableOpacity onPress={this.uploadImageToServer} activeOpacity={0.6} style={styles.button} >
<Text style={styles.TextStyle}> UPLOAD IMAGE TO SERVER </Text>
</TouchableOpacity>
</View>
</ScrollView>
);
}
}
export default testImage;
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
backgroundColor: '#FFF8E1',
paddingTop: 20
},
ImageContainer: {
borderRadius: 10,
width: 250,
height: 250,
borderColor: '#9B9B9B',
borderWidth: 1 / PixelRatio.get(),
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#CDDC39',
},
TextInputStyle: {
textAlign: 'center',
height: 40,
width: '80%',
borderRadius: 10,
borderWidth: 1,
borderColor: '#028b53',
marginTop: 20
},
button: {
width: '80%',
backgroundColor: '#00BCD4',
borderRadius: 7,
marginTop: 20
},
TextStyle: {
color: '#fff',
textAlign: 'center',
padding: 10
}
});
Please refer here, Multiple image selection is not supported by
react-native-image-picker
for IOS.
I use react-native-image-crop-picker which supports multiple image selection for both android & ios
import ImagePicker from 'react-native-image-crop-picker';//import
ImagePicker.openPicker({
includeBase64: true, // for base 64 string
multiple: true,// To support multiple image selection
quality: 1.0,
maxWidth: 500,
maxHeight: 500,
}).then(image => {
for (i = 0; i < image.length; i++) {
this.state.images.push(image[i].data)//image[i].data=>base64 string
}
}
uploadImageToServer = () => {
this.state.images.map((data, key) => {
RNFetchBlob.fetch('POST', 'http://192.168.2.102/Project/upload_image.php', {
Authorization: "Bearer access-token",
otherHeader: "foo",
'Content-Type': 'multipart/form-data',
},
[{ name: 'image', filename: 'image.png', type: 'image/png', data: data },
{ name: 'image_tag', data: this.state.Image_TAG }]).then((resp) => {
var tempMSG = resp.data;
tempMSG = tempMSG.replace(/^"|"$/g, '');
Alert.alert(tempMSG);
}).catch((err) => {
// ...
})
})
}

React native http post got Json Parse error: Unrecognized token '<'

When I tried to post data from react-native to PHP API, react-native show the error:
Json Parse error: Unrecognized token '<'
I tested PHP API by postman with the header type 'application/json', it works fine, here is the react-native code, can anyone help me on this? Thanks in advance!
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View,
ActivityIndicatorIOS,
TextInput,
TouchableOpacity,
} from 'react-native';
const REQUEST_URL = 'http://localhost:8000/user';
export default class extends Component {
constructor(props) {
super(props);
}
_submit() {
fetch(REQUEST_URL, {
method: "POST",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
firstname: "Justin", lastname: "Robot"
})
})
.then((response) => response.json())
.then((responseData) => {
console.log(responseData.body);
})
.done();
}
render() {
return (
<View style={styles.container}>
<TouchableOpacity
style={styles.submitButton}
onPress={() => this._submit()}
>
<Text>http post</Text>
</TouchableOpacity>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
},
submitButton: {
backgroundColor: 'lightskyblue',
borderRadius: 5,
paddingTop: 5,
paddingBottom: 5,
paddingLeft: 20,
paddingRight: 20,
}
});
We just ran into this in React Native because our server was returning an error response via HTML.
<html>
<head><title>413 Request Entity Too Large</title></head>
<body bgcolor="white">
<center><h1>413 Request Entity Too Large</h1></center>
<hr><center>nginx</center>
</body>
</html>
The fixes could be any of the following:
1) Prevent the error from happening in your server side code.
2) Do better error handling on your server to return JSON errors instead of HTML errors.
3) Write some client side code to detect that HTML was returned and show a more useful error message.

Categories