I'm trying to send data to server from many lists in a page, each firing ajax data for PHP to process further. My code selects each lists using (class=dd) and send ajax data one by one. This works perfectly when I use alert(response) after ajax success, removing this alert message only sends less number of lists to server(only 2 lists are sent out of 4). Any thoughts?
$('#submit_sorting').on('click', function() {
var testEmail = /^[A-Z0-9._%+-]+#([A-Z0-9-]+\.)+[A-Z]{2,4}$/i;
if (testEmail.test($('#user_email').val()) || $('#user_email').val()==""){
$('[class=dd]').each(function(){
var data = $(this).nestable('serialize');
var dataJson = JSON.stringify(data);
console.log('sent '+JSON.stringify(data));
var response = ajaxx(data);
alert(response);
});
}
else
{
alert('enter valid email address');
}
});
and here is the ajax code
function ajaxx(data){
return $.ajax({
type: "POST",
url: 'cardsorting/update',
data: {
'new_order': data,
'user_comments':$('#user_comments').val(),
'user_email':$('#user_email').val(),
'_token':$('meta[name="_token"]').attr('content')
},
success: function(data){
if(data=='dataissaved'){
console.log('came here '+$(location).attr('href'));
}
else
{
console.log('received '+JSON.stringify(data));
}
},
error: function (data) {
alert('Could not connect to controller');
}
});
}
Here how it worked in the end, instead of sending multiple ajax requests for each selection, I collect them in an array and then ajax it to the backend php.
$('#submit_sorting').on('click', function() {
var sorting_array = new Array();
var testEmail = /^[A-Z0-9._%+-]+#([A-Z0-9-]+\.)+[A-Z]{2,4}$/i;
var flag = false;
if (testEmail.test($('#user_email').val()) || $('#user_email').val()==""){
$('[class=dd]').each(function(){
var data = $(this).nestable('serialize');
sorting_array.push(data);
console.log('sent '+JSON.stringify(data));
});
flag = true;
}
else
{
alert('enter valid email address');
}
if(flag){
ajaxx(sorting_array);
console.log(JSON.stringify(sorting_array));
}
});
Related
I have a JSON request using post method using ajax within this code
$(document).ready(function() {
$(document).on('submit', '#registration_check', function() {
var data = $(this).serialize();
$.ajax({
type: 'POST',
url: 'apidomain.com',
data: data,
success: function(data) {
$("#registration_check").fadeOut(500).hide(function() {
$(".result_1").fadeIn(500).show(function() {
$(".result_1").html(data);
});
});
}
});
return false;
});
});
the response will return 3 fields like name, email, phone on this element:
<div id="result_1"></div>
it's working nice so far, but want I plan to do is I want to display the alert or popup message if the ajax response found some of return value null. For example:
If JSON response return:
name: jhon, email: jhon#doe.com, phone: 123456789
user will redirect to the other page (done so far)
But if JSON response return
name: jane, email: jane#doe.com, phone:
The popup or alert will appeared, within text phone number empty.
If your data is a JSON object then you can do:
success: function(data) {
for (var i in data) {
if (!data[i]) {
alert(/* MESSAGE HERE */)
return;
}
}
// Your regular code here
}
You can make an associative array of your values in php file and echo it in the json format like
echo json_encode($array);
Then you will receive this in your ajax response like this
var objs = JSON.parse(data);
Then you can parse the values by keys like name, email and phone as you defined in associative array in your php file
console.log(objs.name);
console.log(objs.email);
console.log(objs.phone);
This is how you can parse the values individually. You can also apply conditions by your own way
First thing that comes to my mind: Do you need the JSON response in the document element or is it, that you dont know how to work with jQuery Ajax?
Anyway, this solution should help you in both cases:
$(document).ready(function()
{
$(document).on('submit', '#registration_check', function()
{
var data = $(this).serialize();
$.ajax({
type : 'POST',
url : 'apidomain.com',
data : data,
dataType: 'json', // tell jQuery, that the response data will be a JSON - it will be parsed automatically
success : function(data)
{
// now you have a parsed JSON object in the 'data' var
var show_alert = false;
if (data.phone === null || !data.phone.length) {
show_alert = true;
}
if (data.email === null || !data.email.length) {
show_alert = true;
}
if (show_alert) {
alert('here is the alert :)');
}
$("#registration_check").fadeOut(500).hide(function()
{
$(".result_1").fadeIn(500).show(function()
{
$(".result_1").html(JSON.stringify(data));
});
});
}
});
return false;
});
});
Im quiet confused with this code. Im reading this code of ajax which inserts the data automatically. but what im confused is this line if(result=='12') then trigger ajax what does 12 means why it should be 12 then conditioned to before ajax. Apparently im still learning ajax thanks. P.S this is working well btw im just confused with the code
here is the full code of the create function javascript / ajax
$('#btnSave').click(function(){
var url = $('#myForm').attr('action');
var data = $('#myForm').serialize();
//validate form
var empoyeeName = $('input[name=txtEmployeeName]');
var address = $('textarea[name=txtAddress]');
var result = '';
if(empoyeeName.val()==''){
empoyeeName.parent().parent().addClass('has-error');
}else{
empoyeeName.parent().parent().removeClass('has-error');
result +='1'; //ALSO THIS NUMBER 1 WHY SHOULD IT BE 1?
}
if(address.val()==''){
address.parent().parent().addClass('has-error');
}else{
address.parent().parent().removeClass('has-error');
result +='2'; //ALSO THIS NUMBER 2 WHY SHOULD IT BE 2?
}
if(result=='12'){ //HERE IS WHAT IM CONFUSED
$.ajax({
type: 'ajax',
method: 'post',
url: url,
data: data,
async: false,
dataType: 'json',
success: function(response){
if(response.success){
$('#myModal').modal('hide');
$('#myForm')[0].reset();
if(response.type=='add'){
var type = 'added'
}else if(response.type=='update'){
var type ="updated"
}
$('.alert-success').html('Employee '+type+' successfully').fadeIn().delay(4000).fadeOut('slow');
showAllEmployee();
}else{
alert('Error');
}
},
error: function(){
alert('Could not add data');
}
});
}
});
As I have explained in my commentaries, and since you wanted an example. This is how I will proceed in order to avoid checking for result == '12':
$('#btnSave').click(function()
{
var url = $('#myForm').attr('action');
var data = $('#myForm').serialize();
// Validate form
var empoyeeName = $('input[name=txtEmployeeName]');
var address = $('textarea[name=txtAddress]');
var formValid = true;
if (empoyeeName.val() == '')
{
empoyeeName.parent().parent().addClass('has-error');
formValid = false;
}
else
{
empoyeeName.parent().parent().removeClass('has-error');
}
if (address.val() == '')
{
address.parent().parent().addClass('has-error');
formValid = false;
}
else
{
address.parent().parent().removeClass('has-error');
}
// If form is not valid, return here.
if (!formValid)
return;
// Otherwise, do the ajax call...
$.ajax({
type: 'ajax',
method: 'post',
url: url,
data: data,
async: false,
dataType: 'json',
success: function(response)
{
if (response.success)
{
$('#myModal').modal('hide');
$('#myForm')[0].reset();
var type = '';
if (response.type=='add')
type = 'added';
else if (response.type=='update')
type ="updated";
$('.alert-success').html('Employee ' + type + 'successfully')
.fadeIn().delay(4000).fadeOut('slow');
showAllEmployee();
}
else
{
alert('Error');
}
},
error: function()
{
alert('Could not add data');
}
});
});
It's just checking existence of values and appending string to it.
if(empoyeeName.val()=='')
This check empty name and add error if name is empty. else it concat 1 to result.
if(address.val()=='')
This check empty address and add error if address is empty. else it concat 2 to result.
So if both of them are non empty that means result will be 12 and than only you make ajax call else show error.
i used a json login data file to login with php. i used javascript to search any user in the json data file and show me page or redirect to login page.
$(document).ready(function () {
$('#login').click(function () {
var email = $('#email').val();
var pass = $('#pass').val();
var error = true;
$.ajax({
type: "POST",
url: "login.json",
dataType: "json",
success: function (data) {
$.each(data, function (key, value) {
if (email == value.email && pass == value.pass) {
error = false;
}
});
if (error == false) {
document.location = "index.php?email=" + email;
} else {
$('#email').val('');
$('#pass').val('');
alert('please check your email or password!');
}
}
});
return false;
});
});
this works fine. but i used to login with my url and it also access any email to my index.php file. how to make to this correct.
i type like this on url and it also shows me index file.
http://json.test/index.php?email=test123#gmail.com
i want to restrict this method and only login with json file data. can anyone know how to make php session with this JavaScript code.
I have one function in java script. I want to send my form in ajax call after validation. I wrote ajax code for this but it's neither working nor giving any error on console even .
What can i do ?
javascript
function resetValidation(){
$(_reqForm).find('input, select, textarea, fieldset').removeClass('invalid');
$(_reqForm).find('.error-indicator').attr('aria-hidden', true);
$(_reqForm).find('#errorSummary').remove();
}
function handleSubmit(e){
e.preventDefault();
var formValid = true;
var errorMessages = [];
$.ajax({
type: "POST",
url: "quoteProcess.php",
data : $('#testform').serialize(),
success: function(data) {
alert(data);
//var obj = jQuery.parseJSON(data); if the dataType is not specified as json uncomment this
// do what ever you want with the server response
},
error: function() {
alert('error handing here');
}
});
$(_reqForm).find('#errorSummary').remove();
$(_reqForm).find('[data-do-validate="true"]').each(function(){
var validationResult = validateField($(this));
if (!validationResult.isValid) {
var fieldMsg = getFieldMessage($(this), validationResult.type);
errorMessages.push({ elem: $(this).prop('id'), msg: fieldMsg });
showFieldError($(this), fieldMsg);
formValid = false;
} else {
clearFieldError($(this));
}
});
if (!formValid) {
if (settings.showErrorSummary) {
showErrorSummary(errorMessages);
}
return false;
} else {
if (typeof(settings.submitFunction) !== 'undefined') {
settings.submitFunction();
} else {
_reqForm[0].submit();
}
}
}
I am using twitter bootstrap form wizard to submit data on each page with validation. Now i want to prevent, scroll to next step if ajax response gets error while submitting data. Below is my code,
'onNext': function(tab,navigation,index){
//scrollTo('#wizard',-100);
if(index == 1){
var $valid = $('#register_form').valid();
if(!$valid){
$validator.focusInvalid();
return false;
}
else
{
var options = $('form[name=register_form]').find('input, textarea, select').filter('.fw1').serialize();
var data = options + '&step=1';
$.ajax({
type: 'POST',
url: 'employeeEntryProcess.php',
data: data,
success: function(data){
this.show(2);
},
error: function(){
return false;
}
});
}
}
},
Thanks,
Its working after changes. Thanks to all for helping.
'onNext': function(tab,navigation,index){
if(index == 1){
var $valid = $('#register_form').valid();
if(!$valid){
$validator.focusInvalid();
return false;
}
else
{
var options = $('form[name=register_form]').find('input, textarea, select').filter('.fw1').serialize();
var data = options + '&step=1';
$.ajax({
type: 'POST',
url: 'employeeEntryProcess.php',
data: data,
success: function(response){
$('#wizard').bootstrapWizard('show',1);
},
error: function(){
alert('Error');
}
});
}
}
return false;
},
The only way to do this is to always return false so that it doesn't scroll to next step automatically, and then manually scrolling to the next step in the success function of the AJAX request (so that it would only proceed if it was successful). You may want to put an animation for the duration of the AJAX request as otherwise it would look like nothing is happening.