Wordpress ajax request in pure javascript (where to put action?) - javascript

WordPress ajax request in jquery.
The ajax request in jquery works but I'm trying to use pure JavaScript.
How can I turn this code into pure javascript?
$('#camitonContactForm').submit(function(event){
event.preventDefault();
isValidationOn = true;
validateInputs();
let formaction = $('#camitonContactForm').data('url');
let forminput = $('#camitonContactForm').serialize();
let noncecheck = $('#camitonContactForm').data('nonce'); ;
let formdata = new FormData;
formdata.append('action', 'contact_message');
formdata.append('nonce', noncecheck);
formdata.append('contact_message',forminput);
$.ajax(formaction, {
type:'POST',
data:formdata,
processData: false,
contentType:false,
success: function(res){
},
error: function(err){
alert(err.responseJSON.data);
}
});
Here I tried to write it in pure javascript but it doesn't work.
form.addEventListener('submit', (e) => {
e.preventDefault();
isValidationOn = true;
validateInputs();
//form action
let formwrapper = document.getElementById('camitonContactForm');
let formaction = formwrapper.getAttribute('data-url');
//form nonce
let noncecheck = formwrapper.getAttribute('data-nonce');
//form
let forminput = serialize(formwrapper);
var formdata = new FormData(form);
/*
formdata.append('action', 'contact_message');
formdata.append('nonce', noncecheck);
formdata.append('contact_message',forminput);
*/
let ajax = new XMLHttpRequest();
ajax.open("POST", formaction, true);
ajax.onreadystatechange = function() {
if(ajax.responseText == 4 && ajax.status == 200){
if(ajax.responseText == "success"){
}else{
statusSection.innerHTML = ajax.responseText;
btnsection.disabled = false;
alert('well something wrong');
}
}
}
ajax.send(formdata);
});
the serialize funcion i found on this link below
form serialize javascript (no framework)

Related

location.href not working after ajax response

I have an form that when it sumits the data it echo "success", I used the success to trigger a redirect to another page but it is not working. I have tried everything. The else statement works fine but whatever i write in the if(data == "success") is not working including console.log and alert.`
continueBtn.onclick = () =>{
//Ajax code
let xhr = new XMLHttpRequest();// this will create a new XML Object
xhr.open("POST", "php/signup.php", true );
xhr.onload = () =>{
if(xhr.readyState === XMLHttpRequest.DONE){
if(xhr.status === 200){
let data = xhr.response;
if(data == "success"){
errorTxt.textContent = "Thuinsowofnd wsikenon";
window.location.href = 'users.php';
}else{
errorTxt.textContent = data;
errorTxt.style.display = "block";
}
}
}
}
//let's send form data through Ajax to Php
let formData =new FormData(form);//this will create a new form object
xhr.send(formData);// this will the form data
`
I have tried using windows.location.href = "users.php" but it still doesn't work

vscode live server extension cuts off JavaScript code

I am trying to make a online booking system. And I am using vscode live server for live web for testing. I noticed that it cuts off a huge chunk of js code. I am using the newest version of vscode and google chrome. If you need any more information, feel free to ask me :).
Expected Behaviour:
<script>
window.addEventListener("DOMContentLoaded", function () {
// get the form elements defined in your form HTML above
var form = document.getElementById("my-form");
// var button = document.getElementById("my-form-button");
var status = document.getElementById("status");
// Success and Error functions for after the form is submitted
function success() {
form.reset();
status.classList.add("success");
status.innerHTML = "Thanks!";
}
function error() {
status.classList.add("error");
status.innerHTML = "Oops! There was a problem.";
}
// handle the form submission event
form.addEventListener("submit", function (ev) {
ev.preventDefault();
var data = new FormData(form);
ajax(form.method, form.action, data, success, error);
});
});
// helper function for sending an AJAX request
function ajax(method, url, data, success, error) {
var xhr = new XMLHttpRequest();
xhr.open(method, url);
xhr.setRequestHeader("Accept", "application/json");
xhr.onreadystatechange = function () {
if (xhr.readyState !== XMLHttpRequest.DONE) return;
if (xhr.status === 200) {
success(xhr.response, xhr.responseType);
} else {
error(xhr.status, xhr.response, xhr.responseType);
}
};
xhr.send(data);
}
</script>
Actual Behavior:
<script>
window.addEventListener("DOMContentLoaded", function () {
// get the form elements defined in your form HTML above
var form = document.getElementById("my-form");
// var button = document.getElementById("my-form-button");
var status = document.getElementById("status");
// Success and Error functions for after the form is submitted
function succe</script>
Reload the webpage and it should work.

How to remove jQuery from this code?

Due to some reason, I don't want to use jQuery in this JavaScript code:
$(function() {
var url = ; //webhook URL here
var content = "Hiii";
var username = "Hi";
$.post(url, {"content": content, "username": username});
});
Is there any way to convert this into a code that doesn't require jQuery?
First off, you can replace the $() with something like
document.addEventListener('DOMContentLoaded', (e) => {})
Secondly if you're only targeting newer browsers you can make use of fetch.
document.addEventListener('DOMContentLoaded', (e) => {
var url = ; //webhook URL here
var content = "Hiii";
var username = "Hi";
fetch(url, {
method: 'POST',
body: JSON.stringify({
content: content,
username: username,
})
});
});
or fallback to using plain XHR
var oReq = new XMLHttpRequest();
oReq.open("POST", url, true);
oReq.send({
content: content,
username: username,
});
var content = "Hiii";
var username = "Hi";
var http = new XMLHttpRequest();
var url = "your API url";
http.open("POST", url, true);
//Send the proper header information along with the request
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.onreadystatechange = function() {//Call a function when the state changes.
if(http.readyState == 4 && http.status == 200) {
alert(http.responseText);
}
}
http.send({"content": content, "username": username});
You can use XMLHttpRequest to make AJAX call like above.

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

Modify FormData with jQuery

I am trying to modify the "likes" of a xml file. How do I do that?
What I'm trying now:
var likes = +1;
formData.append("likes", likes);
var xhr = new XMLHttpRequest();
xhr.addEventListener("loadstart", showLoading, false);
var url = "linkishere";
xhr.open('POST', url, true);
xhr.onload = function (e) {
var response = $.parseJSON(e.target.response);
if (response.success == true) {
console.log('success: '+response.success);
hideLoading();
showThankyou();
console.log('Het stemmen is gelukt');
}else {
alert(response.error.message);
console.log(response.error.message);
console.log(agreeTermsAndConditions);
console.log('Er ging iets fout.');
}
};
xhr.send(formData); // multipart/form-data
}
Hope someone can help me with this. Do I use append for this? Sorry I'm new to this.

Categories

Resources