How can I get the results of a JSON POST back - javascript

I'm posting this JSON from a form page
<script src="http://ajax.googleapis.com/ajax/libs/dojo/1.7.1/dojo/dojo.js" type="text/javascript"></script>
<script type="text/javascript">
function poster()
{
var dataToPost = {grant_type: "password", username: dojo.byId("username").value, password: dojo.byId("password").value, redirect_uri: "http://localhost/default.html"};
var xhrArgs =
{
url: "https://localhost/api/did/authenticate?client_id=12345",
handleAs: 'json',
postData: dojo.toJson(dataToPost),
headers: { "Content-Type": "application/json; charset=UTF-8", "Accept" : "application/json" },
load: function(data, args)
{
alert("Data = " + data);
},
error: function(error, args)
{
alert("Error! " + error);
}
}
dojo.rawXhrPost(xhrArgs);
}
</script>
But I'm not able to get the JSON results from said POST. How can I get those results? Please help. The data I get on the load function is null

The script at https://localhost/api/did/authenticate needs to print or echo or write or otherwise return the JSON as text as it exits.

Turns out that what I was trying to do is not possible in JavaScript since I'm trying to do it from one domain into another... so the cross-domain implementation is not possible, unless I use an embedded flash object, or a proxy pass in my server. thanks for the help though...

Related

Unable to access JSONBin.io even I have added the Auth Headers

