Cant send Data in AJAX call by using post method - javascript

here is my code, its pretty simple and works perfect:
var r = new XMLHttpRequest();
var name='KillerSeba';
r.open("GET","../Serve/servepage.php?name="+name,true);
r.onreadystatechange = function () {
if (r.readyState != 4 || r.status != 200) return;
alert("Success: " + r.responseText);
};
r.send();
This code just sends alert "Success: KillerSeba" when page loads. And my php file which answers request looks kinda of:
<?php
$s=$_REQUEST['name'];
echo $s;
?>
Then i want to use POST method instead of GET one. In order to do this, I change "GET" to "POST", changing url to php file, then add name variable to send() function, so my javascript code look like this:
var r = new XMLHttpRequest();
var name='KillerSeba';
r.open("POST","../Serve/servepage.php",true);
r.onreadystatechange = function () {
if (r.readyState != 4 || r.status != 200) return;
alert("Success: " + r.responseText);
};
r.send(name);
But now script doesnt send any Data to php file, cuz i getting only "Success:" alert. KillerSeba dissipates to somewhere. I tried to use 'name' and "name" instead of name inside of send() function, i tried to replace $_REQUEST by $_POST, but it still doesnt help. So my Queistion is: How to send Data in AJAX Request using POST method? How does this send() function work?
P.S. I prefer to use Vanilla JS Framework only.

As you're sending the name as string without any paramerter name that's why it is not working for you with POST method but when you're sending with GET you're concatenating that name with the url. Now, you've to pass the params the same way you sent with GET method. Just try like this way, I just wrap the name to a variable called params that contains the params = 'name='+name; so you've to send it with your r.send(params). See the examples here both for GET and POST
var r = new XMLHttpRequest();
var name='KillerSeba';
r.open("POST","../Serve/servepage.php",true);
//Send the proper header information along with the request
r.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
r.onreadystatechange = function () {
if (r.readyState != 4 || r.status != 200) return;
alert("Success: " + r.responseText);
};
params = 'name='+name;
r.send(params);

You are sending name but without any variable name (it's considered as variable name without any value).
Change your r.send(name); to r.send('name=' + name);.
For more information, take a look at the MDN Web Docs
EDIT: Thanks for your hint, of course you need to set a proper header before sending the request:
r.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

Related

I can't get a response from the server

I followed some guides on how to send json objects to the server(written using node.js) and it doesn't work, I have no idea what is wrong. I know that my server works fine since I tested it on postman so it's my js code that's the problem, all the tutorials I see follow a similar XMLHttpRequest format.
this is my code
var ing = new Ingredient(name, date, qty, rp);
var url = "http://localhost:8081/addIngredient";
var xhr = new XMLHttpRequest();
xhr.open("POST", url, true);
//Send the proper header information along with the request
// application/json is sending json format data
xhr.setRequestHeader("Content-type", "application/json");
// Create a state change callback
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
// Print received data from server
result.innerHTML = this.responseText;
}
};
// Converting JSON data to string
var data = JSON.stringify(ing);
document.write(data);
// Sending data with the request
xhr.send(data);
I used document.write to check where the code stops working but everything passes (since the document.write prints something), I suspect that there is something wrong/missing from xhr.send(data) but I can't tell what. Finally, nothing gets printed from the callback.
It's better to use onload instead of onreadystatechange
xhr.onload = function() {
if (xhr.status == 200) {
console.log(`Response length = ${xhr.response.length}`);
// store xhr.response here somewhere
}
};

JSON XMLHttpRequest POST/PUT to Cherrypy application - getting no data

