XMLHttpRequest no answer from server - javascript

I have tried to get i connection to an php file but i don't recive any reponse from server is anything wrong?,
function request(){
// Create our XMLHttpRequest object
var hr = new XMLHttpRequest();
// Create some variables we need to send to our PHP file
var url = "http://people.dsv.su.se/~pierre/courses/05_ass/ip3/3/3.7.1/example.php";
var number1 = document.getElementById("number1").value;
var number2 = document.getElementById("number2").value;
var vars = "?number1="+number1+"&number2="+number2
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;
document.getElementById("result").innerHTML = return_data;
}
}
// Send the data to PHP now... and wait for response to update the status div
hr.send(vars); // Actually execute the request
document.getElementById("result").innerHTML = "processing...";
}
I don't get any answer from the server were have i done wrong?
I have now tried to write it in jquery insteed but still no response from server
$(document).ready(function() {
// Skicka nummrerna vid klick på #calculate
$('#calculate').click(function() {
var url = "http://people.dsv.su.se/~pierre/courses/05_ass/ip3/3/3.7.1/example.php?";
var number1 = document.getElementById("number1").value;
var number2 = document.getElementById("number2").value;
var numbers = url + number1 + "&" + number2
if (window.XMLHttpRequest)
{// Kod för nya webbläsare
xmlhttp=new XMLHttpRequest();
}
else {//om det inte är en nyare webbläsare
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
// Skriv ut svaret från servern i result
document.getElementById("result").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET",numbers,true);
xmlhttp.send();
alert(numbers);
});
});

You're formatting your variables as if you're using them in a GET request, but then setting your request up for a POST.
[edit: to demonstrate comments]
Try changing these two lines.
hr.open("GET", url + vars, true);
hr.send();
[edit] Full original code with the changes
function request(){
// Create our XMLHttpRequest object
var hr = new XMLHttpRequest();
// Create some variables we need to send to our PHP file
var url = "http://people.dsv.su.se/~pierre/courses/05_ass/ip3/3/3.7.1/example.php";
var number1 =22;// document.getElementById("number1").value;
var number2 =22;// document.getElementById("number2").value;
var vars = "?number1="+number1+"&number2="+number2
hr.open("GET", url + vars, 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;
document.getElementById("result").innerHTML = return_data;
}
}
// Send the data to PHP now... and wait for response to update the status div
hr.send(); // Actually execute the request
document.getElementById("result").innerHTML = "processing...";
}

You need to send() your request with the data as the param. Something like:
params = "number1="+number1+"&number2="+number2;
hr.send(params);

Here is the complete code in jQuery format:
$(document).ready(function () {
$('#calculate').click(function () {
var url = "http://people.dsv.su.se/~pierre/courses/05_ass/ip3/3/3.7.1/example.php?number1=" + $("#number1").val() + "&number2=" + $("#number2").val();
$.ajax(url, {
complete: function (data, textStatus, jqXHR) {
//Put the code that handle the response here
$("#result").html(data.responseText);
}
});
});
});

Related

Joomla 4 Component Development & AJAX - not opening URL but itself

