angular $http.post() and php? - php

I know there are several posts on SO and on many blogs explaining how to get the JSON data that was sent to be read by php. Some use url-encoding, others file_get_contents.
Anyway, it doesn't work for me. I'm sure there is ridiculously easy explanation for it but my code simply doesn't work (the request is sent, the backend answers but that message is more or less always the same: nothing seems to arrive there !
So in my controller I have :
var request_data = {
firstname: 'Quentin',
lastname: 'Hapsburg'
};
$http.post("lib/api/public/blog/post", JSON.stringify(request_data))
.success(function(data) {
console.log(data);
})
And in the php file:
$data = file_get_contents("php://input");
$data = json_decode($data, TRUE);
var_dump($data);
The result is NULL !
Any suggestions on where my error is ???
EDIT: This might have something to do with the rewriting rules but is not a duplicate since the same answer does not solve this question !

try using application/x-www-form-urlencoded
$http.post(urlBase, $httpParamSerializer(object), {
headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'},
}).then(function(r) {
callback(r);
});
and then php will be able to access to your posted object using $_POST

Please use this js file. It will work
Index.html:
<html>
<head>
<script src="js/angular.min.js"></script>
</head>
<body ng-app="myApp">
<div ng-controller="mainCtrl">
sdadasdasd
</div>
<script src="app.js"></script>
</body>
</html>
app.js:
var app = angular.module("myApp", []);
app.controller("mainCtrl", function($scope,$http){
var request_data = {
firstname: 'Quentin',
lastname: 'Hapsburg'
};
$http.post("test.php", JSON.stringify(request_data)).success(function(data) {
console.log(data);
});
});

Related

Fetch data to php file returning null value

I'm trying to test and learn how fetch works so I want to send some data from javascript to a php file, my problem is that I can't retrieve the data (in the php file), only getting a null response.
I'm using POST but I have tried with GET with the same result
As a side note, in console the conection in network only appears after I press F5 , as I understand it, to work should be already when I open Test.php.
datosJS.js
let datos = {
method: "POST",
headers: {
"Content-type" : "application/json"
},
body: JSON.stringify({
username:"Jonathan",
email:"jonathan#gmail.com",
password:"123456"
})
}
fetch('Test.php',datos)
.then(resp => resp.text())
.then(resp =>{
console.log(resp);
})
Test.php
<script src="datosJS.js" type="text/javascript"></script> //I use this to call "datosJS.js" to receive the data here in Test.php
<?php
$body = json_decode(file_get_contents("php://input"), true);
var_dump($body);
?>
I understand PHP is on server side and JS on client side and both of them run in different times, nevertheless I'm having troubles to find the solution to this problem.
Thank you for your help !
** Edited a small change in fetch which now let me see the data in console
Well finally I managed to get the solution to this, explanation is below:
datosJS.js
window.onload = function() {
let datos = {
method: "POST",
headers: {
"Content-type" : "application/json"
},
body: JSON.stringify({
username:"Jonathan",
email:"jonathan#gmail.com",
password:"123456"
})
}
fetch('Test.php',datos)
.then(resp => resp.text())
.then(resp =>{
console.log(resp);
document.getElementById('results').innerHTML = resp;
//document.querySelector('#results').innerHTML = resp; // works as well as getElementById
})
}
Test.php
<script src="datosJS.js" type="text/javascript"></script>
<section class="Section" id="results" name="results">
<?php
$body = json_decode(file_get_contents("php://input"), true);
$nombre = $body['username'];
echo $nombre;
echo '</br>';
print_r($body);
?>
Below I will mark what was lacking in the original code:
In datosJS.js document.getElementById('results').innerHTML = resp; and wrap everything in window.onload = function() {}
In Test.php add the id="results" name="results" to a div, section or whatever to receive from the innerHTML.
I hope it helps someone in the future. Cheers

Receive data from API and send it to another page via AJAX

I'm receiving data from an API (asana) when an event was made in my workspace via a POST method in a file called asanatarget.php
The data is correct and i can store it in file when received.
Looks like that:
{"events":"resource":xxx,"user":xxx,"type":"story","action":"added","created_at":"2019-02-20T14:48:09.142Z","parent":xxx}]}
In the same file I send the data to a new file with AJAX with GET method:
asanatarget.php
<?php
if(isset($_SERVER['HTTP_X_HOOK_SECRET'])) {
$h = $_SERVER['HTTP_X_HOOK_SECRET'];
header('X-Hook-Secret:' . $h);
exit;
}
?>
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
</head>
<body>
<?php
$input = file_get_contents('php://input');
if ($input) {
$entries = json_decode(file_get_contents('php://input'), true);
file_put_contents('targetasanaDATA' . time() . '.txt', json_encode($entries));
?>
<script>
$( document ).ready(function() {
$.ajax({
type: "GET",
url: "/asanawebhook", // Working with laravel, the route is well defined
data: <?php echo json_encode($entries); ?>,
dataType: "json",
success: function(response){
console.log("success " + response);
},
error: function(jqXHR, textStatus, errorThrown) { // What to do if we fail
console.log(JSON.stringify(jqXHR));
}
});
});
</script>
<?php
}
?>
</body>
</html>
When i'm directly loading asanatarget.php with test data, it's working fine and the data is passed to /asanawebhook but when the data is passed directly from the api, it's not working.
I checked and the data is always correct
Your PHP script generates only a HTML page (basically, a text).
The javascript can be interpreted and executed by a browser. But if no browser reads this page and execute it, nothing happens. PHP generates a webpage, nobody reads it, and things ends here.
You can use PHP too to send data via POST. You can build your query with http_build_query() and use file_get_contents().