I want to create a Singlepage Application following REST principles. I have managed to make both GET and DELETE work, but i also need to PUT or POST data.
After failing for some time, i looked around and found some sample code here https://gist.github.com/EtienneR/2f3ab345df502bd3d13e
which, first of all, taught me that setting a request header may be helpful. With that done, however, and following the exact example, I'm still getting "None" for the field i expect to receive data on.
I may be missing something absolutely basic, and looking around some more i just can't find out what it is.
on the javascript side i've got:
update_px (path_spl, success_ppl, fail_ppl, formdata) {
this.success_p = success_ppl;
this.fail_p = fail_ppl;
var data = {};
data.firstname = "John";
data.lastname = "Snow";
var json = JSON.stringify(data);
var xhr = new XMLHttpRequest();
xhr.open("POST", path_spl, true);
xhr.setRequestHeader('Content-type','application/json; charset=utf-8');
xhr.onload = function () {
var users = JSON.parse(xhr.responseText);
if (xhr.readyState == 4 && xhr.status == "201") {
console.table(users);
} else {
console.error(users);
}
}
xhr.send(json);
}
and on the python side of things:
def POST(self, path_spl="NoPathError", id = None, data_opl=None):
print("POST called with path_spl " + path_spl )
if(id != None) :
print(" and id " + id)
print (data_opl)
#process data
return ' '
The method is exposed; output shows I'm receiving the correct path and ID, but data is just None even after swapping in this sample code i found.
Where am i going wrong?
I have found a way to get it to work.
1) ** was missing on the expected data - that alone didn't help, now i was getting an empty dict instead of None
2) i replaced the content type; the header is now
xhr.setRequestHeader('Content-type','application/x-www-form-urlencoded');
with that, i am receiving:
{'{"firstname":"John","lastname":"Snow"}': ''}
Which actually leads me into another question - how did {"firstname":"John","lastname":Snow"} become a key with an empty value during json-ification? But anyway. That's for another day to find out; i can work with what i'm getting now.

$_GET variable not showing up in string and boolean operations

I have a javascript file that uses POST to send some data to a PHP file, as such:
var additional = "Feb2015";
xmlhttp.open("POST", "database_comm_general.php?query=" + additional, true);
In the PHP file, I use $_GET to get that 'additional' variable:
$query = $_GET['query'];
Now, if I want to use it to get some data from MySql, I use this for my query, but when I echo it, it just shows empty quotation marks, where 'Feb2015' should be:
$sql_query = "SELECT * FROM '" . $query . "'";
Output: "SELECT * FROM ''"
Even more odd, if I use json_encode and print it on the javascript side, it shows up just fine.
Similarly, if I see if the variable equals 'Feb2015', with json_encode it will return true, but on the page it will output false at the same time.
Any ideas?
Edit:
This is my javascript code:
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var content = JSON.parse(this.responseText);
window.alert(content);}}
xmlhttp.open("POST", "database_comm_general.php?query=" + additional, true);
xmlhttp.send();
Alright, I haven't been able to fix this exact issue, but I got my code working through other means:
First, I use jquery instead of javascript for communicating with PHP:
text = "Feb2015";
$.ajax(
{ url : "database_comm_general.php?" + text, success: function(data){
var return_data = JSON.parse(data);
populateTableList(return_data);
}});
Second, in the PHP file, I don't use $_GET, I get the data from the link address:
$link = $_SERVER[REQUEST_URI];
$index = strpos($link, "?");
$sub_string = substr($link, $index+1, 7);
$sub_string = $sub_string;
Third, I added a single line of code in the MySQL code that resolved the issues with some of the arrays which couldn't be encoded:
mysqli_set_charset($conn, 'utf8');
All in all, I feel I've been to hell and back, but I hope this helps someone in the future.

How do i correctly format parameters passed server-side using javascript?

