href is responding thought it is false - javascript

guys I have a situation here. Im trying to validate an input from user that if the input is != "" it will do what inside the if and if its else it will do what inside the else. the validation is quite working except for one thing. though the condition is false it is still going inside the if condition and refreshing the the whole system by using this code $(location).attr('href','account_setting_registrar.php');
can you help me?
$(document).ready(function (){
var username ;
var eadd;
$('#change_usrname_button').click(function (){
username = $('#new_chnge_username').val();
if(username != "" ){
$.ajax({
type: 'POST',
url: 'account_setting_registrar_get.php',
dataType: 'json',
data:'username='+username,
success: function (data){
if(data.error == false){
alert("your username is successfuly changed");
$(location).attr('href','account_setting_registrar.php');
}
else{
alert("update error");
}
}
});
}
else{
alert("please put the new username");
}
});
$('#change_eadd_button').click(function (){
eadd = $('#new_chnge_eadd').val();
if(eadd != "" ){
$.ajax({
type: 'POST',
url: 'account_setting_registrar_get.php',
dataType: 'json',
data:'emailadd='+eadd,
success: function (data){
if(data.error == false){
alert("your email address is successfuly changed");
$(location).attr('href','account_setting_registrar.php');
}
else{
alert("update error");
}
}
});
}
else{
alert("please put the new username");
}
});
});

I'm thinking your validation should be a little more thorough...
You are only checking for empty string, however you also don't want it to be valid if the username is null or undefined as well.
You're validation should be the following:
if (username) {
// ajax
}
This will check the following:
null
undefined
NaN
empty string ("")
0
false

You should use data.error=='false' because the response you may getting is a string in json format.

$(document).ready(function (){
var username ;
var eadd;
$('#change_usrname_button').click(function (){
username = $('#new_chnge_username').val();
if(username){
$.ajax({
type: 'POST',
url: 'account_setting_registrar_get.php',
dataType: 'json',
data:'username='+username,
success: function (data){
if(data.error == true){
alert("your username is successfuly changed");
$(location).attr('href','account_setting_registrar.php');
}
else{
alert("update error");
}
}
});
}
else{
alert("please put the new username");
}
});
$('#change_eadd_button').click(function (){
eadd = $('#new_chnge_eadd').val();
if(eadd){
$.ajax({
type: 'POST',
url: 'account_setting_registrar_get.php',
dataType: 'json',
data:'emailadd='+eadd,
success: function (data){
if(data.error == true){
alert("your email address is successfuly changed");
$(location).attr('href','account_setting_registrar.php');
}
else{
alert("update error");
}
}
});
}
else{
alert("please put the new username");
}
});
});
You May try this one sir..

Related

Is there a way to prevent Enter key from returning a response in json from another page? Codeigniter Ajax

