Can php handle multiple http post request at the same time? - php

I'am working on angularjs project in which there are 2 users admin and office staff.And to insert data to database i need to send data to server using http request using post method and this request is received on server side in php. This is simple request to server with some parameters and its working correctly until both the users hit submit button and http request is made at the same time. ie when http request is made by both the users at the same time.If that happens than 2nd request is does not get any response.Now my question is that is there a way to check if server is processing one http request and make 2nd request wait.
angularjs:
$http({
method: "post",
url: $localStorage.weburl + "abc.php?f=abc_data",
timeout: 1 * 10 * 2000,
params: {
action: "add"
},
data: {
data1: data1,
data2: data2
}.then(function mySucces(response) {
}, function myError(err) {
$ionicLoading.hide();
alert("Please check the connection");
})
});
PHP:
function abc_data($conn)
{
$_POST = json_decode(file_get_contents('php://input'), true);
}

You should try like this way
var deferred = $q.defer();
$http.post($localStorage.weburl + "abc.php",{action: "add"})
.success(function (data) {
deferred.resolve(data);
})
.error(function (error) {
deferred.reject(error);
});
return deferred.promise;
If you are using post method then pass you data like {data:arrayOfdata} instead of url: $localStorage.weburl + "abc.php?f=abc_data"

Related

Can't reach PHP code from a JQuery POST Call (Error Undefined Index)

I am trying to pass data from a JS script to a PHP file.
I am using JQuery post as follows:
const Url2 = 'MainPage2.php?action=updatePurchaseToDB';
const data = {
action: "updatePurchaseToDB",
name: "test name"
}
//takes 3 arg, url, data to send, call back function, data in callback holds the page reqeusted in data
$.post(Url2,data, function(data, status){
console.log(`status is ${status} data : ${data}`);
alert("PHP Retrned form server: Status " + status + " Data: " + data);
});
}
This appears to execute correctly as the status is returned as successful.
The PHP code I am looking to reach :
if ($_POST['action'] == 'updatePurchaseToDB'){
echo "<script>$(`#purchaseButton`).html('Test- received data');</script>";
}
The following error is thrown:
Undefined Index: action
Not sure why as the action is declared in the URL and data parameters.
If I try same with a Ajax call:
$.ajax({
url: 'MainPage2.php?action=updatePurchaseToDB',
type: 'POST',
success: function(data)
{
console.log(data);
}
});
Again I get a successful response form the server and same error.
I read this post but I must be reading it incorrectly.
I understand there are allot of answers with a similar question but I was having difficulty finding same for my situation.
Input appreciated.
Contents of $_POST is data lines after HTTP headers.
But your action=updatePurchaseToDB is part of the request url. You should access it thru $_GET["updatePurchaseToDB"].
And one question about
echo "<script>$(`#purchaseButton`).html('Test- received data');</script>";
Isn't it should be
echo "<script>$('#purchaseButton').html('Test- received data');</script>";
In the first case, even if the parameter is in the url or as a data parameter, you are calling as a GET, so the Post is index unavailable.
In the second case you are doing a post, but the parameter 'updatePurchaseToDB' is a GET parameter, you aren't sending any data to PHP file. again, the index will be unavailable.
Try it:
const data = {
action: "updatePurchaseToDB",
name: "test name"
}
$.ajax({
url: 'MainPage2.php?action=updatePurchaseToDB',
type: 'POST',
data: data,
success: function(data){
console.log(data);
}
});

Why this ajax request is successful when request method is GET but fails in POST method

When I set the request type to "GET",(and also use $_GET on server side), it successfully fetches the response,
but gives a 400 error, Missing required parameters: student_id when I set the type to POST.
Here's the code :
$.ajax({
type: "GET",
url: "?r=fees/fees/transactions",
dataType: "json",
data: { student_id: student_id },
success:function( msg ) {
console.log(msg);
},
error: function(xhr, ajaxOptions, thrownError){
console.log("failed");
console.log(xhr.responseText);
console.log(ajaxOptions);
console.log(thrownError);
}
});
Here is the request URL when I set the request method to GET:
http://localhost/demo.git/index.php?r=fees/fees/transactions&_csrf=bEJJWVowdl8jBwQjaUMsAA52eT8MXBMLJigwHTxeKSlVKyxoD2o5KQ%3D%3D&student_id=10115".
why doesn't this work when I set the above request type to POST and receive the variable on server side by POST method?
Here is the server side action (I am using Yii2 MVC framework)
public function actionTransactions($student_id){
$student_id = $_POST['student_id'];
...
...
echo json_encode($response);
}
Your function need param $student_id from GET method. If youre using AJAX to send request, using data: { 'student_id': student_id }, - it will be added to your URL where AJAX is sent.
If you want to use POST method, you have to modify your URL:
url: "?r=fees/fees/transactions?student_id=" + student_id,
And remove data key.
Second solution is to remove $student_id param from your actionTransactions, then system will accept requests without $student_id in GET, but you will have to ensure, that it's in $_REQUEST.

