I am writing code to get data from MySQL database and using Vuejs,
this.$http.get("api.php?action=read")
.then(response => {
console.log(response);
}, error => {
console.log(error);
});
this request returns all api.php content and doesn't return the data.
here is the api.php file
<?php
require_once('include/config.php');
$res = (['error' => false]);
$action = 'read';
if (isset($_GET['action'])) {
$action = $_GET['action'];
}
if($action == 'read') {
$images = array();
$query = 'SELECT * FROM images ORDER BY id DESC';
$select_images = mysqli_query($connection, $query);
while($image = mysqli_fetch_assoc($select_images)) {
array_push($images, $image);
}
echo json_encode($images);
}
mysqli_close($connection);
header("Content-type: application/json");
echo json_encode($images);
die();
?>
Can anyone help me, Please?
It works,
I added
header("Access-Control-Allow-Origin: *");
to the API file
and make the get request from the localhost/vuejs link,
not like localhost:8080
and it's work
Thanks
Include the header in the php. Note: should be the 1st line before you return anything.
<?php
header("Access-Control-Allow-Origin: *");
And try to run the php code 1st using command prompt:
php -S localhost:8888 ajaxfile.php
Note: try to use different port number as for me it is unable to get the api from same 8080 port in which my vueProject is running.
This will create an api end point with your php. Which will listen to http://localhost:8888/projectname/api.php.
Now When used axios.get(http://localhost:8888/projectname/api.php) will get the response for the api.I havent tried without axios module but i guess it should work.
allRecords: function(){
axios.get('http://localhost:8888/VueAxios/ajaxfile.php').then(response => {
this.users = response.data
console.log(response.data)
})
.catch(function (error) {
console.log(error);
});
}
This function worked for me. Note: axios is a very handy in this situation. Hope it helps.
Try response.body to get the response data:
this.$http.get("api.php?action=read")
.then(response => {
console.log(response.body);
}, error => {
console.log(error);
});
Related
i've a problem using a php page that execute query on a DB.
The php page is this:
$Query = $_POST['Query'];
// Create connection
$conn = new mysqli($servername, $username, $password,$db);
$result = mysqli_query($conn, $Query);
$emparray = array();
while($row = mysqli_fetch_assoc($result)) {
$emparray[] = $row;
}
echo json_encode(['result' => $emparray]);
mysqli_close($conn);
My Angular request page:
export class RegisterComponent implements OnInit {
constructor(private http: HttpClient) { }
ngOnInit(): void {
}
confirmRegisterClick(username: string, password: string, phoneNumber: string, email: string) {
this.http.post<any>(MYPHPPAGE, new HttpParams().append(QueryNameService, "Select Count(*) As Count From User Where Username='" + username + "'")).subscribe(data => {
console.log(data);
});
});
}
}
This return a json with the result of the query. The problem is that if i execute the call to the php page from postman or from the browser it works well. If i call it from Angular i get this error:
Access to XMLHttpRequest at 'https://www. .... /TestCOR.php' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
I've tried a lot of online solution anyone work.
I've tried to make a simple php page like that:
<?php
header('Access-Control-Allow-Origin: *');
echo "You have CORS!";
?>
but i always get the same error
Solution Tried:
1:
Add this line to the php page
header('Access-Control-Allow-Origin: *');
2:
Add this lines to the http request header
let headers = new HttpHeaders({
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Headers': 'Content-Type',
'Access-Control-Allow-Methods': 'GET,POST,OPTIONS,DELETE,PUT',
'Authorization': 'Bearer szdp79a2kz4wh4frjzuqu4sz6qeth8m3',
});
3:
Use a proxy (i don't know if i did it well, i'm noob to Angular)
"/WEBSITEPATH": {
"target": "http:\\localhost:4200",
"secure": false,
"changeOrigin": true
}
And add this line inside angular.json:
"proxyConfig": "proxy.conf.json"
I connect to db by php code,I wrote some code to get data with axios.get in react native. But response from axios.get is string not array.
I tried eval(response) and JSON.parse(response) but I can not convert response to array.
here is my react native code, it is writen in componentDidMount
const mobile = "0912111111";
const data = {
mobile: mobile
};
var headers = {
'Content-Type': 'application/json'
}
axios.get('http://192.168.1.3/Account/family_manage.php',{data:data},
{headers:headers})
.then((response) => {
//how to convert response to array of array here
console.log(eval(response).data);
})
.catch(function (error) {
Alert.alert('error');
console.log(error);
});
here is my code in php backend:
header("Access-Control-Allow-Origin: *");
include "connect.php";
$json = file_get_contents('php://input');
$obj = json_decode($json,true);
$mobile=$obj['mobile'];
$sql = "SELECT box_name,num_box FROM family_box WHERE
admin_mobile='$mobile'";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_array($result)){
$myarr[] =array('name'=> $row['box_name'],'num'=>$row['num_box']);
}
echo json_encode($myarr);
} else {
echo "0 results";
}
mysqli_close($conn);
How can I get array of array response and How can I access to 'name' or num in response data?
thanks
in axis you don't need to convert data into stringify it can automatically done by this you can directly use this like this.setState({response:response})
and if you want to see that data into onscreen for check you can also check by console.warn(response)
here's an example that I used for my app
async function getshoppinapi(link) {
let responseJson = await axios.get(link,{ headers: {"Authorization" : `Bearer ${global.token}`} })
//let responseJson = response;
return responseJson;
}
here's my issue:
I did a very basic angularJS app which is supposed to get data from a php file and bind them into the scope. So the php file (linked to MySQL DB) output is:
[{"hum":"55.36","temp":"20.86","unixtime":"2015-10-29 17:39:42","coreid":"xxxxxx","moist":"0.02","volt":"4.30","soc":"114"},
{"hum":"55.33","temp":"20.84","unixtime":"2015-10-29 17:39:50","coreid":"xxxxxx","moist":"0.00","volt":"4.30","soc":"114"},
{"hum":"55.42","temp":"20.84","unixtime":"2015-10-29 17:39:58","coreid":"xxxxxx","moist":"0.02","volt":"4.30","soc":"114"}]
The app's code is:
var dashb = angular.module('dashboard', []);
//avoid cross domain issue
dashb.config(['$httpProvider', function($httpProvider) {
$http.defaults.useXDomain = true;
delete $httpProvider.defaults.headers.common['X-Requested-With'];
}
]);
dashb.controller('dbCtrl', ['$scope', '$http', function ($scope, $http) {
$http.get("http://www.domain.com/php_file_url.php")
.success(function(data) {
$scope.data = data;
$scope.hum = data.hum;
})
.error(function() {
$scope.data = "error in fetching data";
});
}]);
But when I run it it doesn't work. I get no data. What do I do wrong? Thank you
If you're sure you're getting data from your query, you just need to send it as JSON. Add this before the echo $res; line:
header('Content-Type: application/json');
Also, in your code, change the following
$http.defaults.useXDomain = true;
to
$httpProvider.defaults.useXDomain = true;
I really like the help here and normally i figured out any Problem so far just by reading the existing Posts. However this time i can't quiet figure out whats wrong in my code.
I want to write dataildata values of a specific Tablerow in a form. The Data is stored in an mysql database and I access it with php.
The Probleme is that it seems that the Ajax request isn't working. neighter the success nor the error Event get triggered. Although the alter(id) works just fine.
Here is the Ajax call of the function:
$( "#table1 tbody tr" ).on( "click", function() {
var id = $(this).attr('id');
alert( id );
$.ajax({
type: 'POST',
url: 'getDetailData.php',
dataType: 'json',
data: {id : id },
success: function(data){
$("#inputWstId").val(data.WST-ID);
$("#inputSerialNumber").val(data.SERNO);
$("#inputName").val(data.NAME);
alert(data.NAME);
alert ("Test");
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
});
and here is the .php File:
<?php
header('Content-Type: application/json');
$connect = include 'connect.php';
if (isset ($_POST['id'])){
$id= $_POST['id'];
}
$query = " select * FROM pci WHERE id= ". $id ;
$result = mysql_query($query);
$ligne = mysql_fetch_array($result);
$data = array(
"WST-ID" => $ligne["WST_ID"],
"SERNO" => $ligne["SERNO"],
"NAME" => $ligne["NAME"]
);
mysql_close($connect);
echo (json_encode($data));
?>
If you Need more sourcecode or anything else just let me know- Thank you so much for your help!!
WST_ID instead of WST-ID really worked - thank you so much !!
Why is it, that I can't use a "-" in my values ... guess there is a lot more to learn ;)
In the PHP part you need add two more headers :
header("Access-Control-Allow-Origin: *");
header('Access-Control-Allow-Methods: GET, POST');
Add the two line of coding with the:
header('Content-Type: application/json');
change the:
echo (json_encode($data));
to:
print $my_json = json_encode($data);
or:
print_r ($my_json);
Hope it will work.
I think you need to give absolute url. Only getDetailData.php will not work. Try http://xyzabc.com/getDetailData.php
I have a jquery script that just runs fine on http://mysite.com
and looks like this:
Javascript:
$('#form_changePass').live('submit', function() {
//alert('form_changePass cliked');
$.POST("_ajaxCall.php", $(this).serialize(),
function(data){
var json = eval('('+data+')');
//alert(data);
if(json.message=='alert') {
$('div.info').hide();
$('div.alert').show().html(json.string);
}
if(json.message=='info') {
$('div.alert').hide();
$('div.info').show().html(json.string);
}
}
);
return false;
})
PHP script:
if ($_POST['formType']=="form_changePass") {
.....
.......
$arr = array( 'message' => 'info', 'string' => $INFO['updatePass']);
echo json_encode($arr);
}
Now when I move the domain into https the jquery script is not working anymore. I do not get any return value back. Nothing happens.
I also tried to change the POST to getJSON in the javascript and changed the $_POST to $_GET in the php script but it is still not working.
Anybody a idea?
http and https are considered different domains, so it is a cross domain issue. The fix is:
header('Access-Control-Allow-Origin: https://domain.com');
Add this to your php script. Or this only in development so you don't need to worry too much:
header('Access-Control-Allow-Origin: *');
.serialize serializes the form data as a string, so send them using a parameter instead.
$('#form_changePass').on('submit', function() {
//alert('form_changePass cliked');
$.POST("_ajaxCall.php", { formData: $(this).serialize() },
function(data){
var json = eval('('+data+')');
//alert(data);
if(json.message=='alert') {
$('div.info').hide();
$('div.alert').show().html(json.string);
}
if(json.message=='info') {
$('div.alert').hide();
$('div.info').show().html(json.string);
}
}
);
return false;
})
And stop using .live() methods, they have been deprecated now. Use .on() methods.