I am trying to develop a component in Joomla 4. I have a simple button that should fire of a script to update the database.
I can make the call to the JavaScript ok, but the JavaScript does not appear to open the request URL, if anything it opens the current URL or refreshes the page. The script works fine outside of Joomla but not inside.
I have tried both the following, and the same thing happens:
*function buttonLike()
{
var xhr = new XMLHttpRequest();
var parentEl = this.parentElement;
//var url = 'index.php?com_reflect&format=raw;
var url = 'liked.php';
console.log('Get Here OK' + parentEl.id);
xhr.open('GET', 'liked.php', true);
// Form data is sent appropriately as a POST request
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
xhr.onreadystatechange = function ()
{
if(xhr.readyState == 4 && xhr.status == 200)
{
var result = xhr.responseText;
console.log('Never Here Result: ' + result);
}
if(xhr.readyState == 4 && xhr.status == 0)
{
console.log('Always Here');
}
};
xhr.send("id=" + parentEl.id);
}*
OR
function buttonLike()
{
//var url = 'index.php?com_reflect&format=raw;
var url = 'liked.php';
var request = new Ajax(url, {
method: 'post',
update: some_div,
data: options,
onComplete: function (){
$('some_field').setHTML('I am finished!');
}
}).request();
Been going round in circles on this one, any help would be appreciated.

JS: HTML is not dynamically changing

I am building an web that allows user to like a post when they click a button. CreateLike function calls API and creates a like object however, I would like to have the number of likes updated right away without reloading. I built another API that returns the number of likes for a post. Function LikeCount should put the number of likes into the p tag. It works initially when I load the page however, the value does not change when I click the button even though I can see that the API is called. (After reloading the page the number changes as expected) What am I doing wrong?
I have this HTML:
<p class="like-count" id={{post.id}}></p>
<script>LikeCount({{post.id}});</script>
<button type="button" class="btn-like" onclick="CreateLike({{user.id}},{{post.id}})"></button>
with JS functions:
function CreateLike (userid,postid) {
xhr = new XMLHttpRequest();
var url = "{% url 'likes' %}";
var csrftoken = getCookie('csrftoken')
xhr.open("POST", url, true);
xhr.setRequestHeader("X-CSRFToken",'{{ csrf_token }}')
xhr.setRequestHeader("Content-type", "application/json");
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
var json = JSON.parse(xhr.responseText);
console.log(json.email + ", " + json.name)
}
}
var data = JSON.stringify({csrfmiddlewaretoken:csrftoken,"user":userid,"post":postid});
xhr.send(data);
LikeCount(postid);
}
function LikeCount(postid) {
var xmlhttp = new XMLHttpRequest();
var url = "{% url 'likecount' id=112233 %}".replace("112233", postid);
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myArr = JSON.parse(this.responseText);
myFunction(myArr);
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
function myFunction(arr) {
var out = arr.like_count;
document.getElementById(postid).innerHTML = out;
}
}
Like count API looks like this:
{
"like_count": 1
}
if(xhr.readyState === XMLHttpRequest.DONE) {
var status = xhr.status;
if (status === 0 || (status >= 200 && status < 400)) {
LikeCount(); //Put your get like count here
} else {
// Handle Errors
}
}
Call LikeCount only after receiving the response of your POST request. Right now you're immediately sending a GET request without ensuring if the previous POST request got completed.
Added
xhr.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 201) {
var myArr = JSON.parse(this.responseText);
LikeCount(myArr.post);
}
};
before
xhr.send(data);
and it fixed the issue.

console gives an error when button is clicked "function is not defined at HTMLInputElement.onclick"

<script src="jquery-3.2.1.min.js">
function ajax_post(){
loadScript('javascript/jquery-3.2.1.min.js');
// Create our XMLHttpRequest object
alert("button clicked");
// code for modern browsers
// Create some variables we need to send to our PHP file
var hr = new XMLHttpRequest();
var url = "comments.php";
var bid='<?php echo $b; ?>';
var userid='<?php echo $userid; ?>';
var cm = document.getElementById("latest_comment").value;
var vars = "your_comment="+cm+"&bookid="+bid+"&uid="+userid;
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;
document.getElementById("comment").innerHTML = return_data;
}
}
// Send the data to PHP now... and wait for response to update the status div
hr.send(vars); // Actually execute the request
document.getElementById("comment").innerHTML = "processing...";
}
</script>
this is javascript function which should run when i click the csubmit button, but when i click it the console gives an error written in the title. this function has to take the data written in the input tag, go to the comments.php page and insert it in database and display the comments in the comment div
I HAVE BEEN STUCK ON THIS ERROR FOR A VERY LONG TIME,BUT NOT ABLE TO FIND WHERE IS THE ERROR
<input type="button" id="csubmit" value="SUBMIT" onclick="ajax_post();">
Put ajax_post function in other script tag, you can not put JS code in script tag which already have src
<script src="jquery-3.2.1.min.js"></script>
<script>
function ajax_post() {
loadScript('javascript/jquery-3.2.1.min.js');
// Create our XMLHttpRequest object
alert("button clicked");
// code for modern browsers
// Create some variables we need to send to our PHP file
var hr = new XMLHttpRequest();
var url = "comments.php";
var bid = '<?php echo $b; ?>';
var userid = '<?php echo $userid; ?>';
var cm = document.getElementById("latest_comment").value;
var vars = "your_comment=" + cm + "&bookid=" + bid + "&uid=" + userid;
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;
document.getElementById("comment").innerHTML = return_data;
}
}
// Send the data to PHP now... and wait for response to update the status div
hr.send(vars); // Actually execute the request
document.getElementById("comment").innerHTML = "processing...";
}
</script>
This is the problem with your code: Your script is inside a <script> tag with a src attribute. When a src attribute is present, the content inside the <script> tag is completely ignored.
This should work:
<script src="jquery-3.2.1.min.js">
function ajax_post(){
loadScript('javascript/jquery-3.2.1.min.js');
// Create our XMLHttpRequest object
alert("button clicked");
// code for modern browsers
// Create some variables we need to send to our PHP file
var hr = new XMLHttpRequest();
var url = "comments.php";
var bid='<?php echo $b; ?>';
var userid='<?php echo $userid; ?>';
var cm = document.getElementById("latest_comment").value;
var vars = "your_comment="+cm+"&bookid="+bid+"&uid="+userid;
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;
document.getElementById("comment").innerHTML = return_data;
}
}
// Send the data to PHP now... and wait for response to update the status div
hr.send(vars); // Actually execute the request
document.getElementById("comment").innerHTML = "processing...";
}
</script>

