Passing value from JavaScript to PHP using AJAX - javascript

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;
}
};

Related

Why can't separate the function for xmlHttp.onreadystatechange?

The below js file test.js` works fine in my html.
function sendData()
{
var formData = new FormData( document.querySelector("form") );
var xmlHttp = new XMLHttpRequest();
xmlHttp.open("post", "test.php",true);
xmlHttp.send(formData);
xmlHttp.onreadystatechange = function(){
if (xmlHttp.readyState == 4 && xmlHttp.status == 200){
alert(xmlHttp.responseText);
}
}
}
ob = document.getElementById("submit");
ob.addEventListener("click",sendData);
Now i want to separate them
if (xmlHttp.readyState == 4 && xmlHttp.status == 200){
alert(xmlHttp.responseText);
in a single function.
I rewrite the test1.js as test2.js.
var xmlHttp;
function ready(){
if (xmlHttp.readyState == 4 && xmlHttp.status == 200){
alert(xmlHttp.responseText);
}
}
function sendData()
{
var formData = new FormData( document.querySelector("form") );
var xmlHttp = new XMLHttpRequest();
xmlHttp.open("post", "test.php",true);
xmlHttp.send(formData);
xmlHttp.onreadystatechange = ready;
}
ob = document.getElementById("submit");
ob.addEventListener("click",sendData);
The test2.js encounter error info:
test2.js:4 Uncaught TypeError: Cannot read property 'readyState' of undefined
at XMLHttpRequest.ready (test2.js:4)
Another issue :what is the right order for the following statements?
I have seen some material write them as below :
xmlHttp.open("post", "test.php",true);
xmlHttp.send(formData);
xmlHttp.onreadystatechange = function(){ }
Other material also seen:
xmlHttp.onreadystatechange = function(){ }
xmlHttp.open("post", "test.php",true);
xmlHttp.send(formData);
And other order in webpage xmlHttp statements order
xmlhttp.open("POST", "Demo", true);
xmlhttp.onreadystatechange=myCallBack;
xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=UTF-8");
xmlhttp.send("FirstName=Nat&LastName=Dunn");
In sendData you have:
var xmlHttp = new XMLHttpRequest();
Your only mistake is including the var here - just do this instead:
xmlHttp = new XMLHttpRequest();
The reason this matters is that the var is declaring a new local variable of the same name, which is then getting assigned to - so ready doesn't get access to it. It accesses the global xmlHttp variable, which is never assigned to. By removing the var as shown above, you ensure that the global variable is assigned to - and this should work. (Although of course it's not best practice to use globals.)

Reading XML returned from AJAX

I have defined this XML file
<?xml version="1.0" encoding="UTF-8"?>
<root>
<town>
<area>20000</area>
<population>10000</population>
</town>
</root>
with AJAX I load this and I try to parse it.
<script>
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function(){
if(this.readyState == 4 && this.status == 200){
myFunctionParsing(this);
}};
xhttp.open("GET", "towns.xml", false);
xhttp.send();
function myFunctionParsing(xml)
{
var xmlDoc = xml.responseXML;
var nodes = xmlDoc.getElementsByTagName("town");
var n = nodes[0].childNodes[0];
console.log(n.tagName);
var aDiv = document.getElementById("area");
aDiv.innerHTML = n.nodeValue;
}
With that script I want to write in div value of node "area" in some div with name "area".
Why can not I write this value? Why n.tagName is undefined?
A couple things:
I am using MDN's XMLHttpRequest example, which shows how to override the mime type to force it to parse the response as XML. That way you don't have to do responseXML.
querySelector is great! Use it. No need for getElementsByTagName.
function parseXML(xml) {
var area = xml.querySelector('town area');
console.log(area.textContent); // => 20000
}
var url = 'https://gist.githubusercontent.com/gabrielflorit/c618f26ac367fbaf91846efe73913c23/raw/b3c9c3e8d0f1dc747006103442b3b19bf7c91d9c/town.xml';
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
// If specified, responseType must be empty string or "document"
xhr.responseType = 'document';
// overrideMimeType() can be used to force the response to be parsed as XML
xhr.overrideMimeType('text/xml');
xhr.onload = function () {
if (xhr.readyState === xhr.DONE) {
if (xhr.status === 200) {
parseXML(xhr.response);
}
}
};
xhr.send(null);

Send javascript arrays via ajax without using jquery

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);

How to pass a JSON object using form data to a rest service using JS

I have a rest webservice which can accept a string. I want to pass a json object as a string to this service. I have to use a HTML page with some textfields and has to pass the form data to the service. can any one help??
Thankyou
you can try this
function callWebService{
var field= document.getElementById('field').value;
//use jquery to convert to json object
//see comment for more info on this
var ws = 'http://localhost:8080/WebServicePath/';
var url = ws + field;
var xmlhttp = null;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
alert("Success");
}
else {
alert("Failure");
}
};
xmlhttp.open('GET', url, true);
xmlhttp.send(null);
}

IE8 is breaking my AJAX... FF is fine

Feeling very proud of myself after creating a form with an AJAX submit, I test it in IE8 and get "Message: 'quantity' is undefined". I've read that it could be something to do with the fact that earlier versions of IE used ActiveX for AJAX requests, but I'm very new to JS and have no real understanding of the problem, let alone the ability to implement a fix.
Here's my code:
var time_variable;
function getXMLObject() //XML OBJECT
{
var xmlHttp = false;
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP") // For Old Microsoft Browsers
}
catch (e) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP") // For Microsoft IE 6.0+
}
catch (e2) {
xmlHttp = false // No Browser accepts the XMLHTTP Object then false
}
}
if (!xmlHttp && typeof XMLHttpRequest != 'undefined') {
xmlHttp = new XMLHttpRequest(); //For Mozilla, Opera Browsers
}
return xmlHttp; // Mandatory Statement returning the ajax object created
}
var xmlhttp = new getXMLObject(); //xmlhttp holds the ajax object
function ajaxFunction() {
var getdate = new Date(); //Used to prevent caching during ajax call
if(xmlhttp) {
var txtname = document.getElementById("txtname");
xmlhttp.open("POST","slots.php",true); //calling testing.php using POST method
xmlhttp.onreadystatechange = handleServerResponse;
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlhttp.send("quantity=" + quantity.value + "&price=" + price.value + "&slot=" + slot.value + "&store=" + store.value); //Posting txtname to PHP File
}
}
function handleServerResponse() {
if (xmlhttp.readyState == 4) {
if(xmlhttp.status == 200) {
document.getElementById("message").innerHTML=xmlhttp.responseText; //Update the HTML Form element
}
else {
alert("Error during AJAX call. Please try again");
}
}
}
From your last comment on your question, I suspect you are not defining 'quantity' anywhere and assuming that it will reference the form field. Try this:
if(xmlhttp) {
var txtname = document.getElementById("txtname");
var quantity = document.getElementById("quantity");
var price = document.getElementById("price");
var store = document.getElementById("store");
xmlhttp.open("POST","slots.php",true); //calling testing.php using POST method
xmlhttp.onreadystatechange = handleServerResponse;
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlhttp.send("quantity=" + quantity.value + "&price=" + price.value + "&slot=" + slot.value + "&store=" + store.value); //Posting txtname to PHP File
}
If quantity is a form field you need to get it using getElementById before using it just like you did with txtname:
var quantity = document.getElementById("quantity");
You cant use it directly from the form.

Categories

Resources