I am trying to send a newsletter subscription request to Magento, but It returns null and nothing happens.
I've searched around and found very different URLs to post the request. And also grabbed the code from the file from base template.
In fact, maybe I am not sending the correct parameters or whatever.
This is the code in use:
<form method="post" id="newsletter-form">
<input type="hidden" class="url" value="<?php echo $this->getUrl('newsletter/subscriber/new') ?>">
<input id="newsletter" type="text" name="email" placeholder="RECEBA NOVIDADES" value="" class="input-text myFormInput" maxlength="128" autocomplete="off" style="width: 188px !important">
<button type="submit" id="ajax-newsletter-submit" title="CADASTRAR"
class="button myFormButton" style="margin-top:20px;margin-left: -107px !important;width: 103px">CADASTRAR</button>
</div>
</form>
Javascript:
var newsletterSubscriberFormDetail = new VarienForm('newsletter-form');
$j(function() {
$j("#ajax-newsletter-submit").click(function() {
var email =$j("#newsletter").val();
var url=$j(".url").val();
var dataString = 'email='+ email;
if(email=='') {
$j("#newsletter").focus();
} else {
var a = email;
var filter = /^[a-zA-Z0-9_.-]+#[a-zA-Z0-9]+[a-zA-Z0-9.-]+[a-zA-Z0-9]+.[a-z]{1,4}$/;
if(filter.test(a)){
$j.ajax({
type: "POST",
url: url,
data: dataString,
success: function(){
alert('Assinatura realizada com sucesso!');
$j("#newsletter").val('');
}
});
} else {
$j("#newsletter").focus();
}
}
return false;
});
});
Try this code,
var val_form = new VarienForm('your form id');
jQuery("#your form id").submit(function(e)
{
if (val_form.validator && val_form.validator.validate())
{
var postData = jQuery(this).serializeArray();
var formURL = jQuery(this).attr("action");
jQuery.ajax(
{
url : formURL,
type: "POST",
data : postData,
success:function(data, textStatus, jqXHR)
{
alert('success');
},
error: function(jqXHR, textStatus, errorThrown)
{
alert('Failure');
}
});
this.reset(); //form field reset
e.preventDefault(); //STOP default action
e.unbind(); //unbind. to stop multiple form submit.
}
});
Related
I am creating a form using reCAPTCHA v2 and want the form to be able to be submitted again without reloading the page. When I submit the form for the first time, it works as expected. However, when I submit the form again without reloading the page, my CaptchaValidate function will be called twice, first returning false, then returning true. Why is this happening? Any help would be brilliant, thanks.
HTML
<form id="form" method="POST">
<label for="name">Name</label>
<input class="form-control" id="name" name="name">
<label for="age">Age</label>
<input class="form-control" id="age" name="age">
<button class="g-recaptcha" data-sitekey="myKey" data-callback="onSubmit" type="submit">Submit</button>
</form>
Javascript
function onSubmit(response) {
$('#form').submit(function (e) {
e.preventDefault();
const formData = $(this).serializeArray();
$.ajax({
url: '/Home/CaptchaValidate',
type: 'POST',
dataType: 'text',
data: { dataToken: response },
success: function (resultData) {
if (resultData == 'true') {
//do something
}
else {
$('.error-message').html('could not submit form');
}
},
error: function (err) {
console.log(err);
}
})
}).submit();
grecaptcha.reset();
}
Controller
[HttpPost]
public async Task<string> GetCaptchaData(string dataToken)
{
HttpClient httpClient = new HttpClient();
string secretKey = "mySecretKey";
var res = httpClient.GetAsync("https://www.google.com/recaptcha/api/siteverify?secret=" + secretKey + "&response=" + dataToken).Result;
if (res.StatusCode != HttpStatusCode.OK)
return "false";
string JSONres = res.Content.ReadAsStringAsync().Result;
dynamic JSONdata = JObject.Parse(JSONres);
if (JSONdata.success != "true")
return "false";
return "true";
}
try use e.stopImmediatePropagation();
it stops the rest of the event handlers from being executed.
function onSubmit(response) {
$('#form').submit(function (e) {
e.preventDefault();
e.stopImmediatePropagation(); // new line
const formData = $(this).serializeArray();
$.ajax({
url: '/Home/CaptchaValidate',
type: 'POST',
dataType: 'text',
data: { dataToken: response },
success: function (resultData) {
if (resultData == 'true') {
//do something
}
else {
$('.error-message').html('could not submit form');
}
},
error: function (err) {
console.log(err);
}
})
}).submit();
grecaptcha.reset();
}
I have a form on click of submit the input box is highlighted with the red color border if it is empty. Now i have jquery ajax form submission on success of the form i will display a message "data submitted" and i will reset the form so all the input fields will be highlighted in red color. Now i want to empty the fields after the success of form submission and it should not be highlighted in red color.
HTML
(function() {
'use strict';
window.addEventListener('load', function() {
var form = document.getElementById('index-validation');
form.addEventListener('submit', function(event) {
if (form.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
}
form.classList.add('was-validated');
}, false);
}, false);
})();
$(".index-form").submit(function(e) {
e.preventDefault();
return false;
}
else {
var ins_date = new Date($.now()).toLocaleString();
var parms = {
name: $("#name").val(),
email: $("#email").val(),
inserted_date: ins_date
};
var url2 = "http://localhost:3000/api";
$.ajax({
method: 'POST',
url: url2 + "/homes",
async: false,
dataType: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(parms),
success: function(data) {
console.log('Submission was successful.');
$(".alert-success").removeClass("d-none");
$(".alert-success").fadeTo(2000, 500).slideUp(500, function() {
$(".alert-success").slideUp(500);
});
$('.index-form')[0].reset();
console.log(data);
},
error: function(data) {
console.log('An error occurred.');
console.log(data);
},
})
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form class="container index-form" id="index-validation" novalidate>
<input class="form-control" type="text" id="name" name="name" placeholder="Your name" required>
<input class="form-control" type="email" id="email" name="email" placeholder="Email Address" required>
<div class="invalid-feedback">Please Enter a Valid Email Id.</div>
<input type="submit" id="submit" class="btn btn-default btn-lg btn-block text-center" value="Send">
</form>
I'm not clear with your question, Do you want to reset form or remove the error class. But anyways I'll try solving out both :
SCRIPT
<script type="text/javascript">
(function() {
'use strict';
window.addEventListener('load', function() {
var form = document.getElementById('index-validation');
form.addEventListener('submit', function(event) {
if (form.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
}
form.classList.add('was-validated');
}, false);
}, false);
})();
$(".index-form").submit(function(e) {
e.preventDefault();
return false;
} else {
var ins_date=new Date($.now()).toLocaleString();
var parms = {
name : $("#name").val(),
email : $("#email").val(),
inserted_date:ins_date
};
var url2="http://localhost:3000/api";
$.ajax({
method: 'POST',
url: url2 + "/homes",
async: false,
dataType : "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(parms),
success: function(data){
console.log('Submission was successful.');
//if you are removing specific property from class
$(".alert-success").css('display', 'none');
$(".alert-success").fadeTo(2000, 500).slideUp(500, function(){
$(".alert-success").slideUp(500);
});
$("form")[0].reset();
console.log(data);
}, error: function (data) {
console.log('An error occurred.');
console.log(data);
},
})
}
});
</script>
Jquery doesn't support any method such as reset() of javascript, So you can trigger javascript's reset() method.
Feel free to ask doubts if stuck. Happy coding....!!!!!
$(this.('.index-form').find("input[type=text]").val("");
You can just empty the form value by giving the .val() as empty, you have to give this on after your ajax response.
and also instead of using fade in and fade out just try to use hide and show function both may work like same.
I have a form and I want to send values to my controller
I wrote this codes but it returns me MethodNotAllowedHttpException error,
I have a html form
I send it with POST method
My route is post too
My form:
<form method="post" id="form">
{{csrf_field()}}
<input type="text" name="fname" id="fname">
<input type="text" name="lname" id="lname">
<input type="submit" name="submit-btn" id="submit-btn">
<h4 id="head"></h4>
</form>
JS:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$(document).ready(function(){
$('#form').submit(function () {
$.ajax({
type : 'POST',
url : '{{route('routeName')}}',
data : {
fname: $("input#fname").val(),
lname: $("input#lname").val(),
},
error: function (xhr, ajaxOptions, thrownError) {
//alert(xhr.status);
//alert(thrownError);
},
success: function(result){
$('#head').text(result.head);
}
});
});
});
</script>
My Route :
Route::post('routeName' , [
'uses' => 'SomeController#Generate',
'as' => 'routeName']);
Controller :
public function Generate(){
$resp = array();
$fname= Input::get('fname');
$lname= Input::get('lname');
$resp["status"] = "ok";
return (Response::json($resp));}
And the error is :
error
Try this:
</script>
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$(document).ready(function(){
$('#form').submit(function (e) {
e.preventDefault(); //**** to prevent normal form submission and page reload
$.ajax({
type : 'POST',
url : '{{route('routeName')}}',
data : {
fname: $("input#fname").val(),
lname: $("input#lname").val(),
},
success: function(result){
console.log(result);
$('#head').text(result.status);
},
error: function (xhr, ajaxOptions, thrownError) {
//alert(xhr.status);
//alert(thrownError);
}
});
});
});
</script>
Add Request in controller method Generate
public function Generate(Request $request){
$resp = array();
$fname = $request->fname;
$lname = $request->lname;
$resp["status"] = "ok";
return Response::json($resp);
}
Hope it helps.
Try changing the following:
url : '{{url('routeName')}}',
and
return Response::json($resp);
don't forget to prevent the default submit event
$('#form').submit(function (e) {
e.preventDefault();
..........
and change:
$('#head').text(result.status);
I have a request with ajax that still loads the php script instead of performing its function without refreshing. Am guessing there is an issue with my ajax Below is anything wrong with the ajax script
HTML
<form action='connect_exec.php' method='post' id='connect_form' enctype='multipart/form-data'>
<input type='text' name='conn_id' id='conn_id' value='$ad_id'>
<input type='submit' name='connect' class='conn_text' id='connect' value='connect +'>
</form>
Ajax request
$('#connect_form').submit(function(e) {
e.preventDefault();
var ad_id = $('#conn_id').val();
$.ajax({
type: "POST",
url: "connect_exec.php",
data: ad_id
}).done(function(response) {
console.log(response);
}).fail(function(data) {
console.log(data);
});
});
PHP SCRIPT
require_once("db.php");
$db = new MyDB();
session_start();
if (isset($_POST['connect'])) {
$my_id = $_SESSION['log_id'];
$ad_id = $_POST['conn_id'];
$rand_num = rand();
$hsql = <<<EOF
SELECT COUNT(hash) as count FROM connect WHERE(user_one = '$my_id'
AND user_two = '$ad_id') OR(user_one = '$ad_id'
AND user_two = '$my_id');
EOF;
$hret = $db->querySingle($hsql);
if ($hret == 1) {
$response = "Your are already connected to '$ad_id'";
} else {
$csql = <<<EOF
INSERT INTO connect(user_one, user_two, hash) VALUES('$my_id', '$ad_id', '$rand_num');
EOF;
$cret = $db - > exec($csql);
if (!$cret) {
echo "Error connecting to '$ad_id'";
} else {
echo "Successful";
}
}
}
The form executes but not without refreshing the page. Please what is the issue with the ajax?
I recommend you to send form data serialized, using serialize() method.
Also, use submit event for form: $('form').on('submit', function (e) {}
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "connect_exec.php",
data: $('form').serialize()
}).done(function(response) {
console.log(response);
}).fail(function(data) {
console.log(data);
});
});
$('#connect').click(function(e) {
e.preventDefault();
var ad_id = $('#conn_id').val();
console.log(ad_id);
$.ajax({
type: "POST",
url: "connect_exec.php",
data: ad_id
})
.done(function (response) {
console.log(response);
})
.fail(function (data) {
console.log(data);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action='connect_exec.php' method='post' id='connect_form' enctype='multipart/form-data'>
<input type='text' name='conn_id' id='conn_id' />
<input onclick="return;" type='submit' name='connect' class='conn_text' id='connect' value='connect +'>
</form>
My code so far
main.js file:
$('#addButton').on('click', function() {
var email = $('#userInput').val();
$.ajax({
type: "post",
url: 'validation.php',
success: function(html) {
alert(html);
}
});
});
index.html file:
<form method="post">
<input type="text" name="email" placeholder="Your Email" id="userInput"><br>
<button type="submit" name="submit" id="addButton">Add User</button>
</form>
<!-- jQuery first, then Bootstrap JS. -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.2/js/bootstrap.min.js" integrity="sha384-vZ2WRJMwsjRMW/8U7i6PWi6AlO1L79snBrmgiDpgIWJ82z8eA5lenwvxbMV1PAh7" crossorigin="anonymous"></script>
<script src="main.js"></script>
validation.php file:
<?php
if (array_key_exists("submit", $_POST)) {
$link = mysqli_connect("localhost", "my_username", "my_password", "my_db");
if (mysqli_connect_error()) {
die("Error Connecting To Database");
}
if (validateEmail($_POST['email'])) {
$query = "INSERT INTO `users` (`email`) VALUES ('".mysqli_real_escape_string($link, $_POST['email'])."')";
if (mysqli_query($link, $query)) {
$success = "Email: ".$_POST['email']." added";
} else {
echo "Error in query";
}
}
}
?>
Here is my validate email function:
function validateEmail($email) {
if (!preg_match('/^([a-z0-9\+\_\-\.]+)#([a-z0-9\+\_\-\.]{2,})(\.[a-z]{2,4})$/i', $email)) {
echo "Invalid Email";
return false;
} else {
$domain = array('umich.edu');
list(, $user_domain) = explode('#', $email, 2);
return in_array($user_domain, $domain);
}
}
Am I performing my Ajax request incorrectly because it never adds the email to the database?
Try something this :
$.ajax({
type: 'POST',
// make sure you respect the same origin policy with this url:
url: 'validation.php',
data: {
'email': email
},
success: function(html){
}
});
There is a lot of way to do that, but I think this is the best way and the easiest way for you to make it work base on your current code.
First thing, You don't need to use type="submit" button when using AJAX.
HTML should be,
<form id='emailform'>
<input type="text" name="email" placeholder="Your Email" id="userInput"><br>
<button type="button" name="submit" id="addButton">Add User</button>
</form>
Your JS should be something like this, use jQuery's .serialize() function to your form:
$('#addButton').on('click', function() {
var email = $('#userInput').val();
$.ajax({
type: "post",
url: 'validation.php',
data: $('#emailform').serialize(),
dataType: "html",
success: function(html) {
alert(html);
}
});
});
Try this ;)
$('#addButton').on('click', function(event){
/* prevent default behavior of form submission. */
event.preventDefault();
var email = $('#userInput').val();
$.ajax({
type: "post",
data: {
email: email,
submit: 1
},
url: "validation.php",
success: function(html){
alert(html);
}
});
});
You need to send email and submit because you wrapped all code in if (array_key_exists("submit", $_POST)) { means you are checking if the submit field submitted or not.
You can use below function also in your main.js.
Please remember that whenever you run any post request and if you want to send some data to server you need to mention that variable or json one of the parameter.
$(document).ready(function(){
$("button").click(function(){
$.post("demo_test_post.asp", {email: "hello#hello.com"},
function(data, status){
alert("Data sent!");
});
});
});
Or you can use the below code also for better understanding
$.ajax({
type: 'POST',
// make sure you respect the same origin policy with this url:
url: 'validation.php',
data: {
email: email
},
contentType:'application/json',
success: function(html){
}
});