angularjs can't communicate with php using POST - javascript

I am trying to send and then get data from PHP on my server, but I don't think it sends the data.
My js code:
angular
.module('h2hApp', [])
.controller('mainCtrl', ['$scope', '$http', function(scope, http) {
scope.initGames = function() {
http({
method: 'POST',
url: 'apis.php',
data: {
url: someUrl
}
})
.success(function(data) {
console.log(data);
});
};
scope.initGames();
}]);
and my PHP file:
<?php
$url = $_POST['url'];
echo file_get_contents($url);
?>
The only thing I get in response is that error:
Notice: Undefined index: url in /my/path/apis.php on line 2
I made this working using jQuery but with AngularJS it doesn't seem to work. I'm new to Angular and I read some other problems like this. I tried things like adding headers and other things but nothing worked.

You can be forgiven for thinking that your PHP script should be expecting data in the $_POST variable as encoding your data as a query string has traditionally always been the default mechanism.
Angular however encodes the message body as a JSON object by default. As mentioned you could use the params instead however in the long run I'd argue that it's more flexible to conform on the server-side. For example you can read and decode the message body as follows:
<?php
$data = json_decode( file_get_contents('php://input') );
echo $data->url;

It should be 'params', not 'data'. See http://docs.angularjs.org/api/ng/service/$http#usage

Be sure to set the HTTP header, sort of like this:
$http.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';
More info on using Post from AngularJS to PHP

You can use http.post() method -
Try this the code -
http.post('apis.php', {
url: someUrl
})
.success(function(data) {
console.log(data);
});

Related

Passing data from view to controller using Ajax in Laravel

I am trying to pass two variables to my controller using ajax. There are no errors but the data is null when I get it in the controller.
Web.php
Route::get('/donate/select-card', 'CardController#chooseCard')->name('select-card');
CardController.php
public function chooseCard()
{
$from = Input::get("fromAmount");
// $to = $request->input('toAmount');
dd($from);
}
'null' is the output here
Script.js
fromAmount = $(this).find('p span:nth-child(1)').text().split("₹ ")[1];
toAmount = $(this).find('p span:nth-child(2)').text().split("₹ ")[1];
$.ajax({
type:'GET',
url: '/donate/select-card',
data: { fromAmount : fromAmount, toAmount : toAmount }
});
What I want is to have the fromAmount & toAmount in my controller.
Thanks in advance.
This is the ajax data from network:
public function chooseCard(Request $request)
{
return $request->all();
}
** Inject the Request class
** See the response from dev tool.
That one was tricky :)
In your HTML you have a link that is wrapping this call to the ajax. This is messing with
<a href="/donate/select-card">
<button type="button" onclick="test123()">click here for ajax Call</button>
</a>
So clicking on this will send you to "/donate/select-card" but won't be trough the ajax.
For the same reason, once you try to use POST, you get:
The GET method is not supported for this route. Supported methods: POST
The href is with priority and it is GET while the route is expecting a POST.
Make sure you remove all links and default behaviours around the html you use to call the ajax call then use GET or POST as you wish.

NULL in JSON/Arrays in AngularJS (front-end) and Laravel (backend)

I am having difficulty how I can handle null values. Whenever I send JSON to server, all null values in front-end becomes "null" as string. How should I handle this?
AngularJS: In my controller. I am sending values from a form using ng-file-upload plugin https://github.com/danialfarid/ng-file-upload/wiki/PHP-Example
$scope.saveNewDocument = function(){
var formAttachments = Upload.upload({
url: appServer.baseURL + appServer.api.generalDocuments,
method: 'POST',
file: $scope.formData.formAttachments,
sendFieldsAs: 'form',
fields: $scope.formData // $scope.formData is ng-model in view forms
}).then(function(success){
//some codes
}, function(error){
console.log(error);
});
};
Laravel: In my controller.
public function store(Request $request)
{
$request = $request->all();
//if I get values from request. All null becomes "null"
}
Since you haven't provided with any code, I'm not sure exactly about your problem but assuming to solve this problem in PHP (which this is tagged as) you can write a simple if statement and check the data before sending as follows:
if($var==null)
$var=0;

cross domain request data using pure javascript