HTTP 422 Error with JSON & jQuery + Human API

I am using the Human API found here: https://docs.humanapi.co/docs/connect-backend
At one point in connecting to the API, I need to send data back to them as JSON. I get a JSON object called sessionTokenObject which contains this:
{
humanId: "1234567890",
clientId: "abcdefg",
sessionToken: "9876zyx",
}
To which I'm supposed to add a clientSecret. Essentially, I'm taking what's in the JSON object, converting it individual variables, passing them through to another page via URL parameters and then reconstructing everything so that I can add the clientSecret like so:
$pop_clientid = $_GET['clientid'];
$pop_humanid = $_GET['humanid'];
$pop_userid = $_GET['userid'];
$pop_sessiontoken = $_GET['clientid'];
$my_sessiontokenobject = '{
humanId: "'.$pop_humanid.'",
clientId: "'.$pop_clientid.'",
sessionToken: "'.$pop_sessiontoken.'",
clientSecret: "thesecretgoeshere"
}'; ?>
<script type="text/javascript">
jQuery(document).ready(function($) {
$.ajax({
type: "POST",
url: 'https://user.humanapi.co/v1/connect/tokens',
data: '<?php echo $my_sessiontokenobject; ?>',
success: null,
dataType: 'application/json'
});
});
</script>
If I don't wrap the data value in the .ajax() call in apostrophes, I get a 422 error back from https://user.humanapi.com/v1/connect/tokens
If I do, I get an "Uncaught SyntaxError: Unexpected token ILLEGAL" error.
Can anyone see what's wrong with my code, or perhaps even tell me if trying to recreate a JSON object and then pass it back via .ajax() in the manner I am is just completely incorrect?
Try with this: (Returns a 404 Not found error, but it seems that it is in their side)
connectBtn.addEventListener('click', function(e) {
var opts = {
// grab this from the app settings page
clientId: clientId,
// can be email or any other internal id of the user in your system
clientUserId: clientUserId,
clientSecret: clientSecret,
finish: function(err, sessionTokenObject) {
console.log(sessionTokenObject);
// When user finishes health data connection to your app
// `finish` function will be called.
// `sessionTokenObject` object will have several fields in it.
// You need to pass this `sessionTokenObject` object to your server
// add `CLIENT_SECRET` to it and send `POST` request to the `https://user.humanapi.co/v1/connect/tokens` endpoint.
// In return you will get `accessToken` for that user that can be used to query Human API.
sessionTokenObject.clientSecret = clientSecret;
jQuery(document).ready(function($) {
$.ajax({
type: "GET",
url: url,
dataType: 'jsonp',
contentType: "application/json",
data: sessionTokenObject,
});
});
// clientId=ceb8b5d029de3977e85faf264156a4e1aacb5377&humanId=f54fa4c56ca2538b480f90ed7b2c6d22
// $.post(url, sessionTokenObject, function(res){
// console.log(res);
// });
},
close: function() {
// do something here when user just closed popup
// `close` callback function is optional
}
}
HumanConnect.open(opts);
});
Human API Code for Testing, this code generates accessToken from Human API Developer Side but its not coming as in response while i execute this code
<script src='https://connect.humanapi.co/connect.js'></script>
<script>
var options = {
clientUserId: encodeURIComponent('email'), //Unique ID of user on your system (we send this back at the end)
clientId: '',
publicToken: '',
finish: function (err, sessionTokenObject) {
/* Called after user finishes connecting their health data */
//POST sessionTokenObject as-is to your server for step 2.
console.log(sessionTokenObject);
sessionTokenObject.clientSecret = 'Client Secret Key';
$.ajax({
type: 'POST',
url: 'https://user.humanapi.co/v1/connect/tokens',
method: 'POST',
data: sessionTokenObject
})
.done(function (data) {
console.log(data);
// show the response
if (data.success) {
alert(data.success);
} else {
alert(data.error);
}
})
.fail(function (data) {
console.log(data);
// just in case posting your form failed
alert("Posting failed.");
});
// Include code here to refresh the page.
},
close: function () {
/* (optional) Called when a user closes the popup
without connecting any data sources */
alert('user clicked on close Button');
},
error: function (err) {
/* (optional) Called if an error occurs when loading
the popup. */
}
}
function openHumanApiModel() {
HumanConnect.open(options);
}
</script>

