Codeigniter & Ajax - Condition statement in javascript - javascript

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.

Related

How to use two forms in the Ajax request?

var getLoginpasssystem = function(getPassForgotSystem,getLoginCheckSystem){
$(document).ready(function() {
$('#login' || '#lostpasswordform').submit(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: 'http://www.virtuelles-museum.com.udev/spielelogin/logsystem.php',
data: $(this).serialize(),
success: function(response) {
var data = JSON.parse(response);
if (data.success == "accepted") {
document.getElementById('inner').innerHTML = 'Herzlich Willkommen';
// location.href = 'index.php';
} else {
alert('Ungültige Email oder Password!');
}
}
});
});
})
}
The question is how to use two forms in one request with ajax. In this code I used ||, but it doesn't work. I mean the #login form works well but the #lostpasswordform doesn't work. When I click on the button it reloads the page instead of giving an alert.
The reason for this is the way you do your jQuery selection. Selecting multiple elements is done like this: $( "div, span, p.myClass" )
In other words it should work if you replace $('#login' || '#lostpasswordform') with $('#login, #lostpasswordform')
You can read more in detail about this in the jQuery docs
elector be used to select multiple elements. $("#login,#lostpasswordform").submit()
Use below code :
var getLoginpasssystem = function(getPassForgotSystem,getLoginCheckSystem){
$(document).ready(function() {
$("#login,#lostpasswordform").submit(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: 'http://www.virtuelles-museum.com.udev/spielelogin/logsystem.php',
data: $(this).serialize(),
success: function(response) {
var data = JSON.parse(response);
if (data.success == "accepted") {
document.getElementById('inner').innerHTML = 'Herzlich Willkommen';
// location.href = 'index.php';
} else {
alert('Ungültige Email oder Password!');
}
}
});
});
})
}

Display js code in php method ajax

I run the PHP code by ajax method with the click of a button.
$(".btn_ranking").one('click', function(e) {
e.preventDefault();
var name = localStorage.getItem('name');
var time = localStorage.getItem('timer_end');
$.ajax({
url: "php/file.php",
method: "POST",
data: {
name: name,
time: time
}
});
});
I would like the file.php to be able to run the js code, for example:
if ($time < $_SESSION['time']) {
[...]
}
else {
echo '<script>alert("lol");</script>';
}
And that when the button .btn_ranking on the page is pressed, an 'lol' alert will be displayed. If it is possible?
you can echo a response to the AJAX call and then run the JS according to the response..
$(".btn_ranking").one('click', function(e) {
e.preventDefault();
var name = localStorage.getItem('name');
var time = localStorage.getItem('timer_end');
$.ajax({
url: "php/file.php",
method: "POST",
data: { name: name, time: time },
success: function (data) {
if(data==1){
//do this
}else if(data==2){
//do that
alert('LOOL');
}
}
});
});
PHP CODE:
if ($time < $_SESSION['time']) {
echo '1';
}
else {
echo '2';
}
You can't said to a server-side script to use javascript.
What you have to do is to handle the return of you'r ajax and ask to you'r front-side script to alert it. Something like that :
file.php :
if ($time < $_SESSION['time']) {
[...]
}
else {
echo 'lol';
exit();
}
Front-side :
$(".btn_ranking").one('click', function(e) {
e.preventDefault();
var name = localStorage.getItem('name');
var time = localStorage.getItem('timer_end');
$.ajax({
url: "php/file.php",
method: "POST",
data: {
name: name,
time: time
},
success : function(data) {
alert(data);
}
});
});
When you used ajax for call php script, everything will be print in the return of the php code will be return to the HTTP repsonse and so be on the Ajax return function as params.
Ok .. First change your js code to handle answer from php script:
$(".btn_ranking").one('click', function(e) {
e.preventDefault();
var name = localStorage.getItem('name');
var time = localStorage.getItem('timer_end');
$.ajax({
url: "php/file.php",
method: "POST",
data: { name: name, time: time }
success: function(data) {
console.log(data);
// check if it is true/false, show up alert
}
});
});
Then change php script (file.php), something like that:
$response = [];
if ($time < $_SESSION['time']) {
$response['data'] = false;
}
else {
$response['data'] = true;
}
return json_encode($response);
Something like that is the idea :) When u send ajax with POST method get variables from there, not from $_SESSION :)
U can see good example here

AJAX is not working in macOS WebView

