JavaScript equivalent for jQuery's $.ajax function - javascript

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.

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

jQuery ajax drops integer on url

I am using this data...
// Pulled from the button that was hit
var method = document.activeElement.getAttribute('method').toUpperCase();
var url = document.activeElement.getAttribute('url');
Both buttons (methods) have the same url defined... '/user/1'
This is my jQuery AJAX call...
$.ajax({
type: method,
url: url', /* I even hard coded this to make sure what it had to use */
contentType: "application/json; charset=utf-8",
data: $(form).serializeArray(),
error: function (xhr, status) {
alert(xhr.status + ' : ' + url);
}
});
I have discovered that a PUT call truncates the number at the end of the given URL. But it has a trailing SLASH, it's OK.
If I run DELETE, it does what I expect
DELETE: /user/1
If I run PUT, I don;t get what I expect...
PUT: /user
notice the number "1" missing from that url?
I dug around and decided to try native JS... this is what I have...
var xhr = new XMLHttpRequest();
xhr.open(method, url);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onload = function() {
if (xhr.status === 200) {
var userInfo = JSON.parse(xhr.responseText);
}
};
xhr.send(JSON.stringify($(form).serializeArray()));
If I run DELETE, it does what I expect
DELETE: /user/1
If I run PUT...
PUT: /user/1
It works.
Yes, I know the URL has the "1" at the end for a PUT because I am sending the variable to the console before AND after the ajax call.
console.log(method + ': ' + url);
Besides, its the same var creation used for the native JS as used for the jQuery.
Now here's the kicker!
If the URL is defined as...
PUT: /user/walter
The name at the end stays.
Any ideas?

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>

AngularJS $http sending data with Ajax URL

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.

How to get Response Header location from jQuery Get?

So I am trying to get the location from a header response via jQuery get. I tried using getResponseHeader('Location') and getAllResponseHeaders() but they both seem to return null.
Here's my current code
$(document).ready(function(){
var geturl;
geturl = $.ajax({
type: "GET",
url: 'http://searchlight.cluen.com/E5/Login.aspx?URLKey=uzr7ncj8)',
});
var locationResponse = geturl.getResponseHeader('Location');
console.log(locationResponse);
});
The headers will be available when the asynchronous request returns, so you will need to read them in the success callback:
$.ajax({
type: "GET",
url: 'http://searchlight.cluen.com/E5/Login.aspx?URLKey=uzr7ncj8)',
success: function(data, status, xhr) {
console.log(xhr.getResponseHeader('Location'));
}
});
for some headers in jQuery Ajax you need to access XMLHttpRequest object
var xhr;
var _orgAjax = jQuery.ajaxSettings.xhr;
jQuery.ajaxSettings.xhr = function () {
xhr = _orgAjax();
return xhr;
};
$.ajax({
type: "GET",
url: 'http://example.com/redirect',
success: function(data) {
console.log(xhr.responseURL);
}
});
or using plain javascript
var xhr = new XMLHttpRequest();
xhr.open('GET', "http://example.com/redirect", true);
xhr.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
console.log(xhr.responseURL);
}
};
xhr.send();
jQuery abstracts the XMLHttpRequest object in a so-called "super set" that does not expose the responseURL field. It's in their docs where they talk about the "jQuery XMLHttpRequest (jqXHR) object"
For backward compatibility with XMLHttpRequest, a jqXHR object will expose the following properties and methods:
readyState
responseXML and/or responseText when the underlying request responded with xml and/or text, respectively
status
statusText
abort( [ statusText ] )
getAllResponseHeaders() as a string
getResponseHeader( name )
overrideMimeType( mimeType )
setRequestHeader( name, value ) which departs from the standard by replacing the old value with the new one rather than concatenating the new value to the old one
statusCode( callbacksByStatusCode )
No onreadystatechange mechanism is provided, however, since done, fail, always, and statusCode cover all conceivable requirements.
As you can see there is no way to get hold of the response URL because the jqXHR API does not expose it

Categories

Resources