I am using ajax for my operations Create and Update
I can already create and update, but if I press or hit Enter key then this shows from another page which is kinda not look good to see, and it suddenly also create blank data after hitting Enter key.
{"success":false,"type":"update"}
For visual representation, here it what it looks like after hitting the Enter key on input fields
this is what my input is in my View
<input type="text" name="group[]" id="group" placeholder="Enter your Choice" class="form-control" />
in my Controller
public function addGroup(){
$result = $this->group_model->addGroup();
$msg['success'] = false;
$msg['type'] = 'add';
if($result){
$msg['success'] = true;
}
echo json_encode($msg);
}
public function updateGroup(){
$result = $this->group_model->updateGroup();
$msg['success'] = false;
$msg['type'] = 'update';
if($result){
$msg['success'] = true;
}
echo json_encode($msg);
}
And in Model
public function updateGroup(){
$id = $this->input->post('txtId');
$field = array(
'group_name'=>$this->input->post('group')
);
$this->db->where('id', $id);
$this->db->update('groups', $field);
if($this->db->affected_rows() > 0){
return true;
}else{
return false;
}
}
public function addGroup(){
$field = array(
'group_name'=>$this->input->post('group'),
);
$this->db->insert('groups', $field);
if($this->db->affected_rows() > 0){
return true;
}else{
return false;
}
}
Ajax
$('#btnSave').click(function(){
var url = $('#myForm').attr('action');
var data = $('#myForm').serialize();
//validate form
var group = document.getElementById('group').value;
if(group.replace(/\s/g, "").length <=0 ) {
swal("Submission fail!", "Enter the required field", "error");
return false;
}
$.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'
}
swal("Success!", "You delete a Question!", "success");
showGroups();
}else{
alert('Error');
}
},
error: function(){
alert('Could not add data');
}
});
});
$('#myForm').submit(function(e){
$('#btnSave').attr('disabled',true); //disable the button
//.Your other code
success: function(response){
if(response.success){
$('#btnSave').attr('disabled',false); //enable the button
}
}
}
On CLicking the button disable the click event of submnit button which is default behaviour if you press Entern and enable it back if u get successfuly response.
In addition if you just want to disable enter key then u cn do it like this:
var keyCode = e.keyCode || e.which;
if (keyCode === 13) {
e.preventDefault();
return false;
}
Change
$('#btnSave').click(function(){
var url = $('#myForm').attr('action');
var data = $('#myForm').serialize();
//validate form
var group = document.getElementById('group').value;
if(group.replace(/\s/g, "").length <=0 ) {
swal("Submission fail!", "Enter the required field", "error");
return false;
}
$.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'
}
swal("Success!", "You delete a Question!", "success");
showGroups();
}else{
alert('Error');
}
},
error: function(){
alert('Could not add data');
}
});
});
into
$('#myForm').submit(function(e){
e.preventDefault();
var url = $('#myForm').attr('action');
var data = $('#myForm').serialize();
//validate form
var group = document.getElementById('group').value;
if(group.replace(/\s/g, "").length <=0 ) {
swal("Submission fail!", "Enter the required field", "error");
return false;
}
$.ajax({
type: 'ajax',
method: 'post',
url: url,
data: data,
async: false,
dataType: 'json',
beforeSend: function(){
$('#btnSave').attr('disabled',true);
},
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'
}
swal("Success!", "You delete a Question!", "success");
showGroups();
}else{
alert('Error');
}
},
error: function(){
alert('Could not add data');
}
$('#btnSave').attr('disabled',false);
return false;
});
});
Change button into Submit
Hope this Helps !!

Check any data after confirmation message using JSON

I want to make the data alert successfully saved or fail after the user selects on the confirmation message. In this case data checking occurs after the user confirms the message I made.
This is my Javascript Code :
$('#add-btn').on('click', function(event){
var confirmation = confirm("Do you want to save ?");
if (confirmation == true) {
var code = $('#code').val();
var name = $('#name').val();
var unit = $('#unit').val();
var price_code = $('#price_code').val();
var type = $('#type').val();
var final = $('#final').val();
var dataString = 'code=' +code+ '&unit=' +unit+ '&price_code=' +price_code+ '&type=' +type;
if (code != '' && name != '' && unit != '' && price_code != '' && type != '' && final != ''){
event.preventDefault();
$.ajax({
type: "POST",
url: "../public/process/add_data.php",
data: dataString,
dataType: "json",
cache: false,
success: function(data){
if(data.status == 'success'){
alert("Success !");
}
else if(data.status == 'error'){
alert("Data already used !");
}
}
});
}
else{
alert('Please fill all fields !');
}
}
});
All input success to save but the alert cannot show.
I think problem in your php file. your JOSN data is not in correct format that you received in success.Please try this in your add_data.php file
//All code goes here and after insert try this
$array = array();
if(if data insert successfully) {
$array['status '] = 'success';
} else {
$array['status '] = 'error';
}
header('Content-Type: application/json');
echo json_encode($array);
The success function is only executed if everything went well. If there has been any error, you need to add the Ajax failure function as follows:
$.ajax({
type: "POST",
url: "../public/process/add_data.php",
data: dataString,
dataType: "json",
cache: false,
success: function(data){
alert("Success !");
}
}).fail(function () {
alert("Data already used !");
});
finally I find my solution. I'm sorry for my carelessness.
That happened because my variable dataString did not complete.
It should be :
var dataString = 'code=' +code+ '&name=' +name+ '&unit=' +unit+
'&price_code=' +price_code+ '&type=' +type+ '&final=' +final;
Thank you all for your kindness :-)

using ajax to create new table row and form submission

