Send javascript arrays via ajax without using jquery - javascript

i have a javascript array with values like "correct", "wrong".
I want to send this array to my php file using ajax. But im not familiar with how.
This is what i have tried so far..and i would like to do this without jquery.
var hold=[];
for(t = 0;t <= 10; t++){
answers_Arr = document.getElementsByName("question"+t);
for (k = 0; k < answers_Arr.length; k++){
if(answers_Arr[k].checked){
hold[t] = answers_Arr[k].value;
//document.getElementById("test"+t).innerHTML = "Value: "+ hold[t];
break;
}else{
hold[t] = "no";
continue;
}
}
}
var jsonString = JSON.stringify(hold);
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("test1").innerHTML= xmlhttp.responseText;
}
}
xmlhttp.open("GET","result.php?res="+hold[],true);
xmlhttp.send();
}

Here is an example of sending the json string with POST through AJAX:
var jsonString = JSON.stringify(hold);
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
//
}
xmlhttp.open("POST","result.php",true);
xmlhttp.setRequestHeader("Content-type", "application/json");
xmlhttp.send(jsonString);
Avoid sending json strings with GET method because if the request string gets too long, the browser will throw you an error.
Now in your php script you will have all the data in $_POST
Edit: Looks like on some versions of php, the requests that have other Content-type, like application/json, the $_POST has an empty value. To fix this you can do:
$_POST = json_decode(file_get_contents('php://input'));

replace this line
xmlhttp.open("GET","result.php?res="+hold[],true);
with
xmlhttp.open("GET","result.php?res="+jsonString,true);

Related

Trying to post to a .txt file fails but performing a get does work

My partner and I are trying to get a domain that I own, communicate with a ios app that is run on objective c to work via http. He is using the code that was provided by this link Sending an HTTP POST request on iOS.
He is able to do a GET to receive the data in my .txt page but when he performs a PUT to try and write to that file so that I can get that data it fails. We are both rather new to http so it is possible that we are missing something. A concern we have is that he doesn't have the privileges to write to this file. Any advice would help, thanks!
Here is the javascript I am using on my side. I added a header to my response to try and resolve the cors issue.
(function () {
window.onload = function () {
httpGetAsync("http://students.washington.edu/bharatis/distances.txt", processData)
//alert("hello inside onload");
document.getElementById("first").innerHTML = leader1;
document.getElementById("second").innerHTML = leader1;
document.getElementById("third").innerHTML = leader1;
//window.onbeforeunload = update;
}
function processData(responseText) {
//alert(responseText);
var txt = "";
var x = responseText.getElementsByTagName('Distance'); // Talk to alex about
for(i = 0; i < x.length; i++) {
txt += x[i].childNodes[0].nodeValue;
}
var result = parseDouble(txt);
alert(result);
}
function httpGetAsync(theUrl, callback) {
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
callback(xmlHttp.responseText);
}
xmlHttp.open("GET", theUrl, true); // true for asynchronous
xmlHttp.setRequestHeader("Access-Control-Allow-Origin", "*");
xmlHttp.send("response message");
}
})();

Passing value from JavaScript to PHP using AJAX

I'm trying to pass value to PHP code using AJAX.
Javascript
function countop() {
var href = window.location.href;
var href2 = href.split('/', 7);
xmlhttp.open('GET', '/count.php?val_for_count='+href2[6], true);
xmlhttp.send();
};
PHP
$x = $_GET['val_for_count'];
echo $x;
I don't get $x printed and I don't know why.
You have two problems.
First, xmlhttp is never declared, so your code throws a reference error.
var xmlhttp = new XMLHttpRequest();
Second, you never look at the HTTP response!
xmlhttp.addEventListener("load", function (event) {
document.body.appendChild(
document.createTextNode(
this.responseText
)
);
});
You have to create a new instance of XMLHttpRequest before using it:
var xmlhttp = new XMLHttpRequest();
And if you want to print the result of your request in your document, you can do it like this:
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.body.innerHTML = xmlhttp.responseText;
}
};

AJAX and JS, Cannot read JSON data?

I have the following AJAX code:
var ajax = new XMLHttpRequest();
axaj.open("POST", "index.php", true);
ajax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
ajax.onreadystatechange = function(){
if(x.readyState == 4 && x.status == 200){
var returnVal = ajax.responseText;
}
}
ajax.send("nextMax=-1");
And pairs with some PHP that ends with:
echo json_encode(array(
'next_id' => $nextID
));
exit();
This all works, as it is. If I print out returnVal inside the AJAX call, it prints out the correct array, with the correct value:
{"next_id":"935210077606657948"}
But I cannot access the id directly. I've tried
var nextID = returnVal.next_id;
and
var nextID = returnVal['next_id'];
and other variations, but all return undefined.
How do I get the array elements from within returnVal?
Thanks in advance.
Found a solution not 30 seconds after posting the question. But for those who are in the same place:
Switch
var returnVal = ajax.responseText;
to
var returnVal = JSON.parse(ajax.responseText);
and then the call works:
returnVal.next_id;

Unable to POST JSON object from Javascript to a Servlet via AJAX

I am trying to POST a JSON object to a servlet via AJAX. However, the object is null in the servlet. I am unable to figure out what's wrong with this code.
JAVASCRIPT
function submitValues(event, val1, val2)
{
var xmlHttpObj = new XMLHttpRequest();
if(window.XMLHttpRequest)
{
xmlHttpObj = new XMLHttpRequest();
}
else if(window.ActiveXObject)
{
xmlHttpObj = new ActiveXObject("Microsoft.XMLHttp");
}
var jsonObject = submitTheValues(event, val1, val2);
alert("json is:" +jsonObject);
var json = JSON.stringify(jsonObject);
alert("json after stringify:" +json);
xmlHttpObj.open("POST", "../myapp/myservlet", true);
xmlHttpObj.setRequestHeader("Content-type", "application/json");
xmlHttpObj.send(json);
}
SERVLET
String jsonObj = request.getParameter("json");
If you want to receive the data as a parameter you'll have to send it as application/x-www-form-urlencode.
xmlHttpObj.open("POST", "../myapp/myservlet", true);
xmlHttpObj.setRequestHeader("Content-type", "application/x-www-form-urlencode");
xmlHttpObj.send('json='+encodeURIComponent(json));

Why old red value persist in the browser, using XMLHttp request object?

I am reading a comma separated text file from the server, i get the valuse but when i chage the comma seprated variables in the file, it doesn't load the correct result int the browser
while browser persist the first time variable list only, whlile it works correct in IE, in firefox i am facig this proble.
How to sort it out
var arrUserTags = new Array();
var txt;
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "/TinyEditor/TextFile.txt", true);
xmlhttp.send();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
txt = xmlhttp.responseText;
arrUserTags = txt.split(",");
alert(arrUserTags.length);
parse();
}
}
// Add some values to the list box
function parse() {
for (i = 0; i < arrUserTags.length; i++) {
mlb.add(arrUserTags[i], arrUserTags[i]);
alert('hi');
}
}
You server is presumably sending caching instructions that tell browsers the URI for the text file won't change for a while.
Either configure the server to send no cache headers, or change the URI (e.g. by adding a rand() query string to it).

Categories

Resources