jQuery validation followed by Ajax post - ajax

I'm trying to combine jQuery validation plugin with Ajax post. This is my code:
PHP form:
<form id="newsletter_form" method="post">
<input name="newsletteremail" type="text" id="newsletteremail" class="required email">
<input name="Signup" type="submit" class="formsm" id="Signup" value="Signup">
<div id="emailerrormessage"></div>
</form>
JQuery:
$('#newsletter_form').validate({
rules: {
email: {required:true, email:true}
},
submitHandler: function(form) {
$.ajax({
data: $(this).serialize(),
type: "POST",
url: "includes/ajax.php?action=newsletter",
contentType: "application/x-www-form-urlencoded; iso-8859-7",
dataType: 'json',
success: function(response, textStatus, jqXHR) {
if(response.status == 'error'){
$("#newsletteremail").removeClass().addClass('ajaxerror');
} else {
$("#newsletteremail").removeClass();
}
},
error: function (xhr, textStatus, errorThrown) {
$("#emailerrormessage").addClass('ajaxsuccess').html(xhr.responseText).show();
}
});
return false;
}
});
Before using validate() the form would submit fine. After adding the validate() code, the validation works, the form is being submitted (I receive a 200 OK response) but the values being submitted are null. What am I doing wring here?

this refers to the validator object that you're applying to the form, so change:
data: $(this).serialize(),
to
data: $(form).serialize(),

Use jQuery.form plugin and try it as below,
submitHandler: function(form)
{
jQuery(form).ajaxSubmit(
{
dataType : 'json',
beforeSend : function(arr, $form, options)
{
},
success : function(msg)
{
return false;
}
});
}

Related

The GET method is not supported for this route. Supported methods: POST. Laravel Ajax

I'm using ajax to send comments. This is the route
Route::post('/users/add/comment/', 'UsersController#AddComment')->name('AddComment');
The ajax call
function SendAny(){
$.ajax({
url: '/users/add/comment/',
data: {
"_token": "{{ csrf_token() }}",
"content": 'ksdflsdfnnkn',
},
type: 'post',
success: function(result) {
if (result == 0) {
location.reload();
} else {
alert("this an ereor")
}
}
});
}
and the controller
public function AddComment(Request $request){
dd($request);
}
It always throws that error. I changed the route and the func name a lot of times. but it does the same thing and the dd(); request is always empty.
Thanks in advance!
You have to set the ajax method to post with the attribute 'method', not 'type'.
function SendAny(){
$.ajax({
url: '/users/add/comment/',
data: {
"_token": "{{ csrf_token() }}",
"content": 'ksdflsdfnnkn',
},
method: 'post',
success: function(result) {
if (result == 0) {
location.reload();
} else {
alert("this an ereor")
}
}
});
}
I was trying to send the same data using <form> I tried AJAX to have more control over the request.
my form tag goes like <form method="POST" action="/users/add/comment/">
I removed the last / in the URL and it does work. I don't know how or why.
But It works !!!
Form
<form id="YourForm">
...
your inputs
...
</form>
Button
<button type="button" class="btn btn-success SendButton">Save This</button>
JS
<script type="text/javascript">
$(document).on('click', '.SendButton', function (e) {
e.preventDefault();
var data = $("#YourForm").serialize();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
method : "POST",
url : "{{ url('users/add/comment/') }}",
data : data,
dataType : "JSON",
})
.done(function(response) {
alert('Success!');
location.reload();
.fail(function(response) {
console.log("Error: ", response);
});
return false;
});
</script>
You need to change type to method, you use the wrong keyword. Now it is a default GET
$.ajax({
url: '/users/add/comment/',
data: {
"_token": "{{ csrf_token() }}",
"content": 'ksdflsdfnnkn',
},
method: 'post', // it should be method: 'post'
success: function(result) {
if (result == 0) {
location.reload();
} else {
alert("this an ereor")
}
}
});

Ajax success function not receiving data ASP.NET MVC

I can add the data to the database correctly, but Ajax success function is not working. I always get the error function :
View:
<div id="dvform">
<!-- some data-->
<input type="submit" value="submit" id="btnsubmit" />
</div>
<script>
$(document).ready(function () {
$("#btnsubmit").click(function () {
addAppointment();
});
});
function addAppointment (){
$.ajax({
type: 'POST',
url: '/FuelerAppointments/Create',
contentType: 'application/json; charset=utf-8',
dataType: "html",
data: $("dvform").val(),
success: function (data) {
swal("Done!", "The appointment was saved successfully!", "success");
},
error: function (data) {
swal("Error deleting!", "Please try again", "error");
},
});
}
Controller :
[HttpPost]
public ActionResult Create(FuelerAppointment fuelerAppointment)
{
return Json(fuelerAppointment, JsonRequestBehavior.AllowGet);
}
First you should change dataType: "html", to dataType: "json",
and create FuelerAppointment object before the $.ajax():
var fuelerAppointment = {};
fuelerAppointment.Name = $("#Name").val();
and then the data in ajax method
data: '{fuelerAppointment: ' + JSON.stringify(fuelerAppointment) + '}',
For more information check this link Using AJAX In ASP.NET MVC
change dataType: "html" to dataType: "json"
and in data properties should you write like this
var model = {
prop1: prop1Value,
prop2: prop2Value,
...
};
data: {fuelerAppointment: model}
Or
data: JSON.stringify({
fuelerAppointment: {
prop1: prop1Value,
prop2: prop2Value,
...
}
})
Notes: the fuelerAppointment object should behave a sem proprieties in C# class

