JQuery Ajax call working but not native JavaScript - javascript

I have two AJAX calls, one in native JavaScript and another with JQuery, which call a PHP Script. The JQuery one is working, but the JavaScript one not. Here goes the code:
JQuery:
$.ajax({
url: "/Tests/index.php",
method: "POST",
data: {'Id': "2"}
});
Native JavaScript:
var Data = {Id: "2"};
XHR = new XMLHttpRequest();
XHR.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
console.log(XHR.responseText);
}
}
XHR.open("POST", "/Tests/index.php", true);
XHR.setRequestHeader("Content-Type", "application/json");
XHR.send(JSON.stringify(Data));
PHP Script:
echo var_dump($_POST);
The one with JQuery returns 2, but the JavaScript one, doesn't return anything. All the data is seen through the console of the web browser.

Try this code:
var Data = {"Id": "2"};
var XHR = new XMLHttpRequest(); // declared XHR var
XHR.open("POST", "/Tests/index.php", true);
XHR.setRequestHeader("Content-Type", "application/json");
XHR.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
console.log(XHR.responseText);
}
}
XHR.send(Data); // sending data without converting to string
Reference: https://www.w3schools.com/xml/ajax_xmlhttprequest_send.asp

Related

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.

After authenticating via POST, I need to do a GET using Ajax

I'm attempting to create a dashboard that logs into an API then refreshes certain data elements that is fully automated. I can login and authenticate but after googling unsure how to 'chain' the GET request after the 'POST'
I've tried watching a few youtube tutorials and creating functions, attaching them to buttons and divs but I just can't get the data to display. The first batch of code completes and logs in OK, but then sits there and times out. I tried just adding a second open and making the login synchronous but it failed
<script type="text/javascript">
const xhr = new XMLHttpRequest();
var data = 'username=user&password=password';
xhr.onreadystatechange = function()
{
if (xhr.readyState == "4")
{
if (xhr.status == "200")
{
console.log(xhr.responseText);
}
if (xhr.status = "404")
{
console.log("FnF");
}
}
}
xhr.open('post','https://apiServer:8443/api/login', true)
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded")
xhr.setRequestHeader("Accept", "application/xml")
//xhr.open('get', 'https://apiServer:8443/api/resource/items', true);
xhr.send();
I'm expecting the login to be done behind the scenes and not visible, and just have the GET request show data in a div (I'll try and tidy up the xml response when I get the data working first).
In your code you never use your data variable :
const xhr = new XMLHttpRequest();
var data = 'username=user&password=password';
xhr.onreadystatechange = function()
{
if (xhr.readyState == "4")
{
if (xhr.status == "200")
{
console.log(xhr.responseText);
}
if (xhr.status = "404")
{
console.log("FnF");
}
}
}
xhr.open('post','https://apiServer:8443/api/login', true)
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded")
xhr.setRequestHeader("Accept", "application/xml")
//xhr.open('get', 'https://apiServer:8443/api/resource/items', true);
xhr.send(data); // <====== HERE

Not able to echo POST paramenters sent in ajax, inside PHP

I am sending two parameters inside the send method to index.php. But the PHP returns an error "Undefined index". echo $_POST['fname'];
submit.addEventListener("click", function(e){
e.preventDefault();
var xhr = new XMLHttpRequest();
xhr.open("POST", "index.php", true);
xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
xhr.onreadystatechange = function () {
if(xhr.readyState == 4 && xhr.status == 200) {
var result = xhr.responseText;
console.log(result);
}
}
xhr.send("fname=Henry&lname=Ford");
});
In order to send form data through Ajax, you have to specify the content type of the request. In you case it will be 'application/x-www-form-urlencoded:
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
So your code will be:
submit.addEventListener("click", function(e){
e.preventDefault();
var xhr = new XMLHttpRequest();
xhr.open("POST", "index.php", true);
xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
xhr.onreadystatechange = function () {
if(xhr.readyState == 4 && xhr.status == 200) {
var result = xhr.responseText;
console.log(result);
}
}
xhr.send("fname=Henry&lname=Ford");
});

How to display POST values which are coming from javascript XMLHttpRequest() in php

I am sending parameters using XMLHttpRequest() javascript function to another php page in Json formate, but $_POST['appoverGUID'] not getting post values.
Here is my Javascript code.
function loadPage(href){
var http = new XMLHttpRequest();
var url = json.php;
var approverGUID = "Test";
var params = JSON.stringify({ appoverGUID: approverGUID });
http.open("POST", url, true);
http.setRequestHeader("Content-type", "application/json; charset=utf-8");
http.setRequestHeader("Content-length", params.length);
http.setRequestHeader("Connection", "close");
http.onreadystatechange = function() {
if(http.readyState == 4 && http.status == 200) {
document.getElementById('bottom').innerHTML = http.responseText;
}
}
http.send(params);
}
And here is my json.php file code.
if(isset($_POST['appoverGUID'])){
echo $_POST['appoverGUID'];
}
First of all remove these headers since they will be send automatically by the browser and it's the right way to do it.
http.setRequestHeader("Content-length", params.length);
http.setRequestHeader("Connection", "close");
This code is a cross browser solution and it's tested.
// IE 5.5+ and every other browser
var xhr = new(window.XMLHttpRequest || ActiveXObject)('MSXML2.XMLHTTP.3.0');
var params = "appoverGUID="+approverGUID;
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=UTF-8");
xhr.setRequestHeader("Accept", "application/json");
xhr.onreadystatechange = function () {
if (this.readyState === 4) {
if (this.status >= 200 && this.status < 400) {
console.log(JSON.parse(this.responseText));
}
}
}
xhr.send(params);
xhr = null;
You need use json_decode. Some like this:
if ("application/json" === getallheaders())
$_JSON = json_decode(file_get_contents("php://input"), true) ?: [];
Fill params this way (did no escaping/encoding of approverGUID content, here..):
params = "appoverGUID="+approverGUID;
Also see:
http://www.openjs.com/articles/ajax_xmlhttp_using_post.php

ajax error only first request is send

$('#show_mess').click(function (){
$('#dropdown_mess').slideToggle("slow");
$('#arrow_mess').slideToggle("slow");
$('#arrow_not').hide("slow");
$('#dropdown_not').hide("slow");
function recall(){ setTimeout(function () {
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "http://localhost/ajax/mess_data.php", true);
xmlhttp.onreadystatechange = function () {
if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById('dropdown_mess').innerHTML = xmlhttp.responseText;
}
}
xmlhttp.send();
document.getElementById('dropdown_mess').innerHTML = "<img class='non_auto' id='ajax_loading' src='img/ajax_loading.gif'></img>";
recall();
}, 2000);
};
recall();
});
this function works fine but when each ajax call is done i need to colse and re-oper chrome in order to work, works fine in firefox
You are already using Jquery so why don't you try it's ajax function like below
$.ajax({
url: "test.html",
context: document.body
}).done(function() {
....
});
You can find more information on the manual

Categories

Resources