How do I pass data to a php file using jquery AJAX

I'm new to using AJAX methods and am completely stumped with what seems like a very simple procedure.
I'm trying to post data to a php file using AJAX in order to create a folder on my server. No matter what I try it seems as if it's not actually posting data to the php file. I can end up creating a folder directly into the 'users' folder if I remove the $_POST command from the php file... but the second I try to actually create a variable from the posted data so it creates the folder inside of a nested subfolder it fails.
please please please help. I'm losing it. haha.
Someone suggested another thread to solve the problem below... but it still doesn't seem to be working. I'm using the same approach that is suggested in that thread.
Here is my script:
JQuery
<script type="text/javascript>
$('#buildSave').click(function() {
$.ajax({
url: "../php/preparesave.php",
type: "POST",
data: { user : 'Tommy' }
});
});
</javascript>
PHP
<?php
$user = $_POST['user'];
if (!file_exists('../users/' . $user . '/Platoons/')) { mkdir('../users/' . $user . '/Platoons/'); }
?>
Here is the AJAX that I suggest using
$(document).ready(function(){
$('#save').click(function() {
$.ajax({
url: '../php/preparesave.php',
type: 'POST',
data: { user : 'Tommy' },
success: function(output){
alert(output);
}
});
});
});
And below is the PHP (I tried it on my machine and it works)
$user = $_POST['user'];
if(!file_exists('../users/' . $user . '/Platoons/')){
if(mkdir('../users/' . $user . '/Platoons/', 0777, true)){
die('Success');
}else{
die("Folder `../users/{$user}/Platoons/` failed to be created");
}
}
The way you have it, it will only try to create "/Platoon" in a folder $user (Tommy in your example) but that folder doesn't exist and so the script is failing. You need to set the recursive parameter to true so it would first create the folder that doesn't exist and then everything else inside it and then them.
Allows the creation of nested directories specified in the pathname. (Straight from the docs)
There were two errors in your code. Try to compare your lines with the one below.
$('#buildSave').click(function() {
$.ajax({
url: "../php/preparesave.php",
type: "POST",
data: { user : 'Tommy' }
});
});
Try to edit your action url. Use only preparesave.php if you are calling ajax in /php folder. try to use url:"preparesave.php", if this doesnt work then use
url: "preparesave.php?user=Tommy",
Hope it could solve your issue.
THE SIMPLEST POSSIBLE ANSWER
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js</script>
<script>
var cars = ["Saab", "Volvo", "BMW"];
$(document).ready(function(){
$("button").click(function(){
$.post("test2.php",
{
cars
},
function(data,status){
alert("Data: " + data + "\nStatus: " + status);
});
});
});
</script>
</head>
<body>
<button>POST the cars array</button>
</body>
</html>
AND THE PHP.....
<?php
$myVar = $_POST['cars'];
$number = count($myVar);
for ($count = 0; $count < $number; $count++){
echo $myVar[$count];
}
?>
enter code here

Ajax with CodeIgniter - data not received on server side

