AngularJS $http sending data with Ajax URL - javascript

i have used this code before i use angularjs.
function ajax_post(){
// Create our XMLHttpRequest object
var hr = new XMLHttpRequest();
// Create some variables we need to send to our PHP file
var url = "myUrl";
var fn = document.getElementById("username").value;
var ln = document.getElementById("password").value;
var vars = "username="+fn+"&password="+ln;
hr.open("POST", url, true);
// Set content type header information for sending url encoded variables in the request
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Access the onreadystatechange event for the XMLHttpRequest object
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
if(return_data=="1"){
console.log("this is return data"+return_data);
}else{
ons.notification.alert({message: 'Login Failed!'});
}
}
}
// Send the data to PHP now... and wait for response to update the status div
hr.send(vars); // Actually execute the request
}
Here with AngularJS to do same thing
$scope.ajaxLogin = function(){
var fn = document.getElementById("username").value;
var pw = document.getElementById("password").value;
$http({
url: "myURL",
method: "POST",
data: { username: fn, password: pw },
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).success(function(data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
if(status == 200) {
var return_data = data;
if(return_data == 0){
console.log("test "+data,status);
$scope.showAlertSucess();
}else{
$scope.showAlertError();
}
}
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
$scope.showAlertNetwork();
});
};
but AngularJS way its not giving expected output which is "1" it gives "0".
and i went through webconsole what i got is this part is different, i think it send data like JSON
data: { username: fn, password: pw },
but my other code its not like that
var vars = "username="+fn+"&password="+ln;
how to fix it to use with angularJS.
for more to understand here my PHP Code.
if ($result=mysqli_query($con,$sql))
{
$rowcount=mysqli_num_rows($result);
printf($rowcount);
mysqli_free_result($result);
}

If you use AngularJs to provide variable in PHP use this code
$array = json_decode(file_get_contents('php://input'));
In $array input your variables.

Related

Using JavaScript how do I sent JSON from Razor page to Controller in MVC .NET Core

I have a razor page with the following JavaScript code that gets the JSON object. From this code, how can I send the JSON object to a controller? (MVC Core.NET 3.0)
I now this sounds crazy - the only reason I'm doing this is to demo this project for Charles Proxy training - I've written a controller that can get the JSON data from the API - the problem is Charles Proxy can only intercept the data if I run the app locally - and in training others in class won't be able to do that, therefore I have the need to get the JSON object via the client and send it to the server.
Thank you very much in advance :-)
<script>
var xhr = new XMLHttpRequest();
var url = "https://cors-anywhere.herokuapp.com/https://www.511virginia.org/data/geojson/icons.rwis.geojson";
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
var jsonData = JSON.parse(xhr.responseText);
showWeather(jsonData);
}
};
xhr.open("GET", url, true);
xhr.send();
function showWeather(data) {
var output = "<ul>";
var i;
// validate obj has data
//for (var i in data.features) {
// output += "<li>" + data.features[i].id + "</li>";
//}
output += "</ul>";
document.getElementById("wxList").innerHTML = output;
}</script>
In the view / razor /.csthml page:
$.ajax({
url: '/Home/Wx/',
data: JSON.stringify(data),
type: 'POST',
traditional: true,
contentType: 'application/json',
success: function (data) {
$('#message').html("Success!");
}
});
And for the controller:
[HttpPost]
public IActionResult Wx([FromBody] RootObject data)
{
// Do some work here
return View();
}
That worked for me. Cheers

Why .getjson doesnt work but .ajax does?