I am trying to access an external url which returns json data and based on one of the value in that data I need to hide a table row. I have tried several options to do this with jsonp, jquery and ajax but nothing seem to work. YQL is working for me but I can't use outer Service as the code need to be independent. Please someone let me know how I can make this work with javascript
This is one approach I have tried
<script type='text/javascript'>
function checkBlueLight() {
$('#trBlueLight').hide();
$.getJSON('http://.../Lights/getBlueLight?callback=?', function (data) {
if (data.expDate != null) {
$('#trBlueLight').show();
} else {
$('#trBlueLight').hide();
}
});
}
</script>
This is another approach I have tried. same issue unauthorized - 401
$.ajax({
url: 'http://.../Lights/getBlueLight',
dataType: 'json',
success: function(data) {
if (data.expDate != null) {
$('#trBlueLight').show();
} else {
$('#trBlueLight').hide();
}
}
});
I have even tried to get data from url using jsp with and that also causing some permission issue
Do you control the external url? Because you can do:
On your local page:
function your_function(data) {
alert(data.message)
}
And then on http://www.include.me/remote.php (or whatever is returning JSON) you would have it return
your_function({message: "it works!"});
And then back on your local page:
var script = document.createElement("script");
script.setAttribute("type", "text/javascript");
script.setAttribute("src", "http://www.include.me/remote.php");
document.getElementsByTagName("head")[0].appendChild(script);
Which will then include the script, which simply tells it to run your already defined function with the data it provides.
If you can't control the external URL, and it doesn't support CORS nor JSONP, then you best option is to write a server side proxy method for the service. So on your server, you expose a new endpoint on your own host that on the server side access the real service on your clients behalf, and returns the result to your client.
For using jsonp, the server should bind the return type with a callback function. If it not, you cannot get the data from server.
If you are using cors, server should support that. Which means server should set,
"Access-Control-Allow-Origin" header to "*"
The issue with JS or jQuery is that crossdomain data may not be possible depending on the browser or server or a combination of both that prohibits the data exchange. This is security policy on many browsers and servers.
The best and safest choice is using a combination of JS or jQuery (Ajax call) with PHP cURL where the cURL will make the call requesting the data xml/json format and then sent back to the Ajax request.
Please take a look at the following example:
In the JS/JQuery AJax script:
$.ajax({
url: 'php_script_with_cURL.php',
dataType: 'json',
data:'THE_DATA_OR_REQUEST',
type:'post',
success: function(data) {
if (data.expDate != null) {
$('#trBlueLight').show();
} else {
$('#trBlueLight').hide();
}
}
});
and then in the php file (must be in the same server as your JS):
(you can use url string or post to request the data)
//USE POST IF YOU NEED TO SEND VARIOUS COMMANDS TO GET THE DATA BACK
$post = $_POST;
//INIT THE CURL CALL
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
//this will tell the server how to return the data format
CURLOPT_HTTPHEADER => array('Content-type: application/json'),
//use the query string if require, if not just remove it
CURLOPT_URL => 'http://THE_URL_HERE.COM?request_value=some_value',
//use the post only if yo need to post values
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => array(
value1 => $post['value1'],
value2 => $post['value2']
)
//alternative you can also pass the whole POST array
//CURLOPT_POSTFIELDS => $post
));
$data = curl_exec($curl);
if(!$data){
die('Error: "' . curl_error($curl) . '" - Code: ' . curl_errno($curl));
}
curl_close($curl);
//echo the data that will be sent to the JS/JQuery Ajax call
echo $data;
//or if you need to do more processing with php
//$response = json_decode($data);
Hope this helps :)
Happy coding !

how to send json array from controller to view in CodeIgniter

