using ajax to create new table row and form submission - javascript

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};

Related

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 :-)

showing loader image with submition using ajax

$(document).ready(function(){
$('#registration_form').on('submit',function(e){
/// e.preventDefault();
$("#loading").show();
var email = $('#email').val();
var checkEmail = $("#email").val().indexOf('#');
var checkEmailDot = $("#email").val().indexOf('.');
if(email == ''){
$("#email").addClass('error');
error_flag = 1;
}
if(checkEmail<3 || checkEmailDot<9){
$("#email").addClass('error');
error_flag = 1;
}
$.ajax({
url: "<?=base_url('controller/registration_ajax')?>",
// url: "<?=base_url('controller/register')?>",
type: "POST",
datatype: "JSON",
data: {email: email},
success: function(res){
var data = $.parseJSON(res);
var status = data.status;
var message = data.message;
if(status == 'true'){
// $('#myModal').modal('hide');
$('#message').html('');
$('#message').html(message);
$('#message').css('color',"green");
$("loading").hide();
}
else{
$('#message').html('');
$('#message').html(message);
$('#message').css('color',"red");
}
}
});
e.preventDefault();
});
});
how to use loader with ajax when message is success the load stop when message is or error loader is stop how to use loader image image in this stiuation. if submition is true loading hide if false loading also hide.
how to use loader with ajax when message is success the load stop when message is or error loader is stop how to use loader image image in this stiuation. if submition is true loading hide if false loading also hide.
You can use the always handler to do that.
Also note that, you should so the loader only if the ajax is sent, so in your case only after the validations are done it should be done.
$(document).ready(function() {
$('#registration_form').on('submit', function(e) {
/// e.preventDefault();
var email = $('#email').val();
var checkEmail = $("#email").val().indexOf('#');
var checkEmailDot = $("#email").val().indexOf('.');
if (email == '') {
$("#email").addClass('error');
error_flag = 1;
}
if (checkEmail < 3 || checkEmailDot < 9) {
$("#email").addClass('error');
error_flag = 1;
}
$.ajax({
url: "<?=base_url('controller/registration_ajax')?>",
// url: "<?=base_url('controller/register')?>",
type: "POST",
datatype: "JSON",
data: {
email: email
},
beforeSend: function() {
//show it only if the request is sent
$("#loading").show();
},
success: function(res) {
var data = $.parseJSON(res);
var status = data.status;
var message = data.message;
if (status == 'true') {
// $('#myModal').modal('hide');
$('#message').html('');
$('#message').html(message);
$('#message').css('color', "green");
$("loading").hide();
} else {
$('#message').html('');
$('#message').html(message);
$('#message').css('color', "red");
}
}
}).always(function() {
//irrespective of success/error hide it
$("#loading").hide();
});
e.preventDefault();
});
});
Have a loading image like this:
<img src="loader.gif" id="loader" />
And in the script, before the AJAX call, show it:
$("#loader").fadeIn(); // You can also use `.show()`
$.ajax({
// all your AJAX stuff.
// Inside the success function.
success: function (res) {
// all other stuff.
// hide the image
$("#loader").fadeOut(); // You can also use `.hide()`
} // End success
}); // End AJAX
Solution to your Problem
You are missing # in your call:
$("loading").hide();
//-^ Add a # here.
Change it to:
$("#loading").hide();
I'd do it this way:
function loadsth(){
$('#load_dialog').show();
$.ajax({
method: "POST",
url: "?ajax=ajax_request",
data: { data:"test"},
success:function(data) {
$('#load_dialog').hide();
}
});
});
Try using jquery's ajax function beforeSend
$.ajax({
method: "POST",
url: "/url",
data: { data:"test"},
beforeSend: function() {
//SHOW YOUR LOADER
},
success:function(data) {
//HIDE YOUR LOADER
}
});
});
I hope this has given you some idea.
try this its work for u
$.ajax({
url: "<?=base_url('controller/registration_ajax')?>",
type: 'POST',
beforeSend: function(){
$("#loaderDiv").show();
},
success: function(data) {
$('#output-json-inbox').jJsonViewer(data);
$("#loaderDiv").hide();
},
error: function() {
alert("error");
}
});

how to solve this in java script and ajax one Alert show in ajax if value are right

I know this is silly Question but i have occurred this error again and again
My Question is
php script are send me the right data but when i set the if condition in
success:function(data)
data then show me the one alert if i put the right value and wrong value
This is Js Code
function SetTheAmount_man()
{ //Get
var member_id = $('#mem_un_id').val();
// alert(member_id);
$.ajax({
url:"<?php echo
base_url();?>demo_insert.php",
data: {member_id:member_id},
type: "POST",
success:function(data){
//alert(data);
// alert(member_id);
if (data == 'success')
{
alert("123");
}
else
{
alert("456");
}
//window.open('http://www.google.com');
//alert(data);
// $("#secheme_interest_value").html(data);
}
});
}
This is PHP Code demo_insert
if(isset($_POST['member_id']))
{
$mem_un_id=$_POST['member_id'];
$sql_in= mysql_query("select mem_un_id,deleted from phppos_customers where mem_un_id='".$_POST['member_id']."' and deleted='0'");
//$row = mysql_affected_rows($sql_in);
$row=mysql_fetch_array($sql_in);
if($row['mem_un_id']!=''){
echo "success";
}else{
echo "error";
}
//echo $row['mem_un_id'];
}
#Deepak Acharya: Use the datatype in you ajax hit and then check if it helps, try all the datatypes available most likely to use
text
html
json
What is the result of alerting the incoming response?Uncomment this:
//alert(data);
Try to change this:
if(data == 'success')
{
alert("123");
}
else
{
alert("456");
}
to this:
if( data == "success" ) {
alert("123");
}
if( data == "error" ) {
alert("456");
}

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." });
}
}

href is responding thought it is false

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..

Categories

Resources