Below I have a JSON array in my main PHP file. As you can see $firstname_error and $lastname_error are variables which I intend to pass to AJAX in order to have it displayed in two separate divs. At the moment nothing shows up and am unsure why. Any insight is greatly appreciated.
PHP & JSON
if (empty($_POST["City"])) {
$city_error = "A city required";
}
if (empty($_POST["E-mail"])) {
$email_error = "E-mail is required";
}
echo json_encode(array("city" => $city_error, "email" => $email_error));
AJAX
$(document).ready(function () {
$(".form").submit(function (e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "destination.php",
data: $(this).serialize(),
dataType: 'json',
cache: false,
success: function (data) {
if (data.trim() != '') {
$('.error4').html(data.city);
$('.error5').html(data.email);
}
},
error: function () {
}
});
});
});
.error4 and .error5 currently displays nothing.
Since you have dataType: 'json', the data variable passed to your success function is going to be an object so you can't use trim().
To check if the value exists in the response you can use hasOwnProperty on data:
success: function (data) {
$('.error4').text(data.hasOwnProperty('city') ? data.city : '');
$('.error5').text(data.hasOwnProperty('email') ? data.email : '');
},
Hope this helps!
I believe your if condition is not true, So try changing your success function like this:
success: function (data) {
if (data.city.trim() != '') {
$('.error4').html(data.city);
}
if (data.email.trim() != '') {
$('.error5').html(data.email);
}
}
Ok, I figured it out. Use if(data !== null) instead of if (data.trim() != '')
Related
Can anybody suggest me what I'm doing wrong?
I have a div with id="profGroup-section" and have javascript function that check if integer field levelId has value or is null in database.
If levelid has a value I want to show div with id="profGroup-section", else if levelid is null then I want to hide div with id="profGroup-section".
I tried different approaches, but when levelid has value then I successfully show div, but I can't manage hide the div.
Thank You in advance...
Here is my code:
checkLevelDegree: function (serviceId) {
var levelId;
$.ajax({
url: "/Sale/GetServiceByID/",
type: "GET",
contentType: "application/json; charset=utf-8",
datatype: JSON,
data: { serviceId: serviceId },
beforeSend: function () {
$("#profGroup-section").hide();
},
success: function (result) {
levelId = result;
},
complete: function () {
if (levelId === null || levelId === '') {
$("#profGroup-section").hide();
return;
}
else {
$("#profGroup-section").show();
}
},
error: function () { }
});
},
I have a form in an Asp.net MVC 5 project which has a Submit button. When the Submit button is clicked, I want to do the following:
Perform client=side validation using jQuery on various fields (required fields have been filled, email format is valid, etc...). That part is working fine.
Make an Ajax call that will perform some server side validation by calling an action from the controller and return a JSON response. The response contains a Success property and Errors property which contains a list of errors.
The Success property will return true if no error are found and the Errors property will be null. If errors are found the Success property is returns false and the Errors property contains a list of relevant errors.
I'm calling '\ApplicationForm\Validate' action from my ApplicationForm controller and this part is working fine.
When no errors are found in part 2, I want my form to be submitted as normal and call the '\ApplicationForm\Index' action so that my data can then be added to my database. I cannot get this part to work!!
The Submit button is defined as follows:
<div class="form-group">
<div>
<input type="button" id="btnApply" value="Apply" class="btn btn-primary" />
</div>
</div>
My JavaScript code is defined as follows:
$('#AppllicationForm').submit(function () {
if (!$(this).attr('validated')) {
if ($(this).valid()) {
$.ajax({
type: "POST",
data: $(this).serialize(),
url: "/ApplicationForm/ValidateForm",
dataType: 'json',
success: function (response) {
$('validationSummary').show();
if (response != null && response.success) {
console.log('No Validation errors detected');
$('#ApplicationForm').attr('validated', true);
$('#ApplicationForm').attr('action', '/ApplicationForm/Index')
.submit();
return true;
}
else if (response != null && !response.success) {
console.log('Validation errors detected');
var errors = response['errors'];
displayValidationErrors(errors);
window.scrollTo(0, 0);
}
return false;
},
error: function (response) {
$('validationSummary').hide();
console.log(response);
return false;
}
});
}
}
return false;
});
The above is using a regular button but I've also tried to define its type as Submit but to no avail.
I know similar questions have been posted in the past but I cannot find one that has actually helped me out to find a resolution to my problem, so please bear with me and do not mark this question as a duplicate unless there is an actual question/answer with an actual resolution to my problem. Much appreciated!
The closest scenario I found to what I'm trying to achieve is can be found from this article on SO: Submit a form from inside an ajax success function that checks the values
I've been trying so many different things at this stage but nothing is working out. I either don't get the Index action to be called after the ValidateForm action, or either one or the other action is called or the only Index action is called or my model gets messed up, and the list goes on.
I'm clearly not doing this correctly or missing something but I'm at a complete stand still for now. I'm hoping that it will be something silly that I've missed and hopefully someone will clarify this for me.
Any help would be greatly appreciated.
Try it out :
$('#btnApply').click(function (e) {
alert('submit');
e.preventDefault();
var form = $('form'); // change selector your form
if (!form.attr('validated')) {
if (form.valid()) {
$.ajax({
type: "POST",
data: form.serialize(),
url: "/ApplicationForm/ValidateForm",
dataType: 'json',
success: function (response) {
console.log('response received.');
if (response != null && response.success) {
console.log('No validation errors detected.');
form.attr('validated', true);
form.attr('action', '/ApplicationForm/Index')
.submit();
} else if (response != null && !response.success) {
console.log('Validation errors detected.');
var errors = response['errors'];
displayValidationErrors(errors);
window.scrollTo(0, 0);
}
},
error: function (response) {
console.log(response);
$('validationSummary').hide();
}
});
}
}
});
Please try it out:
$('#btnApply').on('click', function (e) {
e.preventDefault();
var form = $( "#AppllicationForm" );
if (!form.attr('validated')) {
if (form.valid()) {
$.ajax({
type: "POST",
data: $(this).serialize(),
url: "/ApplicationForm/ValidateForm",
dataType: 'json',
success: function (response) {
$('validationSummary').show();
if (response != null && response.success) {
console.log('No Validation errors detected');
form.attr('validated', true);
form.submit();
return true;
}
else if (response != null && !response.success) {
console.log('Validation errors detected');
var errors = response['errors'];
displayValidationErrors(errors);
window.scrollTo(0, 0);
}
return false;
},
error: function (response) {
$('validationSummary').hide();
console.log(response);
return false;
}
});
}
}
return false;
});
Your form action attribute will be '/ApplicationForm/Index'. When you click on the button, you make the validation and if everything is OK, then submit the form.
Please check below solution :
$('#btnApply').on('click', function (event) {
if ($('form').valid()) {
event.preventDefault();
$.ajax({
type: "POST",
data: $(this).serialize(),
url: "/ApplicationForm/ValidateForm",
dataType: 'json',
success: function (response) {
$('validationSummary').show();
if (response != null && response.success) {
console.log('No Validation errors detected');
$('#ApplicationForm').attr('validated', true);
$('form').submit(); // Here form will be submmited to Index action.
return true;
}
else if (response != null && !response.success) {
console.log('Validation errors detected');
var errors = response['errors'];
displayValidationErrors(errors);
window.scrollTo(0, 0);
}
return false;
},
error: function (response) {
$('validationSummary').hide();
console.log(response);
return false;
}
});
});
And decorate your ValidateForm method with [HttpPost] attribute.
I thought I'd share my solution as I ended up hiring a freelancer to have a look at it as I was under time constraint and could not afford to spend any more time on this.
How did it fix it? He added a second ajax call from within the first one. The annoying (and costly!) part is that I did try this but I had one important missing line i.e. var formValidated = $('#AppllicationForm').serialize();.
After these changes were made, I just had to rejig some of my logic regarding which div should be displayed and/or hidden but bar that it was pretty standard stuff.
Here's the final code that worked as expected:
$('#AppllicationForm').submit(function () {
if ($(this).valid()) {
$.ajax({
type: "POST",
data: $(this).serialize(),
url: "/ApplicationForm/ValidateForm",
dataType: 'json',
success: function (response) {
if (response != null && response.success) {
var formValidated = $('#AppllicationForm').serialize();
$.ajax({
url: '/ApplicationForm/Index',
data: formValidated,
type: 'POST',
success: function (result) {
$('#mainDiv').hide();
$('#Congrats').show();
}
});
return true;
}
else if (response != null && !response.success) {
var errors = response['errors'];
displayValidationErrors(errors);
window.scrollTo(0, 0);
}
return false;
},
error: function (response) {
$('validationSummary').hide();
return false;
}
});
}
return false;
});
Hope this helps others.
How do I alert a json_encode() message and reload the page? The function below only displays an undefined alert message
if($result1 == false)
$response['msg'] = "Transfer failed due to a technical problem. Sorry.";
else
$response['msg'] = "Successfully transferred";
echo json_encode($response);
$("#transfer").click(function() {
$.ajax({
type : "POST",
url : "transferProduct.php",
data : {},
success : function(data) {
data = $.parseJSON(data);
alert(data.response);
location.reload();
}
});
});
You're trying to get a undefined index response
Provided that your PHP script returns:
{
"msg": "<your-message-here>"
}
In your javascript you can do it:
$.ajax({
type : "POST",
url: "transferProduct.php",
dataType: 'json',
success : function(response) {
alert(response.msg);
location.reload();
}
});
Use code in this way
transferProduct.php
if($result1 == false)
$response['msg'] = "Transfer failed due to a technical problem. Sorry.";
else
$response['msg'] = "Successfully transferred";
echo json_encode($response);
code page
$("#transfer").click(function() {
$.ajax({
type : "POST",
url : "transferProduct.php",
data : {},
success : function(data) {
datas = $.parseJSON(data);
alert(datas.msg);
location.reload();
}
});
});
or you can use $.getJSON in place of $.ajax
$("#transfer").click(function() {
$.getJSON("transferProduct.php",function (data){
alert(data.msg);
location.reload();
});
});
I think you should format the return to correctly identify in the background:
{"success":true,"message":"---------"}
then in JavaScript: data.message
this is how the javascript looks like
<script type="text/javascript">
$(document).ready(function () {
$('#loginButton').click(function () {
//this.disabled = true;
debugger;
var data = {
"userid": $("#username").val(),
"password": $("#password").val()
};
$.ajax({
url: "/Account/LoginPost",
type: "POST",
data: JSON.stringify(data),
dataType: "json",
contentType: "application/json",
success: function (response) {
if (response.Success) {
$.get("#Url.Action("Search", "Home")", function (data) {
$('.container').html(data);
});
}
else
window.location.href = "#Url.Action("Index", "Home")";
},
error: function () {
alert('Login Fail!!!');
}
});
});
});
I am getting the alert('Login fail') also debugger not getting hit.
I am using jquery 1.9.1 and have included unobstrusive
my controller is this as you can i am passing string values not object values
to the controller so stringify is justified here
[HttpPost]
public JsonResult LoginPost(string userid, string password)
{
using (someentities wk = new someentities())
{
var LoginUser = wk.tblUsers.Where(a => a.Username.Equals(userid)&&a.Password.Equals(password)).FirstOrDefault();
if (LoginUser != null)
{
FormsAuthentication.SetAuthCookie(userid,false);
Session["Username"] = LoginUser.Username;
Session["Password"] = LoginUser.Password;
Session["Name"] = LoginUser.Name;
return Json(new { Success = true }, JsonRequestBehavior.AllowGet);
}
else
{
TempData["Login"] = "Please Enter Correct Login Details";
return Json(new { Success = false }, JsonRequestBehavior.AllowGet);
}
}
// If we got this far, something failed, redisplay form
}
when page is loading these error are shown
$(..) live is not a valid function in
(anonymous function) # jquery.unobtrusive-ajax.js:115
(anonymous function) # jquery.unobtrusive-ajax.js:163
take a look to the success function
success: function (response) {
if (response.Success) {
$.get("#Url.Action("Search", "Home")", function (data) {
$('.container').html(data);
});
}
else
window.location.href = "#Url.Action("Index", "Home")";
}
you are using multiple ", combine it with the single one ', this is a syntax error, try to check the code on an editor such as Atom, to avoid this kind of errors
Stringify converts an object to a string. Have you tried passing data an object instead of a string? Try replacing JSON.stringify(data), with data?
I'm working on someone else's code. I have this simple AJAX call in jQuery:
function getWSData (which, data, idVR)
{
if(which == 'verCandAll')
{
funcSuccess = verCandSuccess;
data = {'name' : 'val'};
}
else
{
funcSuccess = verElseSuccess;
data = {'name2' : 'val2'};
}
$.ajax({
type: 'POST',
url: wsURL,
data: data,
success: funcSuccess,
error:function ()
{
$("#msg").ajaxError(function()
{
popWaiting(false);
alert(verGenericCallError);
});
},
dataType: 'xml'
});
}
function verCandSuccess(xml){ ... }
function verElseSuccess(xml){ ... }
It's really simple. The only problem I have is the success callback. In case of verElseSuccess I would send a second parameter to that function, more precisely i would handle the idVR (an input parameter of getWSData). How can I accomplish this?
To achieve this, you can do:
...
if(which == 'verCandAll') {
...
}
else {
// create an anonymous function that calls verElseSuccess with a second argument
funcSuccess = function(xml) {
verElseSuccess(xml, idVR);
};
data = {'name2' : 'val2'};
}
...
Use Underscore.js partial function:
funcSuccess = _.partial(verElseSuccess, idVR);