Transform Ajax to stop using jQuery - javascript

I have been using Ajax with jQuery to save pictures from canvas as follow:
HTML
<script src="https://code.jquery.com/jquery-3.4.0.min.js"></script>
<script src="javascript/take_pic.js"></script>
take_pic.js
$.ajax({
method: "POST",
url: "pictureController.php",
data: { canvasData }
}).done(function(data){
console.log("Success");
}).fail(function(html){
console.log("Fail");
});
pictureController.php
if(isset($_POST['canvasData']))
{
$data = $_POST['canvasData'];
saveData($data);
}
function saveData($data)
{
//...
}
This was working perfectly yesterday but stopped working today.. It seems that pictureController.php is not called anymore! What is strange is that console.log logs success..
I would like to stop using jQuery and use Ajax only, how can I update my JavaScript to do so?
Thank you!

Hey you can do this with :
const req = new XMLHttpRequest();
req.onreadystatechange = function(event) {
// XMLHttpRequest.DONE === 4
if (this.readyState === XMLHttpRequest.DONE) {
if (this.status === 200) {
console.log("Réponse reçue: %s", this.responseText);//ur response is here
} else {
console.log("Status de la réponse: %d (%s)", this.status, this.statusText);
}
}
};
req.open('POST', 'http://www.exemple.com/pictureController.php', true);//url to get and method here
req.send({ canvasData });//data to send here
and for more documentation read this

Related

How can i get and then send the id from the differents tags?

Im creating a website like a forum and i printing all posts from the database using PHP.
This is my code HTML where data-id gets a value(an id) from PHP.Each post has a code like this. As you can see, it has an event,so when i do clic on it(the a tag), it has to send that value using Ajax and make a request to bring back comments from the database and display the comments on a modal. I just can bring back comments from the first post. The other comments from the others post are not being displayed on the modal.
<span>25</span>
This is my ajax code:
document.addEventListener("DOMContentLoaded", () => {
document.querySelector(".comentarPosts").addEventListener("click", () => {
let xhr = new XMLHttpRequest();
xhr.open("POST", "comentarios.php"); // No utilices el tercer parámetro, está deprecado
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.onreadystatechange = () => {
if (xhr.readyState === 4) {
if (xhr.status <= 299 && xhr.status >= 200) {
document.getElementById("modal-message").innerHTML = xhr.responseText;
} else {
alert("Error al conectar con la API");
}
}
};
const comentarPost = document.querySelector(".comentarPosts");
xhr.send(`idPost=${comentarPost.getAttribute("data-id")}`);
});
});
I posted this question and it was closed.
I got this little example and it works:
<html>
25
</html>
<script language="javascript">
document.addEventListener("DOMContentLoaded", () => {
document.querySelector(".comentarPosts").addEventListener("click", function(event) {
alert(event.srcElement.dataset.id);
});
});
But when i have more links like this below only work for the first one,but for the others links dont work:
24
27
28
<script language="javascript">
document.addEventListener("DOMContentLoaded", () => {
document.querySelector(".comentarPosts").addEventListener("click", function(event) {
alert(event.srcElement.dataset.id);
});
});
That's the problem i want to resolve,clic on each links,taking the value from the data-id atributte and sending that value with ajax to make requests to the server.
you can do like this
document.addEventListener("DOMContentLoaded", () => {
var x=document.querySelectorAll(".comentarPosts");
for(i=0;i<x.length;i++)
x[i].addEventListener("click", function(event) {
var formdata = new FormData();
formdata.append('idPost',event.srcElement.dataset.id);
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
}
};
xhttp.open("POST", "comentarios.php", true);
xhttp.send(formdata);
});
});

How to send AJAX post request and receive back JSON data in Vanilla JS?

I have used JQuery example to send form data and receive back JSON data. Now I would like to do the same thing in plain/vanilla Javascript. Here is example of my JQuery code:
$('.frmSubmitData').on('submit', function(e){
e.preventDefault();
var formData = $('#myForm').serialize();
console.log(formData);
$.ajax({
type: 'POST',
encoding:"UTF-8",
url: 'Components/myTest.cfc?method=testForm',
data: formData,
dataType: 'json'
}).done(function(obj){
if(obj.STATUS === 200){
console.log(obj.FORMDATA);
}else{
alert('Error');
}
}).fail(function(jqXHR, textStatus, errorThrown){
alert("Error: "+errorThrown);
});
});
And here is what I have so far in plain JS:
function sendForm(){
var formData = new FormData(document.getElementById('myForm')),
xhr = new XMLHttpRequest();
xhr.open('POST', 'Components/myTest.cfc?method=testForm');
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.onload = function() {
if (xhr.status === 200) {
console.log(xhr.responseText);
}else if (xhr.status !== 200) {
alert('Request failed. Returned status of ' + xhr.status);
}
};
xhr.send(formData);
}
I think that something is wrong in way how I handle response with JSON data. If anyone can help me with problem please let me know. Thank you.
Optimally, for Firefox/Chrome/IE and legacy IE support, first determine the request type:
function ajaxReq() {
if (window.XMLHttpRequest) {
return new XMLHttpRequest();
} else if (window.ActiveXObject) {
return new ActiveXObject("Microsoft.XMLHTTP");
} else {
alert("Browser does not support XMLHTTP.");
return false;
}
}
Then, send the request:
var xmlhttp = ajaxReq();
var url = "http://random.url.com";
var params = "your post body parameters";
xmlhttp.open("POST", url, true); // set true for async, false for sync request
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send(params); // or null, if no parameters are passed
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
try {
var obj = JSON.parse(xmlhttp.responseText);
// do your work here
} catch (error) {
throw Error;
}
}
}

X-Domain Post using XMLHttpRequest

