How do I use POST with ajax? - javascript

How do i use ajax to send POST requests to the server instead of GET?

Since I think that you're using the XHR object directly, you can make an 'postRequest' function easily:
We need the request url, the parameters to be send (params), and at least two callback functions success, which receives the responseText as the first argument when the request is completed successfully, and the error callback, which receives the XHR object and the status text:
function postRequest (url, params, success, error) {
var xhr = window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") :
new XMLHttpRequest();
xhr.open("POST", url, true);
xhr.onreadystatechange = function(){
if ( xhr.readyState == 4 ) {
if ( xhr.status == 200 ) {
success(xhr.responseText);
} else {
error(xhr, xhr.status);
}
}
};
xhr.send(params);
}

Sounds like you really should sit down and read about Ajax if you can not figure out how to move from a GET to a POST. That is Ajax 101 stuff:
https://developer.mozilla.org/En/AJAX

Put POST in as the first argument to xmlhttp.open() assuming you're using pure javascript:
xmlhttp.open('POST', 'example.php', true);

You can do it using jquery:
$.post("pageToPost.php", { firstParam: "Foo", secondParam: "Foo2" }, function(result){
alert("Response from pageToPost: " + result);
});

YUI connection manager would also be worth taking a look at as an alternative to jQuery. Using that you can make an ajax POST request as follows:
YAHOO.util.Connect.asyncRequest('POST', 'php/post.php', callback, "new=1&old=2");

Related

Call MVC Controller Method from TypeScript/JavaScript without jquery

Is it possible to call MVC Controller Method with Ajax call in Type Script/JavaScript without Jquery? if not How I can Call Controller Method from JavaScript/Type Script file?
Consider a method that is calling Controller method to sort and send a sort column to it:
This is function in ts file:
function SortData()
{
.... call Controller method and send sortCriteria (FullName) to it
}
and this is Controller method:
[Route("sortbycolumn")]
public ActionResult SortByColumn(string sortCriteria)
{
.... Do the sort retun back json result
}
Of course you can. In fact, jQuery is library based on javascript and it is not an independent language. Here is what you have to do:
function SortData(){
// Every ajax call is an XMLHttpRequest
var xhttp = new XMLHttpRequest();
// It means that your request is processed asynchronously.
// So we need to define the method that has to be run once the response is received,
xhttp.onreadystatechange = function() {
// status 200 means that your request has been processed successfully.
if (this.readyState == 4 && this.status == 200) {
// Change your html here
}
};
// Setting your request
xhttp.open("POST", "mycontroller/myaction", true);
// Send your request when everything is set.
xhttp.send();
}
If you need more to know, check out this link: https://www.w3schools.com/xml/ajax_intro.asp
I've included an example of a GET and a POST + submitting/receiving data using vanilla JS & AJAX below.
For further info, give this a read.
Good luck.
function SortData() {
var data;
//Post Example
var xhttp = new XMLHttpRequest();
xhttp.open("POST", "/Controller/Action", true);
xhttp.setRequestHeader("Content-Type", "application/json");
//There are two options for using xhttp.send(): Only keep the ONE that applies to you
//Option 1: Submit data to the server
xhttp.send(JSON.stringify(params));
//OR
//Option 2: Nothing to submit to the server
xhttp.send();
xhttp.onload = function(response) {
if(response.target.status == 200) {
data = JSON.parse(response.target.response);
}
};
//Get Example
var xhttp = new XMLHttpRequest();
xhttp.open("GET", "/Controller/Action", true);
xhttp.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
//There are two options for using xhttp.send(): Only keep the ONE that applies to you
//Option 1: Submit data to the server
xhttp.send(JSON.stringify(params));
//OR
//Option 2: Nothing to submit to the server
xhttp.send();
xhttp.onload = function(response) {
if(response.target.status == 200) {
data = JSON.parse(response.target.response);
}
};
}

Symfony 3 - Sending AJAX request as XmlHttpRequest() (javascript) does not pick up request as XmlHttpRequest in backend

