HTTP 422 Error with JSON & jQuery + Human API - php

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>

Related

Problem reposting data periodically using AJAX to Laravel backend

Am working on a PHP Laravel project whereby when a user clicks on a button on the website I perform some background task using AJAX to a PHP backend whreby I trigger a call to a payment gateway, when the user pays via his/her phone,,, I check the payment status (where 1 means paid, 0 means not paid) and if status is equal to 1, I redirect the user to a success page.
Currently am using AJAX to post data from the frontend to the backend and I want to post the data periodically after 5 seconds (where I give the user some time to pay before reaching out to the API to see if the status has changed to 1 then redirect the user).
Am trying to use setTimeout method in JavaScript and dd() the data from the controller which only dumps the data once but doesnt dump after 5 seconds
AJAX code to post data to the backend after 5 seconds
$('.mpesa').on('click', function () {
// run the first time; all subsequent calls will take care of themselves
setTimeout(executeQuery, 5000);
});
function executeQuery() {
alert('clicked');
//Adds Class to the page when it loads
$('.PAY').addClass("loading");
//Gets the MPESA type
var type = $('.mpesa').prop('id');
var quote = $('#quote').val();
var phone = $('#phone').val();
//Converts to a JSON object
var type ={
'type': type,
'quote' : quote,
'phone' : phone,
};
console.log(type);
$.ajax({
//Contains controller of payment
type: 'POST',
url: 'paymentFinal',
data: JSON.stringify(type),
contentType: 'application/json',
dataType: "json",
success: function success(response) {
console.log(response);
},
error: function error(data) {
console.log(data);
}
});
}
//End AJAX call
Controller file being called
public
function payFinal(Request $request)
{
dd($request->all());
}
Updated AJAX code
$('.mpesa').on('click', function () {
setInterval(function() {
alert('clicked');
//Gets the MPESA type
var type = $('.mpesa').prop('id');
var quote = $('#quote').val();
var phone = $('#phone').val();
//Converts to a JSON object
var type ={
'type': type,
'quote' : quote,
'phone' : phone,
};
console.log(type);
$.ajax({
//Contains controller of payment
type: 'POST',
url: 'paymentFinal',
data: JSON.stringify(type),
contentType: 'application/json',
dataType: "json",
success: function success(response) {
if(response) {
window.location.href="success";
}
},
error: function error(data) {
console.log(data);
}
});
}, 15000); // Execute every 15 seconds
});
setTimeout only executes the specified function once after the delay you set. Use setInterval instead so your function get called periodically.
=========================================================================
Update:
You want your function to execute immediately when the user clicks and after that calls itself every 15 secs. To achieve that, you can just use the following code:
$('.mpesa').on('click', executeQuery);
function executeQuery() {
alert('clicked');
//Adds Class to the page when it loads
$('.PAY').addClass("loading");
//Gets the MPESA type
var type = $('.mpesa').prop('id');
var quote = $('#quote').val();
var phone = $('#phone').val();
//Converts to a JSON object
var type ={
'type': type,
'quote' : quote,
'phone' : phone,
};
console.log(type);
$.ajax({
//Contains controller of payment
type: 'POST',
url: 'paymentFinal',
data: JSON.stringify(type),
contentType: 'application/json',
dataType: "json",
success: function success(response) {
console.log(response);
},
error: function error(data) {
console.log(data);
}
});
//use setTimeout here
setTimeout(executeQuery, 15000);
}
Use setTimeout in your function to call itself would solve your problem.
=========================================================================
[To answer OP's question on how to stop the timer]
In your function, say you want the function to stop execution after 5 times.
Set up a variable outside of the function:
var counter = 0;
Then in executeQuery:
if (counter <= 5) { //or use your own logic
counter++;
setTimeout(executeQuery, 15000);
}
Remember that setTimeout is a one-time-thing, so you can just control when to stop calling it.

AJAX call is not working as expected

I am trying to send form data using ajax. But there's an error in ajax operation and only "error" callback function is executed.
Here's what I tried:
$("#issue_submit").click(function (e) {
console.log("clicked on the issue submit");
e.preventDefault();
// Validate the form
var procurementForm = $("#it_procuremet_form");
if($(procurementForm).valid()===false){
return false;
}
// Show ajax loader
appendData();
var formData = $(procurementForm).serialize();
// Send request to save the records through ajax
var formRequest = $.ajax({
url: app.baseurl("itprocurement/save"),
data: formData,
type: "POST",
dataType: "json"
});
formRequest.done(function (res) {
console.log(res);
});
formRequest.error(function (res, err) {
console.log(res);
});
formRequest.always(function () {
$("#overlay-procurement").remove();
// do somethings that always needs to occur regardless of error or success
});
});
Routes are defined as:
$f3->route('POST /itprocurement/save', 'GBD\Internals\Controllers\ITProcurementController->save');
Also I added :
$f3->route('POST /itprocurement/save [ajax]', 'GBD\Internals\Controllers\ITProcurementController->save');
I tried returning a simple string to the ajax call at the controller class.
ITProcurementController.php :
public function save($f3)
{
echo 'Problem!';
return;
$post = $f3->get('POST');
}
But only 'error' callback is executed. I cannot locate what is wrong. Please Help.
You are specifying that you expect json back:
// Send request to save the records through ajax
var formRequest = $.ajax({
url: app.baseurl("itprocurement/save"),
data: formData,
type: "POST",
// Here you specify that you expect json back:
dataType: "json"
});
What you send back is not json:
echo 'Problem!';
return;
This is an unquoted string, which is not valid json.
To send valid json back, you would need:
echo json_encode('Problem!');
return;
You could also remove the dataType attribute, depending on your needs.

Send data from Javascript to PHP and use PHP's response as variable in JS

I have checked around, but can't seem to figure out how this is done.
I would like to send form data to PHP to have it processed and inserted into a database (this is working).
Then I would like to send a variable ($selected_moid) back from PHP to a JavaScript function (the same one if possible) so that it can be used again.
function submit_data() {
"use strict";
$.post('insert.php', $('#formName').formSerialize());
$.get('add_host.cgi?moid='.$selected_moid.');
}
Here is my latest attempt, but still getting errors:
PHP:
$get_moid = "
SELECT ID FROM nagios.view_all_monitored_objects
WHERE CoID='$company'
AND MoTypeID='$type'
AND MoName='$name'
AND DNS='$name.$selected_shortname.mon'
AND IP='$ip'
";
while($MonitoredObjectID = mysql_fetch_row($get_moid)){
//Sets MonitoredObjectID for added/edited device.
$Response = $MonitoredObjectID;
if ($logon_choice = '1') {
$Response = $Response'&'$logon_id;
$Response = $Response'&'$logon_pwd;
}
}
echo json_encode($response);
JS:
function submit_data(action, formName) {
"use strict";
$.ajax({
cache: false,
type: 'POST',
url: 'library/plugins/' + action + '.php',
data: $('#' + formName).serialize(),
success: function (response) {
// PROCESS DATA HERE
var resp = $.parseJSON(response);
$.get('/nagios/cgi-bin/add_host.cgi', {moid: resp });
alert('success!');
},
error: function (response) {
//PROCESS HERE FOR FAILURE
alert('failure 'response);
}
});
}
I am going out on a limb on this since your question is not 100% clear. First of all, Javascript AJAX calls are asynchronous, meaning both the $.get and $.post will be call almost simultaneously.
If you are trying to get the response from one and using it in a second call, then you need to nest them in the success function. Since you are using jQuery, take a look at their API to see the arguments your AJAX call can handle (http://api.jquery.com/jQuery.post/)
$.post('insert.php', $('#formName').formSerialize(),function(data){
$.get('add_host.cgi?moid='+data);
});
In your PHP script, after you have updated the database and everything, just echo the data want. Javascript will take the text and put it in the data variable in the success function.
You need to use a callback function to get the returned value.
function submit_data(action, formName) {
"use strict";
$.post('insert.php', $('#' + formName).formSerialize(), function (selected_moid) {
$.get('add_host.cgi', {moid: selected_moid });
});
}
$("ID OF THE SUBMIT BUTTON").click(function() {
$.ajax({
cache: false,
type: 'POST',
url: 'FILE IN HERE FOR PROCESSING',
data: $("ID HERE OF THE FORM").serialize(),
success: function(data) {
// PROCESS DATA HERE
},
error: function(data) {
//PROCESS HERE FOR FAILURE
}
});
return false; //This stops the Button from Actually Preforming
});
Now for the Php
<?php
start_session(); <-- This will make it share the same Session Princables
//error check and soforth use $_POST[] to get everything
$Response = array('success'=>true, 'VAR'=>'DATA'); <--- Success
$Response = array('success'=>false, 'VAR'=>'DATA'); <--- fails
echo json_encode($Response);
?>
I forgot to Mention, this is using JavaScript/jQuery, and ajax to do this.
Example of this as a Function
Var Form_Data = THIS IS THE DATA OF THE FORM;
function YOUR FUNCTION HERE(VARS HERE) {
$.ajax({
cache: false,
type: 'POST',
url: 'FILE IN HERE FOR PROCESSING',
data:Form_Data.serialize(),
success: function(data) {
// PROCESS DATA HERE
},
error: function(data) {
//PROCESS HERE FOR FAILURE
}
});
}
Now you could use this as the Button Click which would also function :3

Why won't my .ajax request work?

The code I want to work:
$.ajax({
type: "POST",
url: "_Source/ajap/ajap.nlSrch.php",
data: { sndJson : jsonData },
dataType: "json",
processData: false,
success: function(html) {
$("#srchFrm").append(html);}
});
The code that works:
$.ajax({
type: "POST",
url: "_Source/ajap/ajap.nlSrch.php",
data: { sndJson : jsonData },
success: function(html) {
$("#srchFrm").append(html);}
});
Unfortunately when I send the first one my post data looks like this "Array ()" and when I use the later I get this "Array ( [sndJson] => [\"8\",\"3\",\"6\",\"7\"] )".
I know that there has to be a simple explanation but I haven't been able to figure it out.
Help please!
Try sending your data in a query string...
$.ajax({
type:"POST",
url:"_Source/ajap/ajap.nlSrch.php?json="+jsonData,
dataType:"json",
success: function(data) {
$("#srchFrm").append(data);}
error: function(xhr, ajaxOptions, thrownError)
{alert("Error!");}
});
You can use shorthand $.post instead of using low level ajax class --- because you don't need to advanced handling. So, this one will be great enough.
$(document.ready(function(){
$("#submit_button").click(function(){
$.post('php_script.php', {
// here's what you want to send
// important -- double quotes, 'cause It's evals as valid JSON
"var1" : "val1"
"var2" : "val2"
}, function (respond){
try {
var respond = JSON.parse(respond);
} catch(e){
//error - respond wasn't JSON
}
});
});
});
PHP code:
<?php
/**
* Here you can handle variable or array you got from JavaScript
* and send back if need.
*/
print_r($_POST); // var1 = val1, var2 = val2
?>
Back to your question,
Why my .ajax request doesn't work?
This is because JavaScript throws fatal error and stops further code execution.
You can catch and determine the error occasion, simply by adding
try {} catch(){} block to the statement you think may occur any error
When you specify dataType: json, jQuery will automatically evaluate the response and return a Javascript object, in this case an array. You're taking the result and adding it as html to #srchForm, so it does not make sense to convert it to a javascript object. Use dataType: html, or none at all.
http://api.jquery.com/jQuery.ajax/
The following examples above are not reusable. I am a huge fan of reuseable code. here is my solution.
Software design 101:
DRY Don't repeat your self. You should wrap your code into an object. This way you can call it from anywhere.
var Request = {
version: 1.0, //not needed but i like versioning things
xproxy: function(type, url, data, callback, timeout, headers, contentType)
{
if (!timeout || timeout <= 0) { timeout = 15000; }
$.ajax(
{
url: url,
type: type,
data: data,
timeout: timeout,
contentType: contentType,
success:function(data)
{
if (callback != undefined) { callback(data); }
},
error:function(data)
{
if (callback != undefined) { callback(data); }
},
beforeSend: function(xhr)
{
//headers is a list with two items
if(headers)
{
xhr.setRequestHeader('secret-key', headers[0]);
xhr.setRequestHeader('api-key', headers[1]);
}
}
});
}
};
Usage:
<script type="text/javascript">
var contentType = "applicaiton/json";
var url = "http://api.lastfm.com/get/data/";
var timeout = 1000*5; //five seconds
var requestType = "POST"; //GET, POST, DELETE, PUT
var header = [];
header.push("unique-guid");
header.push("23903820983");
var data = "{\"username\":\"james\"}"; //you should really deserialize this w/ a function
function callback(data)
{
//do logic here
}
Request.xproxy(requestType, url, data, callback, timeout, header, contentType);
</script>

Workaround possible for cURL and Javascript?

Everything was going great in my previous help request thread. I was on the correct track to get around a CSRF, but needed to be pointed in the right direction. I received great help and even an alternate script used to log into Google's Android Market. Both my script and the one I altered to match my form is get hung up at the same point. Apparently cURL cannot process JS, is there any way to work around the form being submitted with submitForm() without changing the form?
Here is the code for the SubmitForm function
function submitForm(formObj, formMode) {
if (!formObj)
return false;
if (formObj.tagName != "FORM") {
if (!formObj.form)
return false;
formObj = formObj.form;
}
if (formObj.mode)
formObj.mode.value = formMode;
formObj.submit();
}
Here is the code for the submit button -
<a class="VertMenuItems" href="javascript: document.authform.submit();">Submit</a>
Here is a link to my last question in case more background information is needed.
PHP service...
<?php
// PHP service file
// Get all data coming in via GET or POST
$vars = $_GET + $_POST;
// Do something with the data coming in
?>
Javascript elsewhere...
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
function sendData(data)
{
var response;
$.ajax({
url: 'phpservice.php',
data: data,
type: 'POST',
dataType: 'json',
async: false,
success: function(response_from_service)
{
response = response_from_service;
},
error: function()
{
}
});
return response;
};
function getData(data)
{
var response;
$.ajax({
url: 'phpservice.php',
data: data,
type: 'GET',
dataType: 'json',
async: false,
success: function(response_from_service)
{
response = response_from_service;
},
error: function()
{
}
});
return response;
};
});
</script>

Categories