I cannot figure out how to get the following code working in my little demo ASP.NET application, and am hoping someone here can help.
Here is the javascript:
function checkUserName() {
var request = createRequest();
if (request == null) {
alert("Unable to create request.");
} else {
var theName = document.getElementById("username").value;
var userName = escape(theName);
var url = "Default.aspx/CheckName";
request.onreadystatechange = createStateChangeCallback(request);
request.open("GET", url, true);
request.setRequestHeader("Content-Type", "application/json");
//none of my attempts to set the 'values' parameter work
var values = //JSON.stringify({userName:"userName"}); //"{userName:'temp name'}"; //JSON.stringify({ "userName":userName });
request.send(values);
}
}
Here is the method in my *.aspx.cs class:
[WebMethod]
[ScriptMethod(UseHttpGet=true)]
public static string CheckName(string userName)
{
string s = "userName";
return s + " modified backstage";
}
When this code runs I receive this exception:
---------------------------
Message from webpage
---------------------------
{"Message":"Invalid web service call, missing value for parameter: \u0027userName\u0027.","StackTrace":" at System.Web.Script.Services.WebServiceMethodData.CallMethod(Object target, IDictionary`2 parameters)\r\n at System.Web.Script.Services.WebServiceMethodData.CallMethodFromRawParams(Object target, IDictionary`2 parameters)\r\n at System.Web.Script.Services.RestHandler.InvokeMethod(HttpContext context, WebServiceMethodData methodData, IDictionary`2 rawParams)\r\n at System.Web.Script.Services.RestHandler.ExecuteWebServiceCall(HttpContext context, WebServiceMethodData methodData)","ExceptionType":"System.InvalidOperationException"}
---------------------------
OK
---------------------------
I started searching here, then went on to several threads on SO, trying quite a few combinations of quotation marks and key-value pairs, but nothing I've tried has worked.
When I remove the parameter from the C# method and request.send(), I get a response in my JS callback that I can work with. But as soon as I try to do something with parameters, I get the above exception. I'd like to know how to do this without using jQuery, if possible.
Thanks in advance.
FINAL VERSION
Using Alexei's advice, I ended up with the following, which works. The URL was missing the apostrophes on either end of the parameter value; this was keeping the call from going through.
function checkUserName() {
var request = createRequest();
if (request == null) {
alert("Unable to create request.");
} else {
var theName = document.getElementById("username").value;
var userName = encodeURIComponent(theName);
var url = "Default.aspx/CheckName?name='" + theName + "'";
request.onreadystatechange = createStateChangeCallback(request);
request.open("GET", url, true);
request.setRequestHeader("Content-Type", "application/json");
request.send();
}
}
request.send(values);
This won't work with a "GET". Try
request.open("POST", url, true);
http://www.w3schools.com/ajax/ajax_xmlhttprequest_send.asp
You need to:
decide whether you want GET or POST. For GET request you need all parameters to be in Url (and body to be empty), for POST you can use both. As of current code you are expecting GET, but sending POST.
properly add query parameter - name and encoded value. encodeUriComponent is JavaScript function of choice, see Build URL from Form Fields with Javascript or jquery for details
if using POST you need to properly encode parameters there too as well specify correct "content-type" header.
if sending JSON you need to decode JSON server side.
Alternatively you can use hidden form to perform POST/GET as covered in JavaScript post request like a form submit
Side note: jQuery.ajax does most of that for you and good source to look through if you want to do all yourself.
Like Alan said, use the POST method. Or pass your arguments in your URL before opening it, e.g.
var url = "Default.aspx/CheckName?userName=" + values;
EDIT : no, it's probably a bad idea since you want to send JSON, forget what I said.
If you need to go for POST, then you need to send it like this.
var values = JSON.stringify({"'userName':'"+ userName+ "'"});
And you have to change HttpGet to HttpPost
Given that your server side method asks for GET, you need:
request.open("GET", url + "?username=" + userName, true);
request.send();
The works for me:
function checkUserName() {
var request = new XMLHttpRequest();
if (request == null) {
alert("Unable to create request.");
} else {
var userName = "Shaun Luttin";
var url = '#Url.RouteUrl(new{ action="CheckName", controller="Home"})';
request.onreadystatechange = function() {
if (request.readyState == XMLHttpRequest.DONE ) {
if(request.status == 200){
document.getElementById("myDiv").innerHTML = request.responseText;
}
else if(request.status == 400) {
alert('There was an error 400')
}
else {
alert('something else other than 200 was returned')
}
}
}
request.open("GET", url + "?username=" + userName, true);
request.send();
}
}
With this on the server side:
[HttpGet]
public string CheckName(string userName)
{
return userName + " modified backstage";
}

How to pass all the params as a single object while making ajax call

I have the below js code:
xmlhttp = GetXmlHttpObject();
if (xmlhttp != null) {
var url = "/support/residential/outage/serviceOutage?cbrnum=" + cbrnum + "&btn=" + btn + "&outagetkt=" + outagetkt;
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("thankyoucontent").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("POST", url, true);
xmlhttp.send(null);
}
This calls a servlet by passing certain params in query string. Now my question is , can we bind all the params into a single object , send that object alone in query string and use the object in the servlet to retrieve the param values? Is it possible?
Yes, you can send the data as JSON to the server:
var data = {cbrnum: cbrnum, btn: btn};
var url = "...?data=" + encodeURIComponent(JSON.stringify(data));
Then on the server side, retrieve the value of data and parse the JSON into native data types (Converting JSON to Java).
Note though that browsers often impose a length limit on the URL. If you have a lot of data, do a POST request instead.

Categories

Resources