So my problem is that ajax (or something else) does not work for a form, and what is the most strange is that there is one form which does work perfectly with AJAX. I’ve tried a lot of things: changed input
with button
and for it the type from "submit" to "button"
, tried to use another method from jQuery .post()
and .get()
, tried to use xmlHttpRequest
. I am very confused now. Maybe you can see something what i can’t.Thanks
EDIT: So, i’ve modified it a little and got this error in the console (by now there where not any errors).
Error
Html form
<form action="./contactAction.php" method="POST" class="contact_form" id="cform"name="contactForm">
<input type="text" name="contactFname" placeholder="Prenumele" />
<input type="text" name="contactLname" placeholder="Numele" />
<input type="text" name="contactEmail" placeholder="Emailul tau" />
<textarea name="contactSubject" placeholder="Scrie mesajul tau" style="height: 200px"></textarea>
<button type="submit" name="contactBtn">Submit</button>
</form>
JS
$(document).ready(function () {
$("#contactBtn").click(() => {
contactFormValidation();
});
});
function contactRequest() {
let fname = $("#contactFname");
let lname = $("#contactLname");
let email = $("#contactEmail");
let subj = $("#contactSubject");
$.ajax({
type: "POST",
url: "../../contactAction.php",
data: ({"constactFname": fname, "contactLname": lname, "contactEmail": email, "contactSubject": subj}),
dataType: "html",
success: (response) => {
alert("Request success");
//$("#loginPage").html(response);
},
error: () => {
alert("Error :(");
}
});
return false;
}
function contactFormValidation() {
let $form2 = $("#contactForm");
$form2.validate({
wrapper: "div",
debug: false,
rules: {
contactFname: {
required: true
},
contactLname: {
required: true
},
contactEmail: {
required: true,
email: true
},
contactSubject: {
required: true
}
},
submitHandler: () => {
alert("Submit calledd");
contactRequest();
}
});
}
2
Answers
You can try this way.
Javascript
You have a few syntactical errors in your code.
From the looks of it, you’re trying to fetch the value based off the
name
attribute. For this to work, you’ll need the selector syntax for that specifically.With your current logic, you are also never actually fetching the value of the input fields. You’re merely holding the reference to the element. You need to access the value of the input field in order to retrieve it.
You are not using valid variable declarations. You need to specify your variable declarations by using either
var
,let
,const
.An example of getting the values a proper way would be:
Another way would be to use the
serialize()
method from jQuery. More about that here.