Pulling data from AngularJS $http request

I sending a request to my php file to get data from database from my AngularJS file. Some-time I am getting data also lot of time there is no response is coming.
Here is my AngularJS code:
myApp.controller('PageCtrl', function PageCtrl($scope, $routeParams, $http) {
$http.post(APP_URL + "server/FullDesc.php", {id: parseInt($routeParams.Id)}).success(function (data) {
var timer = setTimeout(function () {
$scope.Details = data[0];
console.log(data);
$scope.$apply($scope.Details);
}, 10);
}, 'json');
})
In resposne I am getting output of my response like this
In image you can see there is no response showing. How to solve this issue.
You should try adding an error scenario as well:
myApp.controller('PageCtrl', function PageCtrl($scope, $routeParams, $http) {
$http.post(APP_URL + "server/FullDesc.php",
{id: parseInt($routeParams.Id)}
).then(function(successResponse){
var data = successResponse.data;
console.log('successResponse', data);
$scope.Details = data[0];
//$scope.$apply($scope.Details); // assigning to scope should automatically do an apply
}, function(errorResponse){
console.log('errorResponse', errorResponse);
});
});
Then you should also check what is being sent to the server and what the server sends back. It seems your server may be encountering an error and you are not sending an error response back.

Posting XML data to a PHP API via Phonegap/Ajax

I've been task with building an app to check on the status of servers through a phonegap app. The trouble is the client is not giving me access to the existing API or the server. The only information he has given me is: "You can send a POST request to the xmlUserApi.php named "request" by jQuery for example."
As I understand it, we are sending some XML in the format
<xmlApi>
<action> getServerList </action>
<auth></auth>
</xmlApi>
For example, from which a an XML list of all the servers is returned.
Whenever I try to POST this data to the PHP (xmlUserApi.php), nothing is returned. I feel it would be helpful to look through the PHP, but, the client won't let me.
Any help/ideas would be really appreciated
EDIT
The response I'm getting in the inspector is :
<form action=xmlUserApi.php method=post>
<textarea name=request cols=120 rows=30></textarea>
<input type=submit value=Request></form><br><br>86.135.213.213
What your client is suggesting is programmatically replicating the action of a user filling out the form at the address they provided.
To do that, try this:
var xmlData = '<xmlApi><action> getServerList </action><auth>xxxxxx</auth></xmlApi>';
var serverPath = 'http://some.com/path/';
var requestPath = 'xmlUserApi.php';
var request = $.ajax({
url: requestPath,
type: 'POST',
dataType: 'jsonp',
data: { request: xmlData }
});
request.done(function(data) {
/process data
});
request.fail(function(jqXHR, textStatus) {
alert(textStatus);
});
//Leaving original answer down here
"You can send a POST request to the xmlUserApi.php named "request" by jQuery for example."
Not sure what they mean by 'named "request"', but with jQuery you would do this:
var serverPath: 'http://their.server.tld/path/';
var authToken: 'sometoken';
$.post(serverPath + 'xmlUserApi.php', { action: 'getServerList', auth: authToken },
function(data) {
//whatever you want to do with the return goes here
}
);
There may also be an issue with the connection to the API, sometimes passing additional parameters helps with this, you could try:
var serverPath = 'http://their.server.tld/path/';
var requestPath = serverPath + 'xmlUserApi.php';
var authToken = 'sometoken';
$.ajax({
url: requestPath,
type: 'POST',
dataType: 'jsonp',
data: { action: 'getServerList', auth: authToken }
}).done(function(data) {
//processing here
}).fail(function(jqXHR, textStatus) {
alert(textStatus);
});

Categories