So, basically, I am trying to get data from JSONbin.io. I have set the RequestHeader before I send the request. As you see there's beforeSend and xhr.setRequestHeader("X-Master-Key", "$2b$10$QCzFeVffyq7vaiSBUfPbCeXUGV.IBpiHlWIOsDQAgj########");. But, it still say Error 401 aka unauthenticated request. I wondering if someone can help me with this. I also provide image that show that the headers is there.
Link: https://jsonbin.io/api-reference
Image: https://ibb.co/jGtFLk9
<script>
function getKey() {
$.ajax({
url: 'https://api.jsonbin.io/b/624efc9cd8a4cc06909d66cd/2',
type: "GET",
dataType: "json",
beforeSend: function(xhr) {
xhr.setRequestHeader("X-Master-Key", "$2b$10$QCzFeVffyq7vaiSBUfPbCeXUGV.IBpiHlWIOsDQAgj########");
},
success: function(data) {
const keyStore = data.keys;
var copyKey = document.getElementById("KeyDisplay");
document.getElementById('KeyDisplay').value = keyStore[Math.floor(Math.random() * 49)]
document.getElementById('Button').textContent = "Copied Key"
document.getElementById("Button").disabled = true;
copyKey.select();
navigator.clipboard.writeText(copyKey.value);
}
});
}
</script>
```
[1]: https://i.stack.imgur.com/zQxGv.png

How to receive judgement result from model of Custom Vision with JavaScript

I want to receive judgement result from model of Azure Custom Vision by using JavaScript.
I changed JavaScript code that this site has.
https://southcentralus.dev.cognitive.microsoft.com/docs/services/eb68250e4e954d9bae0c2650db79c653/operations/58acd3c1ef062f0344a42814
But I can't.
What is wrong with my code?
I changed IterationId, application, url, content-Type, Prediction-key, and data.
These part are enclosed with {} in the code below.
<!DOCTYPE html>
<html>
<head>
<title>Human</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js">
</script>
</head>
<body>
<script type="text/javascript">
$(function() {
var params = {
// Request parameters
"iterationId": "{Iteration id that showed in Performance Page}",
"application": "{My Project name of Custom Vision}",
};
$.ajax({
url: "{url that showed in "How to use the Prediction API"}" + $.param(params),
beforeSend: function(xhrObj){
// Request headers
xhrObj.setRequestHeader("Content-Type","application/octet-stream");
xhrObj.setRequestHeader("Prediction-key","{my prediction key that showed in "How to use the Prediction API"}");
},
type: "POST",
// Request body
data: "D:\some name\some name\image.jpg",
})
.done(function(data) {
alert("success");
})
.fail(function() {
alert("error");
});
});
</script>
</body>
</html>
Of course, I expected showing "success".
But, the actual output is "error"......
When I changed URL that this site has(https://southcentralus.dev.cognitive.microsoft.com/docs/services/eb68250e4e954d9bae0c2650db79c653/operations/58acd3c1ef062f0344a42814) in my code, I can get Success message.
And, I also write
processData: false,
contentType: false,
in ajax in my code
Change your code to see what is the error that you get back:
(Note the new "error" parameter to the request)
$.ajax({
url: "{url that showed in "How to use the Prediction API"}" + $.param(params),
beforeSend: function(xhrObj){
// Request headers
xhrObj.setRequestHeader("Content-Type","application/octet-stream");
xhrObj.setRequestHeader("Prediction-key","{my prediction key that showed in "How to use the Prediction API"}");
},
type: "POST",
// Request body
data: "D:\some name\some name\image.jpg",
error: function(xhr,status,error) {
// >>>>>>>>>>>> CHECK HERE THE ERROR <<<<<<<<<<<<
}
})
.done(function(data) {
alert("success");
})
.fail(function() {
alert("error");
});
Once you have the error, it would be easier to help you.

Unable to pass formData with other parameters in jQuery

I am trying to pass formData along with other parameters to a PHP script.
Using the $.post method, I was getting an 'Illegal Invocation' error. So I abandoned the $.post method and went to $.ajax method.
As follows:
$('#uploadBtn').on('click', function()
{
var formData = new FormData($('#uploadfile')[0]); // the form data is uploaded file
var booking = $('#bookingNum').val();
var partner = $('#partnerCode').val();
var parameters =
{
formData:formData,
booking:booking,
partner:partner
}
$.ajax({
url: 'process/customer.php',
data: parameters, // <- this may be wrong
async: false,
contentType: false,
processData: false,
cache: false,
type: 'POST',
success: function(data)
{
console.log(data);
},
error: function(jqHHR, textStatus, errorThrown)
{
console.log('fail: ' + errorThrown);
}
});
});
On the PHP side, I'm trying to get the parameters object like so:
<?php
if(isset($_POST['parameters']))
{
echo "Hello";
$value = $_POST['parameters'];
// I can get the other 2 parameters like this
$company = htmlspecialchars(trim($value['booking']));
$partner = htmlspecialchars(trim($value['partner']));
// not sure how to get the uploaded file information
}
?>
Basically, I am uploading a file to be saved to a directory. But the problem is, I cannot send anything over to the PHP side. I am getting this warning:
"jquery.js:2 [Deprecation] Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check https://xhr.spec.whatwg.org/."
I need to be able to send the 'parameters' object over to the PHP script, then access it for processing.
How can I achieve this using the $.ajax method? Then how do I access the formData once on the PHP side?
The parameters is the object you are POSTing. the key value pairs will be based on it's properties. Try accessing them like $_POST['formData'] and $_POST['booking'].
Also... please rework your code to remove the async:false ... TBH this should never have been put into jQuery and is absolutely terrible. Don't feel bad, it's the first thing every newcomer tries when they first start using ajax, myself included. You're going to cause the UI thread to hang for the duration, preventing all user interaction during the call.
EDIT
I didn't realize you are trying to post a file at first, so this is not a complete answer as I don't think you are accessing it correctly. But The important part of this answer is that there is no parameters index of $_POST (which is why not even your echo "hello" is coming back).
if you POST an object that looks like
{
key1 : "value1",
key2 : "value2"
}
they will come through to php as
$_POST['key1'];//"value1";
$_POST['key2'];//"value2";
important to note, files posted to the server are typically found in the $_FILES superglobal. (don't know if AJAX changes that, but I imagine not)
EDIT2
Combining the two... this is the general idea. Make your html + JS look like...
$('#form').on('submit', function()
{
var form_data = new FormData();
form_data.append("file", document.getElementById('fileInput').files[0]);
var booking = $('#bookingNum').val();
var partner = $('#partnerCode').val();
form_data.append("booking ",booking);
form_data.append("partner",partner);
$.ajax({
url: 'process/customer.php',
method:"POST",
data: form_data,
contentType: false,
cache: false,
processData: false,
success: function(data)
{
console.log(data);
},
error: function(jqHHR, textStatus, errorThrown)
{
console.log('fail: ' + errorThrown);
}
});
return false;//prevent default form submission
});
<form id='form'>
<input type='file' id='fileInput' />
<label for='bookingNum'>Booking Num: </label>
<input type='text' id='bookingNum' name='bookingNum' />
<label for='partnerCode'>Partner Code:</label>
<input type='text' id='partnerCode' name='partnerCode' />
<button id='uploadBtn'>Submit</button>
</form>
and try it with your php code like
<?php
if($_POST['bookingNum']){
var_dump($_POST['bookingNum']);
}
if($_POST['partnerCode']){
var_dump($_POST['partnerCode']);
}
if($_FILES['file']){
var_dump($_FILES['file']);
}
$('#uploadBtn').on('click', function()
{
var form_data = new FormData();
form_data.append("file", document.getElementById('ID').files[0]);
var booking = $('#bookingNum').val();
var partner = $('#partnerCode').val();
form_data.append("booking ",booking);
form_data.append("partner",partner);
$.ajax({
url: 'process/customer.php',
method:"POST",
data: form_data,
contentType: false,
cache: false,
processData: false,
success: function(data)
{
console.log(data);
},
error: function(jqHHR, textStatus, errorThrown)
{
console.log('fail: ' + errorThrown);
}
});
});

ajax post call not working

I am trying to call MVC Controller from jquery but not able to place the call. Is there any problem in below code
Please figure out that if any problem and also I am not getting any error.
url="http://localhost:49917/Account/SaveAddress"
this.SaveAddress = function (url, addressData)
{
$.ajax({
type: "POST",
url: url,
dataType: "json",
data: JSON.stringify(addressData),
contentType: 'application/json; charset=utf-8',
success: function (responseDetail) {
},
error:function(e)
{
},
});
return 0;
};
public async Task<ActionResult> SaveAddress(AddressListViewModel addressListVM)
{
bool response;
string message;
if (addressListVM.ID <= 0)
{
response = await Task.Run(() => AccountManager.Instance().AddAddress(addressListVM));
message = response ? "New address added successfully." : "Failed to add new address.";
}
else
{
response = await Task.Run(() => AccountManager.Instance().UpdateAddress(addressListVM));
message = response ? "Selected address updated successfully." : "Failed to update selected address.";
}
ModelState.Clear();
return Json(new { responsestatus = response, message = message }, JsonRequestBehavior.AllowGet);
//return PartialView("_AddressDetail", BuildAddressListEntity(
// UserManager.FindById(User.Identity.GetUserId()), response, message, addressListVM.ID, true));
}
Yes, you are missing a closing bracket at the end of the this.saveaddress function
this.SaveAddress = function (url, addressData)
{
$.ajax({
type: "POST",
url: url,
dataType: "json",
data: JSON.stringify(addressData),
contentType: 'application/json; charset=utf-8',
success: function (responseDetail) {
},
error:function(e)
{
},
});
after all of that .. you need one more closing bracket:
}
;)
What does the console display? If you are using Chrome then right-click, choose Inspect, and find the Console tab. If you are calling the AJAX function correctly then something must be displayed in this Console tab which will probably lead you in the right direction better than I could with the information I have.
Put a breakpoint in your success and error functions. If it hits the error function then the issue is either that the controller action was not found or that the data is not valid json (either the post data or return data). You should add the errorThrown parameter to the error function so you can easily see what the issue is. You also do not need to stringify the data if it is already valid json, but if it is a string representing json data, you will need to use json.parse (sorry for the incorrect case).

cakephp 2.2 retrieve json data in controller

I'm trying to send JSON data from a web page using JQuery, like this:
$.ajax({
type: "post", // Request method: post, get
url: "http://localhost/ajax/login",
data: '{username: "wiiNinja", password: "isAnub"}',
dataType: "json", // Expected response type
contentType: "application/json",
cache: false,
success: function(response, status) {
alert ("Success");
},
error: function(response, status) {
alert('Error! response=' + response + " status=" + status);
}
});
In cake2.2, I have a controller named Ajax that has a method named "login", like this:
public function login($id = null)
{
if ($this->RequestHandler->isAjax())
{
$this->layout = 'ajax'; // Or $this->RequestHandler->ajaxLayout, Only use for HTML
$this->autoLayout = false;
$this->autoRender = false;
$response = array('success' => false);
$data = $this->request->input(); // MY QUESTION IS WITH THIS LINE
debug($data, $showHTML = false, $showFrom = true);
}
return;
}
I just want to see if I'm passing in the correct data to the controller. If I use this line:
$data = $this->request->input();
I can see the debug printout:
{username: "wiiNinja", password: "isCool"}
I read in the CakePHP manual 2.x, under "Accessing XML or JSON data", it suggests this call to decode the data:
$data = $this->request->input('json_decode');
When I debug print $data, I get "null". What am I doing wrong? Is my data passed in from the Javascript incorrect? Or am I not calling the decode correctly?
Thanks for any suggestion.
============= My own Edit ========
Found my own mistake through experiments:
When posting through Javascript, instead of this line:
data: '{username: "wiiNinja", password: "isAnub"}',
Change it to:
data: '{"username": "wiiNinja", "password": "isAnub"}',
AND
In the controller code, change this line:
$data = $this->request->input('json_decode');
To:
$data = $this->request->input('json_decode', 'true');
It works.
Dunhamzzz,
When I followed your suggestions, and examine the "$this->request->params" array in my controller code, it contains the following:
array(
'plugin' => null,
'controller' => 'ajax',
'action' => 'login',
'named' => array(),
'pass' => array(),
'isAjax' => true
)
As you can see, the data that I'm looking for is not there. I've already got the the proper routes code. This is consistent with what the documentation for 2.x says here:
http://book.cakephp.org/2.0/en/controllers/request-response.html
So far, the only way that I found to make it work, is as stated above in "My own Edit". But if sending a JSon string to the server is not the right thing to do, I would like to fix this, because eventually, I will have to handle third party code that will send JSon objects.
The reason you are struggling wit the data is because you are sending a string with jQuery, not a proper javascript object (JSON).
$.ajax({
type: "post", // Request method: post, get
url: "http://localhost/ajax/login",
data: {username: "wiiNinja", password: "isAnub"}, // outer quotes removed
dataType: "json", // Expected response type
contentType: "application/json",
cache: false,
success: function(response, status) {
alert ("Success");
},
error: function(response, status) {
alert('Error! response=' + response + " status=" + status);
}
});
Now the data will be available as a PHP array in $this->request->params.
Also for sending a JSON response, please see this manual page. Most of your code there can be reduced to just 2 lines...
//routes.php
Router::parseExtensions('json');
//Controller that sends JSON
$this->set('_serialize', array('data'));

Categories

Resources