Cannot pass data to database with JSON ajax? - javascript

1 Ajax (Working able to send data to db)
var ajax=new XMLHttpRequest();
ajax.onreadystatechange=function(){
if(ajax.readyState === 4 && ajax.status === 200) {
alert(ajax.responseText);
//window.location.replace('login_form.php');
}
};
ajax.open("POST","register.php",false);
ajax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
ajax.send(parameters);
} // End of else statement
} // End of function
2 JSON AJAX (not Working - data are not sent to my db)
var ajax=new XMLHttpRequest();
ajax.onreadystatechange=function(){
if(ajax.readyState === 4 && ajax.status === 200) {
var passData = JSON.parse(ajax.responseText);
}
};
ajax.open("POST","register.php",false);
ajax.setRequestHeader("Content-type", "application/json");
ajax.send(parameters);
} // End of else statement
} // End of function
a) With ajax when i click on my btn register my data is being sent to my database but with json it does not working (both of them show no error).
b) I'm not able to re-direct the user to the login form even after a successful registration, it just remain on the registration page

Related

How can Javascript account for returning a 500?

I am using a login form to construct and send a URL (that'd be the "full url" written to storage in the script below) that should return a JSON object.
If the login is correct, the back-end sends me a JSON object with a validation key in it to validate if it cam back successfully. (like this: [{"result":"VALID"}] )
If the login is incorrect, it only provides a 500 error.
Unfortunately, when it gets that 500 error, instead of booting them because the result isn't VALID, the script just gives up because there's no object to validate.
From the Front-End, how can I detect that I have received a 500 error and then trigger "bootThem()"?
function readTextFile(file, callback) {
var rawFile = new XMLHttpRequest();
rawFile.overrideMimeType("application/json");
rawFile.open("GET", file, true);
rawFile.onreadystatechange = function () {
if (rawFile.readyState === 4 && rawFile.status == "200") {
callback(rawFile.responseText);
}
}
rawFile.send(null);
}
window.onload = function () {
// get the url from storage.
var fullURL = localStorage.getItem("fullURLStored")
// if the URL is empty, boot them back to the login page.
if(fullURL == " "){
bootThem();
}
// send the URL to the server.
readTextFile(fullURL, function (text) {
var data = JSON.parse(text);
if(data[0].result !== "VALID"){
bootThem();
} else{
//do stuff
}
});
}
Please see below fiddle I have simulated a 500 response from Mock API and handlinkg it:
if (rawFile.readyState === 4 && ((rawFile.status === 200) || (rawFile.status === 500))) {
console.log("fired");
callback(rawFile.responseText);
}
https://jsfiddle.net/asutosh/vdegkyx2/8/
Okay so thanks to Asutosh for the push in the right direction, I was able to adjust my function to boot the user if a 500 error was returned from the JSON call, and allow the user to pass through if there was not.
This was exactly what I needed to handle the 500 error coming back form the JSON:
function bootThem() {
//execute code to reset session and return user to login page.
}
function readTextFile(file, callback) {
var rawFile = new XMLHttpRequest();
rawFile.overrideMimeType("application/json");
rawFile.addEventListener('error', () => {
console.log("error code");
});
rawFile.open("GET", file, true);
rawFile.onreadystatechange = function() {
if (rawFile.readyState === 4 && (rawFile.status === 500)) {
console.log("500");
bootThem();
callback(rawFile.responseText);
}
if (rawFile.readyState === 4 && (rawFile.status === 200)) {
console.log("200");
callback(rawFile.responseText);
}
}
rawFile.send(null);
}
window.onload = function () {
// get the url from storage.
var fullURL = localStorage.getItem("fullURLStored")
// if the URL is empty, boot them back to the login page.
if(fullURL == " "){
bootThem();
}
// send the URL to the server.
readTextFile(fullURL, function (text) {
var data = JSON.parse(text);
if(data[0].result !== "VALID"){
bootThem();
} else{
//do stuff
}
});
}

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.

how to send very long data in ajax url?

i am using php and ajax together to access data from user and insert into database.problem is that it works fine with small string but when i try to send data on 10000 characters browser prompts an error saying url to long.. i can make change in php but i want it to be dynamic so i have to it using this way only.. help me plz.
function submitQuestion(){
var x=document.forms['Ask']['title'].value;
var y=document.forms['Ask']['description'].value;
if(x.length == 0 || y.length == 0){
alert('Insufficient Data');
}else{
startLoading();
console.log(y);
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function(){
if(this.readyState == 4 && this.status==200){
console.log(this.responseText);
if(this.responseText == "All Done"){
clearInterval(startLoadingClearInt);
alert("data Inserted");
// window.location.replace('../profile/userprofile.php');
}
}
};
//here x is very inn some cases and produces an error
xhttp.open("POST","./submitQuestion.php?title="+x+"&description="+y, true);
xhttp.send();
}
}
You cannot transfer large data via url (as messerbill said). You have to send them in the Body:
function submitQuestion(){
var x=document.forms['Ask']['title'].value;
var y=document.forms['Ask']['description'].value;
if(x.length == 0 || y.length == 0){
alert('Insufficient Data');
}else{
startLoading();
console.log(y);
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function(){
if(this.readyState == 4 && this.status==200){
console.log(this.responseText);
if(this.responseText == "All Done"){
clearInterval(startLoadingClearInt);
alert("data Inserted");
// window.location.replace('../profile/userprofile.php');
}
}
};
//here x is very inn some cases and produces an error
xhttp.open("POST","./submitQuestion.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("title="+x+"&description="+y");
}
}
inside the PHP-Script you get the data via the $_POST Array, not via the $_GET Array!

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

AJAX xmlhttp.open sumit data using POST method

I am trying to send a form data using POST method and xmlhttp.open
Please help find the error in my code
function submitChat() {
if (form1.msg.value == '' ) {
alert ('ALL FIELDS ARE MANDATORY');
return;
}
var xmlhttp = new XMLHttpRequest();
var msg = form1.msg.value;
var params = 'msg=helloooooooo';
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById('chatlogs').innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open('POST', 'rtest.php?rid=14', true);
xmlhttp.send(params);
}
Everything is fine and it is working with GET method. but POST method is not working. Please help.

Categories

Resources