I have the following block of code:
console.log(1);
var xhr = new XMLHttpRequest();
xhr.open('POST', 'http://anothersite.com/deal-with-data.php');
xhr.setRequestHeader('Content-type','application/x-www-form-urlencoded');
console.log(2);
xhr.onreadystatechange = function () {
console.log(3);
if (this.status == 200 && this.readyState == 4) {
console.log(4);
xhr.send("formType="+thisFormType+
"&mediaCode="+3478+
"&car="+carID+
"&title="+$('#title').val()+
"&firstname="+$('#firstname').val()+
"&surname="+$('#lastname').val()+
"&tel="+$('#telephone').val()+
"&email="+$('#emailaddress').val()+
"&postcode="+$('#postcode').val()+
"&add1="+$('#add1').val()+
"&add2="+$('#add2').val()+
"&add3="+$('#add3').val()+
"&town="+""+
"&county="+""+
"&optin-post="+$('#optin-post').attr('checked')+
"&optin-tel="+$('#optin-tel').attr('checked')+
"&optin-email="+$('#optin-email').attr('checked')+
"&optin-sms="+$('#optin-sms').attr('checked')+
"&tarID="+targetID+
"&campID="+campaignID+
"&subID="+subjectID
);
console.log(5);
}
}
console.log(6);
So, everything fires except for the xhr.onreadystatechange - I never get the console.log(4) - I have enabled Access-Control-Allow-Origin in PHP and the htaccess as well as trying a veritable plethora of Javascript post functions.
The problem is, as a requirement, I need to post data from a form on a server that has no support for Server side languages - to another domain to handle the data.
Any ideas? It's driving me insane!
edit: I've also tried it with $.ajax
$.ajax({
url: 'http://anothersite.com/deal-with-data.php',
type: "post",
crossDomain: true,
data: {
"formType":thisFormType,
"mediaCode":3478,
"car":$('#car').val(),
"title":$('#title').val(),
"firstname":$('#firstname').val(),
"surname":$('#surname').val(),
"tel":$('#telephone').val(),
"email":$('#email').val(),
"postcode":$('#postcode').val(),
"add1":$('#add1').val(),
"add2":$('#add2').val(),
"add3":$('#add3').val(),
"town":"",
"county":"",
"optin-post":$('#opt-post').attr('checked'),
"optin-tel":$('#opt-tel').attr('checked'),
"optin-email":$('#opt-email').attr('checked'),
"optin-sms":$('#opt-sms').attr('checked'),
"tarID":targetID,
"campID":campaignID,
"subID":subjectID
},
beforeSend: function() {
$('#submit').val('Sending...').attr('disabled','disabled');
},
success: function(data) {
console.log("success call");
console.log(data);
},
error: function(err) {
console.log("error call");
console.log(err);
}
});
And now I've tried to enable it in httpd.conf as well: https://serverfault.com/a/378776/36601
You should not pass xhr.send inside xhr.onreadystatechange. Do something like the following:
var xhr = new XMLHttpRequest();
xhr.open('POST', 'myurl', true);
xhr.onload = function () {
if (xhr.status === 200 && xhr.readyState === 4) {
// do some cool stuff
console.log('You got a successfull request');
}
};
xhr.setRequestHeader('Content-type','application/x-www-form-urlencoded');
xhr.send(); // pass your params here
You may need to set Access-Control-Allow-Methods: POST header also. Read more on https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS

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

Passing values from javascript to servlet not working in chrome

Im trying to pass parameters to servlet from javascript with :
function selectHandler() {
var selection = table.getChart().getSelection()[0];
var topping = data.getValue(selection.row, 0);
var answer=confirm("Delete "+topping+"?");
if(answer){
document.location.href="/item?_method=delete&id="+topping;
alert(topping+" has been deleted");
location.reload();
}
else return false;
}
The values are getting passed to the servlet and is working fine when I'm using firefox as in I'm getting the url as: http://XXXXXXX/item?_method=delete&id=xxxx
But when I'm using chrome the URL that is send is http://XXXXXXX/item. as the values are not getting passed!! I have tried with window.location.href also with no change. what could be the issue?
What you need is ajax call or say XMLHttpRequest as below:
<script type="text/javascript">
function doAjax () {
var request,
selection = table.getChart().getSelection()[0],
topping = data.getValue(selection.row, 0),
answer=confirm("Delete "+topping+"?");
if (answer && (request = getXmlHttpRequest())) {
// post request, add getTime to prevent cache
request.open('POST', "item?_method=delete&id="+topping+'&time='+new Date().getTime());
request.send(null);
request.onreadystatechange = function() {
if(request.readyState === 4) {
// success
if(request.status === 200) {
// do what you want with the content responded by servlet
var content = request.responseText;
} else if(request.status === 400 || request.status === 500) {
// error handling as needed
document.location.href = 'index.jsp';
}
}
};
}
}
// get XMLHttpRequest object
function getXmlHttpRequest () {
if (window.XMLHttpRequest
&& (window.location.protocol !== 'file:'
|| !window.ActiveXObject))
return new XMLHttpRequest();
try {
return new ActiveXObject('Microsoft.XMLHTTP');
} catch(e) {
throw new Error('XMLHttpRequest not supported');
}
}
</script>
You can also do it easily by jquery,
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js" />
<script type="text/javascript">
function doAjax () {
...
$.ajax({
url: "item?_method=delete&id="+topping+'&time='+new Date().getTime()),
type: "post",
// callback handler that will be called on success
success: function(response, textStatus, jqXHR){
// log a message to the console
console.log("It worked!");
// do what you want with the content responded by servlet
}
});
}
</script>
Ref: jQuery.ajax()

Categories

Resources