I am new to ionic1 framework and working on sidemenu ionic app. I want to get list of playlist from Mysql Database.
I have tried this in my controller.js :
.controller('PlaylistsCtrl', function($scope,$http) {
$http.get("#/php/list.php")
.success(function (response) {
$scope.playlists = response.records;
});
console.log($scope.playlists);
})
Php file code :
header("Content-Type: application/json; charset=UTF-8");
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST');
$json[] =array('title'=>'Reggae','id'=>1);
$json[] =array('title'=>'test','id'=>2);
echo json_encode($json);
It gives undefined.
Please help me where I am going wrong.
Your code works asynchron. That is why you add an anonymous function to retrieve the data.
The console.log is called right after the request but before the response is there. So $scope.playlists is empty.
You have to put the console.log inside the success callback to see the result.
Related
I'm trying to do a basic POST request from my ionic angular app using the HttpClient from Angular. From that POST, I need to pass the payload to PHP file for me to manipulate another function in the PHP.
I can seem to echo the whole data, but trying to get the single value gives an error.
Below is my code under home.ts
test() {
let data = {
firstname: "John",
lastname: "Wick"
}
const headers = new HttpHeaders();
headers.set('Content-Type', 'application/json; charset=UTF-8');
headers.set('Access-Control-Allow-Origin', '*');
headers.set('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, PUT');
this.http.post(this.php_url, data, {headers: headers}).subscribe((res) => {
console.log("Posted successfully")
console.log(res);
}, (err) => {
console.log(err.error);
});
}
In my index.php file, I have the code below.
<?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Headers: *');
header('Content-Type: application/json');
$json = file_get_contents('php://input');
echo $json->firstname;
?>
I am able to echo $json, but not when trying to get the single value. How do I get the single value from the JSON data?
you have to use
print_r($json['firstname']);
insted of
echo $json->firstname;
Iam using the Axio Reactjs code below to post form data to php backend.
when I check record.php files from the chrome browser console and
network. it shows that connection is okay but posted data is empty. it seems like the axios is not sending the data to php backend.
I have tried some solutions here on SO but cannot get it to work. Any work around will be appreciated.
axios({
method:'POST',
url:'http://localhost/mydata/record.php',
rec:{
myParameter1: 'test',
myParameter2: 'test2',
}
}).then(res => {
const data = res.data;
this.setState({ data });
console.log(data);
})
.catch(err => { // log request error
//this.setState({ error: false });
console.error(err);
})
php code
<?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST');
header("Access-Control-Allow-Headers: X-Requested-With");
//header("Content-Type: application/json");
//check if file_get_contents is enabled
if( ini_get('allow_url_fopen') ) {
echo "enabled";
} else{
echo "not enabled";
}
$data = file_get_contents("php://input");
$request = json_decode($data);
print_r($request);
print_r($data);
?>
In axios docs you can find data tag:
https://github.com/axios/axios#request-config
// `data` is the data to be sent as the request body
// Only applicable for request methods 'PUT', 'POST', and 'PATCH'
// When no `transformRequest` is set, must be of one of the following types:
// - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams
// - Browser only: FormData, File, Blob
// - Node only: Stream, Buffer
data: {
firstName: 'Fred'
},
// syntax alternative to send data into the body
// method post
// only the value is sent, not the key
data: 'Country=Brasil&City=Belo Horizonte',
this is what you need, there is no rec property in axios config
Try removing the key rec in your data segment in axios or better still do something along the lines of
{
rec: {
myParameter1: 'test',
myParameter2: 'test2',
}
}
I'm trying to POST data to a PHP backend and receive back the values and push it into an array. Hence, I created a function to do just that. However, I'm not to change the API on the backend (written in PHP). So I cannot change it to suit my normal methods of using POST.
This is my function
test() {
let data = "method=getThis" + "&db=myDatabase"
this.http.post("API URL", data).subscribe(data => {
this.result = data; // get data in result variable
this.items = JSON.stringify(this.result); // then convert data to json string
// console.log(this.items);
this.allData = JSON.parse(this.items); // parse json data and pass json string
// console.log(this.allData.length); // got result of particular string
this.array = [];
for (var i = 0; i < this.allData.length; i++) {
this.array.push({
data1: this.allData[i].data1,
data2: this.allData[i].data2,
})
}
console.log(this.array[0])
})
}
And this is an example function on the backend
else if($_POST['method']=="getThis"){
global $conn;
mysqli_select_db($conn, $_POST['db']);
$name="";
$result=array();
$r=mysqli_query($conn,"select data1,data2 from table");
while ($rs = mysqli_fetch_array($r,MYSQLI_ASSOC)){
array_push($result,$rs);
}
echo json_encode(array("result"=>$result));
}
So how do I actually get it to post? I'm stuck here. I usually post with JSON and then decode the JSON on the backend. But this time around I'm not developing the backend and not changing it so gotta use the one provided.
Posting using POSTMAN with this
method=getThis&db=myDatabase
works well. Not sending JSON just a text. So how do I actually achieve this in Ionic.
You could try it that way. It works for me:
First import:
import { map } from "rxjs/operators/map";
Your function:
test() {
let data = "method=getThis" + "&db=myDatabase"
this.http.post("API URL", data).pipe(
map(res => res.json())
).subscribe(response => {
//Here your code
// 'response' is json
});
}
Since the data you are sending is in plain text, you will need to add a header mentioning the content type.
import { HttpHeaders } from '#angular/common/http';
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'text/html'
})
};
this.http.post("API URL", data, httpOptions).subscribe()
PHP side should be return JSON and told browser content type is application/json, please test your code base on one simple page.
//demo.php
<?php
$data = ['message' => 'Hello world.'];
header("Content-Type: application/json; charset=UTF-8");
//If allow cross domain and not configration in Ngix/Apache
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS");
header("Access-Control-Allow-Headers: Accept-Encoding, X-Requested-With, Content-Type, Origin, Accept, Authenticationtoken");
echo json_encode($data);
And please try http access demo.php again.
I am trying to make a post request from my angular js, as below
var postData={
firstName:'VenuGopal',
lastName:'Kakkula'
};
postData=JSON.stringify(postData);
$http({method:'POST',url:'http://localhost/blog/posttest.php?insert=true',data:postData,headers: {'Content-Type': 'application/x-www-form-urlencoded'}})
.success(function (data,status,headers,config) {
alert('Success' + data);
})
.error(function (data, status,headers,config) {
// uh oh
alert('error' + status + data);
});
I am not sure how to read this POST DATA in my PHP REST webservice.
<?php
header("Access-Control-Allow-Origin:*");
header('Access-Control-Allow-Headers:Content-Type');
header("Content-Type:application/json");
if(!empty($_GET['insert']))
{
$result=json_decode($_POST['firstName']);
deliver_response(200,"Got the Post data","GotData $result");
}
function deliver_response($status,$statusmsg,$data)
{
header("HTTP/1.1 $status $statusmsg");
$response['status']=$status;
$response['status_message']=$statusmsg;
$response['data']=$data;
$json_response=json_encode($response);
echo $json_response;
}
?>
I tried the below options
json_decode($_POST['firstName'])
json_decode($_POST['data'])
json_decode($_POST['[postData'])
None of them returned the data, Its always returning the error Undefined index: firstName in F:\xampp\htdocs\Blog\posttest.php on line 10
Can anybody help me how I can read the POST request data sent in php file.
Most likely it is because you are submitting JSON data which is not automagically populated into the $_POST variable per standard form data.
The work around is to manually parse the input into a variable for use.
Example:
<?php
$args = json_decode(file_get_contents("php://input"));
echo $args->firstName;
?>
You can also solve this problem without changing code in server and use $_POST the regular way. Explained here: http://victorblog.com/2012/12/20/make-angularjs-http-service-behave-like-jquery-ajax/
I've Googled every instance of this error I can find, and none of the solutions work for me. In essence, I am doing what others have suggested. Despite that, I am receiving an error that my callback function is not being called. I am using Ajax/Jquery/JASONP to do a cross domain form submission using GET. Here is my code on the form side:
$(document).ready(function() {
$("#ajaxform1").submit(function(e){
e.preventDefault();
var surl = "http://blahblah/test_create_user.php?callback=?";
$.ajax({
type: 'GET',
url: surl,
crossDomain: true,
data: $('#ajaxform1').serialize(),
dataType: "jsonp",
success: function(msg) {
$.each(msg, function (index, value) {
if(value==1)
{
alert("New User Added");
} else {
alert("User Already Exists")
} }
});
},
error: function(xhr, status, error) {
var myerror = xhr+" "+status+" "+error;
alert("Failure Connecting to Kayako. Please Try Again("+myerror+")"); }
});
Here is the applicable snippet of my PHP Code:
if($USER_CHK->first()->id){
$data = array('msg' => '0'); // user exists
else {
$data = array('msg' => '1'); // User added
}
//echo customerAdded(FALSE);
header('Access-Control-Allow-Origin: '.$_SERVER['HTTP_ORIGIN']);
header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
header('Access-Control-Max-Age: 1000');
header('Access-Control-Allow-Headers: Content-Type, Authorization,X- Requested- With');
header("Content-type: application/json");
$data = array('msg' => '0');
print $_REQUEST['callback']. '('.json_encode($data).')';
exit;
});
});
My debugging shows that all form variables are getting posted.
The PHP code returns: jQuery11020900643879813015_1397599599587({"msg":"1"})
Yet the error indicating the callback was not called is thrown.
How does the request looks like on the server side?
I have a working example which is very similar to what you have. The only difference is that the content type I am replying with is:
'text/javascript'
Also, my JSONP message includes a semicolon at the end (which I think is not really a cause for failure).
returnJSONP = $_REQUEST['callback']. '('.json_encode($data).');';
If you were able to resolve, could you please post the solution?
I gave up trying to get this working and, instead, posted to a local php script which then used CURL to post to the remote server. I echo the CURL results back to the jQuery function and all works well.