how to create radio buttons by JS.

i have some problrm creating the radio buttons dynamically. in my problem i am requesting data from server in json formate than i check if it contains options i have to create the radio buttons otherwise simply creates the txt area of field to submit the answer. than again i parse it in json formate and send to the server and if my question is write i get new url for next question and so on...
my question is how can i create the radio buttons and read the data from it and than parse that data like {"answer": "something"}.my code is bellow:
enter code herefunction loadDoc(url) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
console.log(this.responseText);
var data = JSON.parse(this.responseText);
document.getElementById("my_test").innerHTML = data.question;
// Send the answer to next URL
if(data.alternatives !== null){
createRadioElement(div,);
}
var answerJSON = JSON.stringify({"answer":"2"});
sendAnswer(data.nextURL, answerJSON)
}
};
xhttp.open("GET", url, true);
xhttp.send();
}
function sendAnswer(url, data) {
xhr = new XMLHttpRequest();
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-type", "application/json");
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
var data = JSON.parse(this.responseText);
console.log(this.responseText);
loadDoc(data.nextURL);
}
}
// var data = JSON.stringify({"email":"hey#mail.com","password":"101010"});
xhr.send(data);
}
function createRadioElement(name, checked) {
var radioHtml = '<input type = "radio" name="' + name + '"';
if ( checked ) {
radioHtml += ' checked="checked"';
}
radioHtml += '/>';
var radioFragment = document.createElement('div');
radioFragment.innerHTML = radioHtml;
return radioFragment.firstChild;
}
I'm only guessing since you have some things in your posted code that won't even run, but createRadioElement returns a detached node which you never actually inject into your document.
E.g.,
document.body.appendChild(createRadioElement());

Convert ajax function to jquery

I would like to convert this ajax function to a jquery function but im not sure how it would be done in jquery
function ajax_posta() {
// Create our XMLHttpRequest object
var hr = new XMLHttpRequest();
// Create some variables we need to send to our PHP file
var url = "javas.php";
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;
document.getElementById('status').innerHTML = return_data;
}
}
// Send the data to PHP now... and wait for response to update the status div
hr.send("num=" + (--num)); // Actually execute the request
document.getElementById('status').innerHTML = "<img src = 'loading.gif' height = '30' width = '30'>";
}
$(document).ready(function()
{
$('.eventer.button').click(function () {
var self = this;
$.post('javas.php', function (data) {
$(self).parent('div').find('.status').html(data);
})
});
}
)
;
</script>
You're pretty much there
$.ajax('javas.php', {
success: function(response) {
$(".status").html(response);
},
data: "num=" + (--num)
});
If these are the only two pieces of data you need to send to your request, you could just use $.post, but the advantage here is that if you ever want to specify more options, like contentType, all you'd have to do is add it to the existing options object.

Categories

Resources