I have an ExceptionListener implemented in Symfony3 (also works in Symfony2). The ExceptionListener identifies whether the request was normal HTTP or AJAX (XmlHttpRequest) and generates a response accordingly. When using jQuery .post() or .ajax(), the ExceptionListener returns $request->isXmlHttpRequest() as TRUE, but when using javascript var xhr = new XmlHTTPRequest(), the ExceptionListener returns $request->isXmlHttpRequest() as FALSE. I am using the latter in a small amount of instances where files need to be uploaded via AJAX (which cannot be done using .post() or .ajax().
I am looking for a solution (either frontend or backend) to resolve my ExceptionListener incorrectly picking this up as a normal HTTP request.
Frontend Code:
function saveUser()
{
var form = document.getElementById('userForm');
var formData = new FormData(form);
var xhr = new XMLHttpRequest();
xhr.open('POST', '{{url('saveUser')}}', true);
xhr.onreadystatechange = function (node)
{
if (xhr.readyState === 4)
{
if (xhr.status === 200)
{
var data = JSON.parse(xhr.responseText);
if (typeof(data.error) != 'undefined')
{
$('#processing').modal('hide');
$('#errorMsg').html(data.error);
$('#pageError').modal('show');
}
else
{
$('#successMsg').html('User Successfully Saved');
$('#processing').modal('hide');
$('#pageSuccess').modal('show');
$('#userModal').modal('hide');
updateTable();
}
}
else
{
console.log("Error", xhr.statusText);
}
}
};
$('#processing').modal('show');
xhr.send(formData);
return false;
}
ExceptionListener.php (partial)
# If AJAX request, do not show error page.
if ($request->isXmlHttpRequest()) # THIS RETURNS FALSE ON JS XmlHTTPRequest()
{
$response = new Response(json_encode(array('error' => 'An internal server error has occured. Our development team has been notified and will investigate this issue as a matter of priority.')));
}
else
{
$response = new Response($templating->render('Exceptions/error500.html.twig', array()));
}
When using vanilla ajax you need to pass the following header to your ajax request
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');

How can I convert this AJAX request function (raw Javascript) to use POST instead of GET?

I was looking for AJAX in pure JavaScript (without jQuery) for learning purposes and came across this video, along with the code (shown below) on how to make one. However, it's geared towards GET method and I'm not sure how to tweak it to accept additional parameters so that the function can be used for either POST or GET depending on my specified parameters. For example, the lines xhr.open('GET', url, true); and xhr.send(''); both are GET-specific (all other lines in the function are the same for both GET and POST methods)--I want to be able to be able to specify whether to use POST or GET as a parameter for function load for xhr.open and a string such as "username="+username+"&password="+password for function load for xhr.send('');
For example, the function below is for GET and is used like this load('emails.php', function(xhr) {...}. I want the function to be used like this: load('emails.php', 'POST', '"username="+username+"&password="+password' function(xhr) {...}` for POST andload('emails.php', 'GET', '', function(xhr) {...}`
The function for AJAX for GET:
function load(url, callback) {
var xhr;
if(typeof XMLHttpRequest !== 'undefined') xhr = new XMLHttpRequest();
else {
var versions = ["Microsoft.XmlHttp",
"MSXML2.XmlHttp",
"MSXML2.XmlHttp.3.0",
"MSXML2.XmlHttp.4.0",
"MSXML2.XmlHttp.5.0"];
for(var i = 0, len = versions.length; i < len; i++) {
try {
xhr = new ActiveXObject(versions[i]);
break;
}
catch(e){}
} // end for
}
xhr.onreadystatechange = function() {
if((xhr.readyState < 4) || xhr.status !== 200) return;
callback(xhr);
};
xhr.open('GET', url, true);
xhr.send('');
}
Right now the request body is set to null and ignored since you are making a GET request. You should just be able to put whatever you want sent in the body of the POST request inside of the send method:
xhr.open('POST', url, true);
xhr.send(JSON.stringify(someJsonHere));
Check out the documentation for the xhr.send method here:
Here is also a link to a more thorough guide on using XMLHttpRequests; at the bottom it has a section specific to sending data.

Normal redirect or preload

So on the net I've come across a several ways to preload / redirect a webpage.
Now's the question is this the proper way to handle a redirect with preload (Load the next page async while still showing the current page)
$.get("page.php", function (data) {
document.open();
document.write(data);
document.close();
window.history.pushState("Title", "Title", "/page.php");
$.cache = {};
}, "html");
Or should I better stay with a regular redirect?
window.location = "page.php";
The next page contains a fullscreen video and a soundtrack (audio)
Thanks.
You can use Ajax to load next page asynchronous.
Here is an example of a simple Ajax request using the GET method, written in JavaScript.
AJAX stands for Asynchronous JavaScript and XML, and for the XMLHttpRequest object to behave as AJAX, the async parameter of the open() method has to be set to true: xhr.open('get', 'send-ajax-data.php', true);
get-ajax-data.js:
// This is the client-side script.
// Initialize the Ajax request.
var xhr = new XMLHttpRequest();
xhr.open('get', 'send-ajax-data.php', true); // `true` makes the request asynchronous
// Track the state changes of the request.
xhr.onreadystatechange = function () {
var DONE = 4; // readyState 4 means the request is done.
var OK = 200; // status 200 is a successful return.
if (xhr.readyState === DONE) {
if (xhr.status === OK) {
alert(xhr.responseText); // 'This is the returned text.'
} else {
alert('Error: ' + xhr.status); // An error occurred during the request.
}
}
};
// Send the request to send-ajax-data.php
xhr.send(null);
And at the end you can use below codes to reload or redirect page data:
document.getElementById("myDiv").innerHTML = xhr.responseText;

javascript XMLHttpRequest requestXML is null

I'm trying to grab an xml document from a url and then parse it. I am able to open it fine on a browser, but it doesnt seem to work through my javascript. Can anyone help me?
function downloadUrl(url, callback) {
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4) {
request.onreadystatechange = function(){};
callback(request, request.status);
}
};
request.open('GET', "url", true);
request.send(null);
}
downloadUrl("http://jojo.theone.net/survey.xml", function(data) {
alert("Inside downloadURL"); // shows up
var xml = request.responseXML;
alert(xml); // Doesn't even show up.
alert(request.responseText); // Doesnt show up.
});
You are using data as the parameter name in your callback method, but calling the callback method as callback(request, request.status). The result is that the request object is now in the var called "data", and the request.status is not referenced at all.
Try
downloadUrl("http://jojo.theone.net/survey.xml", function(request, status) {
alert("Inside downloadURL");
var xml = request.responseXML;
alert(xml);
alert(request.responseText);
});
Try to use data value not the request object. Also it is better to use some framework like Mootools or jQuery to perform AJAX requests -- you'll get a more compatible and predictable interface.
Also note that request will fail if the url you're requesting has different server, port and protocol than the script that is making request.

Categories

Resources