I'm working on Free Code Camp's wiki viewer and trying to figure out the api call. I thought getjson and ajax were equivalent but maybe i'm doing something wrong.
So at first I used this getjson code:
$.getJSON('http://en.wikipedia.org/w/api.php?action=query&list=search&format=json&srsearch=' + search,
function(api){
console.log(api);
}, 'jsonp');
but it returned this error: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
Then I used ajax with the same url:
$.ajax({
url: 'http://en.wikipedia.org/w/api.php?action=query&list=search&format=json&srsearch=' + search,
dataType: 'jsonp',
success: getWiki //just console logs the api
});
and this seemed to return the api call. Can anyone explain why getjson didnt work but ajax did?
You're missing the required callback=? query parameter to force $.getJSON to perform a JSONP request
$.getJSON('http://en.wikipedia.org/w/api.php?callback=?', {
action: 'query',
list: 'search',
format: 'json',
srsearch: search
}, api => {
// response handler
})
See http://api.jquery.com/jquery.getjson/#jsonp
This is my solution also I left an alternative using only JavaScript
NOTE I added this &origin=* param in the url to make it work using this the original jQuery code.
var search = 'php';
var searchURL = 'https://en.wikipedia.org/w/api.php?action=query&format=json&generator=search&origin=*&gsrsearch=' + search;
// Using JSON
$.getJSON(searchURL, function(data){
var read = JSON.stringify(data);
console.log('Using jQuery: ' + read);
}, 'jsonp');
// Using JavaScript
var getJSON = function(url, callback) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.responseType = 'json';
xhr.onload = function() {
var status = xhr.status;
if (status == 200) {
callback(null, xhr.response);
} else {
callback(status);
}
};
xhr.send();
};
getJSON(searchURL, function(err, data) {
if (err != null) {
alert('Something went wrong: ' + err);
} else {
var read = JSON.stringify(data);
console.log('Using JavaScript: ', read);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

JavaScript equivalent for jQuery's $.ajax function

I have the following jQuery code:
dataString = 'test'; // array?
$.ajax({
type: "POST",
url: "tokenize.php",
data: {
data: dataString
},
cache: false,
success: function (data) {
returnedvalue = data;
console.log(data); //alert isn't for debugging
}
});
This jQuery code is working fine, but I want a plain JavaScript version of this code which I'm not able to figure out how to do. I made up this code with help from Stack Overflow only.
I have seen that this can be done using XMLHttpRequest:
var http = new XMLHttpRequest();
var url = "tokenize.php";
var params = "lorem=ipsum&name=binny"; // What will be done here in my case?
http.open("POST", url, true);
//Send the proper header information along with the request
http.setRequestHeader("Content-length", params.length);
http.setRequestHeader("Connection", "close");
// Call a function when the state changes.
http.onreadystatechange = function () {
if (http.readyState == 4 && http.status == 200) {
alert(http.responseText);
}
}
http.send(params);
The format of application/x-www-form-urlencoded data is:
key=value&key=value&key=value
Run each key and value through encodeURIComponent to deal with characters that have special meaning or that aren't allowed in the encoding.

AngularJS $http get data object displays status code instead of response

I have mulled over this for days and can still not figure out what I'm doing incorrectly so any ideas or even shots in the dark are appreciated. I am trying to display the response from a rest service to the user using the using the AngularJS $http get method, but when I print the data object to the console, I consistently receive the number 200 (I'm fairly certain it is giving me the status code). I hit success every time and, upon sending the request, the Chrome debug tool shows me the response with all the correct data. I just can't seem to get it to appear in a variable for display. Let me know if you think of anything! Thanks!
My javascript:
$scope.resendDestinations = [];
$scope.resendDestGet = function () {
var omtTypeCodeString = '';
for(var i = 0; i < $scope.mySelections.length; i++){
if(omtTypeCodeString == ''){
omtTypeCodeString = $scope.mySelections[i].orderHeader.omtOrderTypeCode;
}
else{
omtTypeCodeString = omtTypeCodeString + ',' + $scope.mySelections[i].orderHeader.omtOrderTypeCode;
}
}
$http({
method: 'GET',
url: restService.pom + //service url,
respondType: 'json',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Access-Control-Allow-Credentials': true
},
params: {
orderTypeCode: omtTypeCodeString,
transactionCode: 3
}
}).success(function (status, data, response, header) {
console.log("Success!");
//TODO see if this is being used... has to be
status = parseInt(status);
$scope.resendDestinations = data.multipleOrders;
if (status == 200 && $scope.resendDestinations.length == 0) {
$scope.bigAlert.title = 'Error',
$scope.bigAlert.header = 'Search Error';
$scope.bigAlert.content = 'Current search parameters do not match any results.';
$scope.showBigAlert();
}
else{
$scope.resendDestinations = data;
console.log("Data DestinationList here: ");
console.log($scope.resendDestinations);
console.log(data.multipleOrders);
console.log(data);
}
$scope.isSearching = false;
}).error(function (response, data, status, header) {
//Do error things
});
return $scope.resendDestinations;
};
And the service response:
[{"destCode":3,"destDescr":"Repository","attributes":null},{"destCode":4,"destDescr":"Pipeline","attributes":null},{"destCode":1,"destDescr":"Processor","attributes":null},{"destCode":2,"destDescr":"DEW","attributes":null},
{"destCode":7,"destDescr":"Management System","attributes":null},
{"destCode":8,"destDescr":"Source","attributes":null}]
You have the arguments in the wrong order. It should be: success(function(data, status, headers, config)
See the docs here (click).
Also, the .then() method is generally preferred. If you switch to that, you would access the data like this:
.then(function(response) {
var data = response.data;
var status = response.status;
//etc
});

how to Get the access token using oauth.js client library?

I'm able to get request token verifier from the library(http://oauth.googlecode.com/svn/code/javascript/), But got stuck in getting the access token.. can someone tell me where i'm doing it wrong?
function goForAccessRequest1(verifier){
var url2 = "http://www.google.com/accounts/OAuthGetAccessToken";
var accessor2 = {
token: OAuthToken,
//tokenSecret: OAuthTokenSecret,
signatureMethod : "HMAC-SHA1",
consumerKey : "1010722015153-i8tisqmaqch26b0muqvefbfp3h18m862.apps.googleusercontent.com",
//consumerSecret: "zZp8BsyfIzHJox1rBi8Lq3fm",
};
var message2 = {
action: url2,
method: "POST",
parameters: {
oauth_verifier : verifier,
//scope : "http://www.google.com/calendar/feeds",
}
};
OAuth.completeRequest(message2, accessor2);
var requestBody = OAuth.formEncode(message2.parameters);
//url2 = url2 + '?' + OAuth.formEncode(message2.parameters);
var AccessTokenRequest = new XMLHttpRequest();
AccessTokenRequest.open("POST", url2, true);
AccessTokenRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
AccessTokenRequest.setRequestHeader("Authorization", "OAuth");
AccessTokenRequest.send(requestBody);
AccessTokenRequest.onreadystatechange = function receiveAccessToken(){
if(AccessTokenRequest.readyState == 4){
console.log(AccessTokenRequest.responseText)
}
}
}
I'm getting the error like signature error whenever i try to send the parameters using "GET", and whenevr i send the parameters in POST body, getting the error as "parameters missing"

Categories

Resources