I have the following AJAX:
$.ajax({
type: "POST",
url: base+"tree/plant/",
data:{
name: $('#field_treename').val(),
summary: $('#field_summary').val(),
description: $('#field_description').val(),
address: $('#field_url').val(),
category: $('#field_category').val()
}
})
.done(function(resp){
$('#plant-tree-inner').html(resp);
});
base is my base URL, tree is a controller and plant is a method in that controller.
The URL is correct, the controller and method are in place, with correct names. I've made sure of that by echoing a string in the plant method and it appeared correctly on the client after the AJAX response.
However, none of the post data seems to be arriving at the server.
Doing echo $this->input->post('name'); inside the plant method gives an empty string. Doing var_dump($_POST) gives an empty array. I even tried giving parameters to the plant method but that just throws a missing parameter error.
So where is the data getting lost and why?
EDIT: I see now that my question is wrong. It has nothing to do with CodeIgniter, since the data isn't being sent at all. The field values are undefined according to Javascript, but they certainly exist in HTML:
<input type="text" id="field_treename" placeholder="Tree name" value="" />
Seems like something is wrong with jQuery library.
For test' sake, try to send request avoiding it.
You may try this also..
$.ajax({
type: "POST",
url: base+"tree/plant/",
data:{
name: $('#field_treename').val(),
summary: $('#field_summary').val(),
description: $('#field_description').val(),
address: $('#field_url').val(),
category: $('#field_category').val()
}
success:function(resp){
$('#plant-tree-inner').html(resp);
}
});
Try to simulate the problem in the very basic method like creating another directory in your localhost or server like this and create files as describe below.
in the index.php
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>POST Sending Problem</title>
<script src="jquery-1.12.2.js"></script>
</head>
<body>
Link
<script src="custom_function.js"></script>
</body>
</html>
Create js file for example test.js and put this as test
function test (id, base) {
$.ajax({
type: "POST",
data: {
'id': id
},
url: base,
success: function(data) {
alert(data);
},
error: function(data) {
alert('no data');
}
});
}
Next create a php file your_phpfile.php
<?php
if (isset($_POST['id'])) {
echo $_POST['id'];
} else {
echo "no-result";
}
?>
This would help you determine the problem. If this works fine, try applying it using codeigniter.
Good Luck
User this one..
var request = "name="+$('#field_treename').val()+"&"
request += "summary="+$('#field_summary').val()+"&"
request += "description="+$('#field_description').val()+"&"
request += "address="+$('#field_url').val()+"&"
request += "category="+$('#field_category').val()
and in set as data=request. This should work.

Send JSON to PHP and get a response

I'm just learning how to use jQuery and PHP together. This is my first attempt, and I feel like I'm almost getting the concept. However, there's an issue I failed to address. When I post a JSON object to PHP script and try to return one of the parameters, I get the following error : "Trying to get property of non-object in ..."
index.html:
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-git2.js"></script>
<meta charset=utf-8 />
<title>JS Bin</title>
<style id="jsbin-css"></style>
</head>
<body>
<button onClick="postData();">Submit me!</button>
<script>
function postData() {
var myData = {
'firstName' : 'John',
'lastName' : 'Doe'
};
$.ajax( {
type: "POST",
url: "postData.php",
contentType: "application/json",
data: myData,
success: function(msg){
alert(msg);
},
error: function(err) {
alert('error!' + err);
}
});
}
</script>
</body>
</html>
postData.php:
<?php
$input = file_get_contents('php://input');
$jsonData = json_decode($input);
$output = $jsonData->{'firstName'};
echo $output;
?>
With a bit more work, you can achieve this using a REST client that will automatically handle data-type conversion and URL parsing among other things.
To name some of the advantages of using a REST architecture:
Simple.
You can easily scale your solution using caching, loading-balancing etc.
Allows you to logically separate your URL-endpoints.
It gives you the flexibility to change implementation easily without changing clients.
Try reading, A Brief Introduction to REST to get a better idea about the design pattern and it's uses. Of course you won't need to write a framework from scratch if you don't want to, since there are already several open-source PHP based implementations out there such as Recess PHP Rest Framework.
Hope this helps!
json_decode (depending on PHP version) defaults to returning an array, not an object. The proper way to access it would be:
$output = $jsonData['firstname'];
You'll also want it to return an associative array, so pass true as the second argument of json_decode.
$jsonData = json_decode($input, true);
What could alternately be happening is that the JSON is invalid, in which case PHP returns null. You can check for that:
if ($jsonData = json_decode($input, true) === null) {
// Do stuff!
} else {
// Invalid JSON :(
}
I put it a little bit more simple with the function post of jquery.
I hope you found it useful:
first your html and js:
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-git2.js"></script>
<meta charset=utf-8 />
<title>JS Bin</title>
<style id="jsbin-css">
</style>
</head>
<body>
<button onClick="postData();">Submit me!</button>
<script>
function postData() {
$.post(
"postData.php",
{
firstName : 'John',
lastName : 'Doe'
},
function(msg)
{
alert(msg);
}
);
}
</script>
</body>
</html>
then your php:
<?php
echo $_REQUEST['firstName']." - ".$_REQUEST['lastName'];
?>
I finally figured it out:
js:
function postData() {
var myData = {
firstName: 'John',
lastName: 'Doe'
};
$.ajax({
type: "POST",
url: "postData.php",
data: JSON.stringify(myData),
success: function(msg){
alert(msg);
},
error: function(err){
alert('error!' + JSON.stringify(err));
}
});
}
php:
<?php
$input = file_get_contents('php://input');
$jsonData = json_decode($input);
$output = $jsonData->{'firstName'};
echo $output;
?>
When decoding you DON'T want to put "true" as the second argument, because then, it's not JSON but an associative array (or so I've read). If I put json_decode($input, true), then it won't work.

Categories