Jquery validation is working but the ajax is not submitted

I'm trying to validate fields inside the form and then fire a function to submit the form using Ajax, the validation is working very well, but the ajax is not working at all
can you please help me figure the solution out
$(function() {
$.validator.addMethod("urlRegex", function(value, element) {
return this.optional(element) ||regex here .test(value);
}, "this should be url.");
$("#songvalid").validate({
rules:
{
song:
{
required: true,
urlRegex: true
}
},
messages:
{
song:
{
urlRegex:"من فضلك أدخل حروف وأرقام فقط"
}
},
submitHandler: function(form){
$("#error").fadeOut();
$("#song-btn").html('<img src="btn-ajax-loader.gif" /> انتظر لحظات ...', );
$.ajax({
url: 'song_process.php',
type: this.method,
data: $(this).serialize(),
success: function(responsd) {
if(responsd=="song"){
$("#song-btn").html(' تم الإرسال');
}
else{
$("#error").fadeIn(1000, function(){
$("#error").html('<div class="alert alert-danger"> <span class="glyphicon glyphicon-info-sign"></span> '+responsd+' !%</div>');
});
}
}
});
return false;
}
});
});
I found the answer!
I changed this:
type: this.method,
data: $(this).serialize(),
to this:
type: 'POST',
data: $("#formName").serialize(),

MVC Razor Ajax call from button click

I'm struggling to get a button click to invoke an Ajax function which then posts to a controller action. Cannot even get a simple message to work (nothing happens when button is clicked). Clearly, I'm missing something fundamental. What is it?
The Ajax script in my Razor form:
<script type="text/javascript">
$('#UseShipAddr').click(function () {
$.ajax({
url: "#(Url.Action("UseShippingAddress", "Checkout"))",
type: "POST",
data: { id: 50 },
cache: false,
async: true,
success: function (data) {
alert(data);
}
});
});
</script>
The button that I want to use to invoke the Ajax function:
<input type="button" value="Use Shipping Address" id="UseShipAddr" />
The action in CheckoutController:
// Ajax POST: /Checkout/UseShippingAddress/5
[HttpPost]
public ActionResult UseShippingAddress(int id)
{
return Content("It worked!");
}
Please try this code.
$(document).ready(function(){
$('#UseShipAddr').click(function () {
$.ajax({
url: "Checkout/UseShippingAddress",
type: "POST",
data: { id: 50 },
cache: false,
async: true,
success: function (data) {
alert(data);
}
});
});

Second $.ajax call stuck the code

I have an ajax+jquery navigation system with $.ajax, and I`m trying to do a second call to $.ajax to send a contact form infos, but, when I add the second $.ajax all just stop working.
First Call -
function loadPage(url)
{
url=url.replace('#!','');
$('#loading').css('visibility','visible');
$.ajax({
type: "POST",
url: "loader.php",
data: 'page='+url,
dataType: "html",
success: function(msg){
if(parseInt(msg)!=0)
{
$('#conteudo').html(msg);
$('#loading').css('visibility','hidden');
}
}
});
}
Second Call
$("#enviar").click(function() {
var str = $("form").serializeArray();
$.ajax({
type: "POST",
url: "update.php",
data: str,
success: function(mn) {
if(parseInt(mn)!=0)
{
$("#conteudo").html(mn);
$("#enviado").css('visibility','visible');
}
}
return false;
});
#EDIT
Very good! The first ajax is not stucking anymore, but this second is not working as expected.
This is intended to parse $_POST values to a php script and if ok just turn div visible..
How I`m doing that -
<form name="formcontato" id="form">
<fieldset>
<label>Seu nome</label>
<input type="text" name="nome" class="input-block-level">
<label>Email</label>
<input type="email" name="email" placeholder="seu#email.com" class="input-block-level">
<div class="form-actions">
<input type="button" name="enviar" value="Enviar" id="enviar" class="btn btn-baixar" />
</div>
</fieldset>
</form>
This is the form.
$("#enviar").click(function () {
var str = $("#form").serialize();
$.ajax({
type: "POST",
url: "update.php",
data: str,
success: function (mn) {
alert("Ok!");
if (parseInt(mn) != 0) {
$("#conteudo").html(mn);
$("#enviado").css('visibility', 'visible');
}
}
});
return false;
});
This is the js
if($_POST) {
$nome = trim($_POST['nome']);
echo $nome;
}
This is the update.php
In what you posted, the second function does not properly close the $.ajax() function with a }); so it would generate a parse error and none of the code in this block would be available.
Try this where the $.ajax() call is succesfully closed.
$("#enviar").click(function () {
var str = $("form").serializeArray();
$.ajax({
type: "POST",
url: "update.php",
data: str,
success: function (mn) {
if (parseInt(mn) != 0) {
$("#conteudo").html(mn);
$("#enviado").css('visibility', 'visible');
}
}
});
return false;
});
FYI, proper and consistent indentation is essential to spotting these issues.

Resources