I have a function in my controller:
function getAllExpense()
{ $date=$this->frenchToEnglish_date($this->input->post('date'));
$id_user=$this->session->userdata('id_user');
$where=array('date'=>$date, 'id_user'=>$id_user);
$allExpenses=$this->expenses_model->get_all('depenses',$where);
return json_encode($allExpenses);
}
In the view, I need to do an ajax_call to getAllExpense, but I need also to retrieve the result returned by getAllExpense in case of success(and I can't do this). Here is my view
function searchExpense()
{
var date= $('#dateSearch').val();
$.ajax({
type:'POST',
url : '<?php echo site_url()."/public/expenses/getAllExpense/"; ?>',
data :'date='+date,
success:function(data)
{ $('#searchExpense').toggle();
}
});
}
and finally the form :
<div id="searchExpense" class="toogle_form" style="display:none">
<label><strong>Vos depenses :</strong></label>
<?php
if (isset($allExpenses) && ! empty($allExpenses))
{
foreach ($allExpenses as $expense)
{
echo $expense['id_depense'] ;
echo ' ';
echo $expense['commentaire'];
echo '</br>';
}
}
else
{
echo 'Vous n\'avez pas eu de depenses pour cette date';
}
?>
</div>
This does not show anything on the browser.
I can't use the method of sending data by loading the view in getAllExpense because I already load it in the function index.
Could anyone help me please?
In your controller function getAllExpense, try echoing your json data with a header rather than using return:
Change this:
return json_encode($allExpenses);
to:
$this->output->set_header('Content-Type: application/json; charset=utf-8');
echo json_encode($allExpenses);
The url:
Reading it backwards I understand getAllExpense to be your function name and expenses to be your controller name... What is /public/?
The data:
Currently you're using data :'date='+date. This is incorrect. $.ajax expects an object as the data parameter. Use data: {date: date}.
Where's the dataType?
If you're expecting json from the server, tell $.ajax this so it can parse the response properly. Use: dataType: 'json'
Your success function
It helps for debugging to call console.log() on the returned data. Inside the callback use: console.log(data); Then, open up your web tools. If you're using Chrome press ctrl+shift+j and inspect the console tab when firing your AJAX request. If you head over to the network tab and click on the most recent request (at the bottom) you can view the HTTP response as well.
"and finally the form :"
You didn't include a form.
Isolate the problem:
You're much better off inspecting the AJAX response using Chrome's Network tab as I've mentioned, but you could also isolate the issue to a client one or server one by changing your function temporarily to:
function getAllExpense(){
//$date=$this->frenchToEnglish_date($this->input->post('date'));
$date = "12/21/2012"; /*or whatever your date format is.*/
$id_user=$this->session->userdata('id_user');
$where=array('date'=>$date, 'id_user'=>$id_user);
$allExpenses=$this->expenses_model->get_all('depenses',$where);
//return json_encode($allExpenses);
echo json_encode($allExpenses);
}
And calling getAllExpense directly in the URL bar. You'll be able to see the raw json and determine if it's in a format you're happy with.

Both .getJSON() and .ajax() not working for REST API call

Can someone explain me how to make a REST call using jQuery/Javascript? I tried using the .getJSON() and .ajax(), but neither helped me.
This is the REST URL :
http://ws1.airnowgateway.org/GatewayWebServiceREST/Gateway.svc/forecastbyzipcode?zipcode=94954&date=2010-01-15&format=json&key=API_KEY
Code:
$.getJSON('http://ws1.airnowgateway.org/GatewayWebServiceREST/Gateway.svc/forecastbyzipcode?zipcode='+zip+'&format=json&key=**<KEY HERE>**',
function(data)
{
alert(data.AQI);
}
);
$.ajax({
url: 'http://ws1.airnowgateway.org/GatewayWebServiceREST/Gateway.svc/forecastbyzipcode',
type: 'GET',
data: 'zipcode='+zip+'&format=json&key=**<KEY HERE>**',
success: function() { alert('get completed'); }
});
there are a couple of problems. First, you need to add &callback=? to the end of the querystring to allow the crossdomain.
$.getJSON('http://ws1.airnowgateway.org/GatewayWebServiceREST/Gateway.svc/forecastbyzipcode?zipcode=94954&format=json&key=B868EA39-1D92-412A-96DE-DCF5ED30236D&callback=?',
function(data)
{
alert(data.forecast[0]);
}
);
You will then get an Uncaught SyntaxError: Unexpected token : error. This is because you are expecting json data, but the headers on the server are sending text/html - not application/json. Take a look at the console when you run this fiddle, you'll see the errors.
Therefore, you can't get the data from cross domain because you have to be using jsonp - which requires the header to be sent correctly.
If this is your api, then you just need to send the correct header, otherwise, you need to get with the developers there and ask them to fix it.
Alternatively
If neither of those above options work, you could always create a proxy script that would get the contents of the json feed for you and echo it out. Here's one in PHP:
<?php
// myproxy.php
header('Content-type: application/json');
$zip = $_GET['zip'];
$results = file_get_contents('http://ws1.airnowgateway.org/GatewayWebServiceREST/Gateway.svc/forecastbyzipcode?zipcode=' . $zip . '&format=json&key=B868EA39-1D92-412A-96DE-DCF5ED30236D');
echo $results;
?>
Then, you would just point your $.getJSON to this script on your server:
$.getJSON('/myproxy.php?zip='+zip,
function(data)
{
var mydata = jQuery.parseJSON(data);
alert(mydata.forecast[0]);
}
);

Categories