i am trying to make this ajax to submit my form but it only goes to the very last errror(Unexpected error! Try again).when i remove the datatype:json part,it then alerts undefined
function ajax(action,id){
if(action =="save")
data = $("#userinfo").serialize()+"&action="+action;
else if(action == "delete"){
data = "action="+action+"&item_id="+id;
}
$.ajax({
type: "POST",
url: "ajax.php",
data : data,
dataType: "json",
success: function(response){
if(response.success == "1"){
if(action == "save"){
$(".dert-form").fadeOut("fast",function(){
alert(here first);
});
}else if(action == "delete"){
alert(here to delete);
}
}
},
error: function(res){
alert("Unexpected error! Try again.");
}
});
}
here is ajax.php
if($action == "save"){
/* Check for blanks */
$err = "You have blank fields. ";
echo json_encode(
array(
"success" => "0",
"msg" => $err,
)
);
}
Here is a working example of your code with some adjustments:
function ajax(action,id){
action = 'save';
if(action =="save")
data = $("#userinfo").serialize()+"&action="+action;
else if(action == "delete"){
data = "action="+action+"&item_id="+id;
}
$.ajax({
type: "GET",
url: "http://demo.ckan.org/api/3/action/package_list",
data: data,
dataType: "jsonp",
success: function(response){
console.log(response);
if(response.success == "1"){
if(action == "save"){
$(".dert-form").fadeOut("fast",function(){
alert("here first");
});
}
else if(action == "delete"){
alert("here to delete");
}
}
},
error: function(res, textStatus, errorThrown){
console.log("Unexpected error! Try again.");
}
});
}
I'm hitting a data.gov API endpoint and logging the response to the console. Note, the dataType has to be jsonp since I'm make a cross-domain request. You can also look at the JSBin I created with the above code.
use json format for data instead or query string
data = {"action":action,"item_id":id};

if, else statement in jquery with php data

So I have a javascript ajax call like so:
$.ajax({
type: "POST",
url: "/checkout/doCharge",
data: dataString,
success: function(data) {
if(data == '1'){
$("#CheckoutSubmit").prop('disabled', false);
}
else{
$.growl.error({ message: "Your card was declined! Please try again." });
}
}
});
return false;
And the php call is:
$response = $this->stripe->charge_card($amount, $card, $desc);
if($response['paid'] == 'true'){
echo '1';
}
else{
echo '0';
}
Right now, the if(data == '1') is not working. it doesn't throw any error either. I am trying to get data as 1 if the paid response is true and 0 if the response is false.
Use $.trim to remove extraneous whitespace around the response.
success: function(data) {
data = $.trim(data);
if(data == '1'){
$("#CheckoutSubmit").prop('disabled', false);
}
else{
$.growl.error({ message: "Your card was declined! Please try again." });
}
}

Form Validation with Jquery and AJAX

I am using AJAX with JQUERY to call a PHP script to validate a user email. But, for some reason, the form submits even when it shouldn't. What am I doing wrong? I know the error is for sure not in my PHP.
My Code:
$("#signup").submit(function() {
var error= false;
var dataString = $(this).serialize();
var email= $("#email").val().trim();
if (email != 0) {
// Run AJAX email validation and check to see if the email is already taken
$.ajax({
type: "POST",
url: "checkemail.php",
data: dataString,
async: false,
success: function(data) {
var error= false;
if (data == 'invalid') {
var invalid= 1;
}
else if (data == 'taken') {
var taken= 1;
}
if (invalid == 1) {
alert('invalid email');
error = true;
}
if (taken == 1) {
alert('email taken');
error = true;
}
if (error == true) {
return false;
}
}
});
}
});
Try updating these:
$("#signup").submit(function(e) { //<----pass the event here as "e"
e.preventDefault(); //<----stops the form submission
var error= false;
var dataString = $(this).serialize();
var email= $.trim($("#email").val()); //<----use trim this way
If you absolutely have to use AJAX for form submission, this might be a better way to do it:
$('form').submit({
$.ajax({
type:'post',
url: 'someurl.php',
data: dataString,
context: this, // this here refers to the form object
success:function(data)
{
// perform your operations here
if(something_is_wrong)
{
// show message to user
}
else
{
this.submit(); // put this code in the block where all is ok
}
}
});
return false; // makes sure the form doesn't submit
});

Categories

Resources