I have created a WebView for macOS app and it contains one AJAX call. The same WebView is working fine when the app calls my local URL, but when it calls the live URL, the AJAX call is not working.
$(document).ready(function () {
$('#pripolcheck').click(function () {
var pripolcheck = $('#pripolcheck').val();
var app = $('#app').val();
var user_id = $('#user_id').val();
var contact = $('#contact').val();
// Returns successful data submission message when the entered information is stored in database.
var dataString = 'pripolcheck1=' + pripolcheck + '&app1=' + app + '&user_id1=' + user_id;
if (pripolcheck == '') {
alert('Please Fill All Fields');
} else {
// AJAX Code To Submit Form.
$.ajax({
type: 'POST',
url: 'http://mywebsite.com/ajaxformsubmit.php',
data: dataString,
cache: false,
success: function (result) {
// alert(result);
// $(".pripol").hide();
$('.pripolcheck').prop('checked', true);
$('input.pripolcheck').attr('disabled', true);
}
});
}
return false;
});
});
My local PHP version is 7.1.8 and my live server PHP version is 5.4.
Change your function to onclick of checkbox directly,put this code in your checkbox onclick="MyFuncion",why I'm telling this is for web view we need to give exact command in exact position it's not a browser
And your AJAX call will be like below,
function myFunction()
{
var pripolcheck = $("#pripolcheck").val();
var app = $("#app").val();
var user_id = $("#user_id").val();
var contact = $("#contact").val();
// Returns successful data submission message when the entered information is stored in database.
var dataString = 'pripolcheck1='+ pripolcheck + '&app1='+ app + '&user_id1='+ user_id;
if(pripolcheck=='')
{
alert("Please Fill All Fields");
}
else
{
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "ajaxformsubmit.php",
data: dataString,
cache: false,
success: function(result){
// alert(result);
// $(".pripol").hide();
$('.pripolcheck').prop('checked', true);
$("input.pripolcheck").attr("disabled", true);
}
});
}
return false;
}
"My local PHP version is 7.1.8 and my live server PHP version is 5.4."
I think this explains everything.
However, try setting an absolute URL in your call:
url: 'ajaxformsubmit.php',
to
url: '/ajaxformsubmit.php',
Or whatever the actual path would be. Just a single slash will give you
http://wherever.com/ajaxformsubmit.php
if u use same site url plz use relative path not absolute path then its ok.
if use defrant site url plz comment me so give me new solution
PLZ try
$(document).ready(function () {
$('#pripolcheck').click(function () {
var pripolcheck = $('#pripolcheck').val();
var app = $('#app').val();
var user_id = $('#user_id').val();
var contact = $('#contact').val();
// Returns successful data submission message when the entered information is stored in database.
var dataString = 'pripolcheck1=' + pripolcheck + '&app1=' + app + '&user_id1=' + user_id;
if (pripolcheck == '') {
alert('Please Fill All Fields');
} else {
// AJAX Code To Submit Form.
$.ajax({
type: 'POST',
url: '/ajaxformsubmit.php',
data: dataString,
cache: false,
success: function (result) {
// alert(result);
// $(".pripol").hide();
$('.pripolcheck').prop('checked', true);
$('input.pripolcheck').attr('disabled', true);
}
});
}
return false;
});
});

Ajax not working properly

Bear with me I'm my javascript is a little rusty. So I'm trying to use a call by ajax to a PHP file and give it a plan type then make sense of it check to see if it then return a true or false if some allowed slots are less than some slots used up for the plan. Here is the Form in XHTML.
<form method="post" action="/membership-change-success" id="PaymentForm">
<input type="hidden" name="planChosen" id="planChosen" value="" />
</form>
On the same file. The ( < PLAN CHOICE > ) gets parsed out to the current plan.
<script>
var hash = window.location.hash;
var currentPlan = "( < PLAN CHOICE > )";
$(".planChoice").click(function(event){
var isGood=confirm('Are you sure you want to change your plan?');
var success;
$("#planChosen").val($(this).data("plan"));
$.ajax({
url: '/ajax/planCheck.php',
type: "POST",
dataType: 'json',
data: ({plan: $(this).data("plan")}),
success: function (data) { //This is what is not working I can't get it to return true
success = data;
}
});
if(success) {
if (isGood) {
$("#PaymentForm").submit();
}
window.location = '/membership-change-success';
} else {
alert('Please make sure you deactivate your listings to the appropriate amount before you Downgrade.')
}
});
My PHP for the ajax response looks like this.
<?php
require ('../includes/common.php');
include_once ('../includes/db-common.php');
require ('../includes/config.php');
$membership = new membership($dbobject);
$listing = new listing($dbobject);
$totalAvailableListings = ($membership->get_listingsAmount($_POST['plan']));
if($totalAvailableListings>=$listing->get_active_listings($user->id)){
echo json_encode(true); // I've tried with out jason_encode too
} else {
echo json_encode(false);
}
And that's pretty much it if you have any suggestions please let me know.
So I've tried to do it another way.
$(".planChoice").click(function (event) {
var isGood = confirm('Are you sure you want to change your plan?');
var success;
$("#planChosen").val($(this).data("plan"));
if (false) {
if (isGood) {
$("#PaymentForm").submit();
alert('you did it');
}
} else {
alert(isSuccessful($(this).data("plan")));
//alert('Please make sure you deactivate your listings to the appropriate amount before you downgrade.');
}
});
and I have an ajax function
function isSuccessful(plan) {
return $.ajax({
url: '/ajax/planCheck.php',
type: "POST",
dataType: 'json',
data: {plan: plan}
});
}
The alert tells me this [object XMLHttpRequest]
any suggestions?
$.ajax() returns results asynchronously. Use .then() chained to $.ajax() call to perform task based on response
$.ajax({
url: '/ajax/planCheck.php',
type: "POST",
dataType: 'json',
data: {plan: $(this).data("plan")}
})
.then(function(success) {
if (success) {
$("#PaymentForm").submit();
}
// if `form` is submitted why do we need to set `.location`?
// window.location = '/membership-change-success';
} else {
alert('Please make sure you deactivate your listings to the appropriate amount before you Downgrade.')
}
}, function err(jqxhr, textStatus, errorThrown) {
console.log(errorThrow)
})
You should use the following form for your ajax call
$.ajax({
url: '/ajax/planCheck.php',
type: "POST",
dataType: 'json',
data: ({plan: $(this).data("plan")}),
success: success = data
})
.done(function(response) {
if(success) {
if (isGood) {
$("#PaymentForm").submit();
}
window.location = '/membership-change-success';
}
else {
alert('Please make sure you deactivate your listings to the
appropriate amount before you Downgrade.')
}
});
the .done() clause ensures that you perform that code after the ajax call is finished and the response is obtained.

Bootstrap Formwizard - Prevent to scroll to next step if each page form submitting ajax response gets error

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.

Categories