user3253289
user3253289

Reputation: 63

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,                 
    )    
);

}

Upvotes: 0

Views: 55

Answers (2)

Sid
Sid

Reputation: 1144

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.

Upvotes: 1

Muhammad Ali
Muhammad Ali

Reputation: 2014

use json format for data instead or query string

 data = {"action":action,"item_id":id};

Upvotes: 0

Related Questions