Surya Matadewa
Surya Matadewa

Reputation: 1027

Simple ajax in laravel 4

i have following code

ajax

 //ajax edit button
 $('.edit_button').on('click', function(e) {
    e.preventDefault();
    var id_produk = $(this).attr('id');
    $.ajax({
        type : "POST",
        url : "editproduk",
        data : id_produk,
        dataType: 'JSON',
        success : function(data) {
           alert('Success');
           console.log(data);
        },
        error: alert('Errors')
    });
});

i always get messagebox error
and don't know where i'm missing,
because in chrome - inspect element - console not give any clue

my route

Route::post('/account/editproduk', array(
    'as' => 'edit-produk-post',
    'uses' => 'AccountController@postEditProduk'
));

my controller

public function postEditProduk() {
    if (Request::ajax()) {
        return "test test";
    }
}

extended question
i running my script well after using return Response::json() like this

$id_produk = Input::get('id_produk');
$produk = Produk::findOrFail($id_produk);
return Response::json($produk);

and access it in view by this script

success : function(data) {
    alert('Success');
    console.log(data["name-produk"]);
}

but if i want to return array json like

$id_produk = Input::get('id_produk');
$produk = Produk::findOrFail($id_produk);
$spesifikasi = SpesifikasiProduk::where('id_produk', '=', $id_produk);
return Response::json(array($produk, $spesifikasi));

i can't access it in view like this...

success : function(data1, data2) {
    alert('Success');
    console.log(data1["name-produk"] - data2["title-spek"]);
}

how to access json array


extended question update

if i'm wrong please correct my script because i get a litle confused with explenation

is this correct way to return it?

Response::json(array('myproduk' => 'Sproduk', 'data2' => 'testData2'));

result

console.log(produk["myproduk"]);
--------------------------------
Object {id_produk: 1, nama_produk: "produk1", deskripsi: "desc_produk" 


console.log(produk["data2"]);
--------------------------------
testData2

and i still don't have idea how to print nama_produk in my_produkarray

Upvotes: 0

Views: 105

Answers (2)

Rash
Rash

Reputation: 8197

Question 1:

Why is this code not sending JSON data back.

public function postEditProduk() {
    if (Request::ajax()) {
        return "test test";
    }
}

Answer: Because this is not the right way to send the JSON data back. From the Laravel 4 docs, the right way to send JSON data back is linked. Hence the correct code becomes:

public function postEditProduk() {
    if (Request::ajax()) {
        return Response::json("test test");
    }
}

Question 2: Why am I not able to access the data in data1 and data2

success : function(data1, data2) {
    alert('Success');
    console.log(data1["name-produk"] - data2["title-spek"]);
}

Answer: Because this is not the right way to catch the JSON data. The right way to send is given in the Laravel 4 API reference docs.

static JsonResponse json(string|array $data = array(), int $status = 200, array $headers = array(), int $options)

As you can see the method json takes string or array as the first parameter. So you need to send all your data in the first parameter itself (which you are doing). Since you passed only one parameter, you have to catch only 1 parameter in your javascript. You are catching 2 parameters.

Depending on what $produk and $spesifikasi is, your data will be present in one single array. Lets say that $produk is a string and $spesifikasi is an array. Then your data on the javascript side will be this:

[
    [0] => 'value of $produk',
    [1] => array [
        [0] => 'value1',
        [1] => 'value2'
    ]
]

It would be best if you print the log your entire data and know the structure. Change your code to this:

success : function(data) {
    console.log(data.toString());
}

This will print your entire data and then you can see the structure of your data and access it accordingly. If you need help with printing the data on your console, google it, or just let me know.

I sincerely hope that I have explained your doubts clearly. Have a nice day.

Edit

extended question answer: Replace this line:

$spesifikasi = SpesifikasiProduk::where('id_produk', '=', $id_produk);

With this:

$spesifikasi = SpesifikasiProduk::where('id_produk', '=', $id_produk)->get();

Without calling the get() method, laravel will not return any value.

Then access your data in javascript like this:

console.log(JSON.stringify(data));

This way you will get to know the structure of your data and you can access it like:

data[0]["some_key"]["some_other_key"];

Upvotes: 1

Amin
Amin

Reputation: 599

In your controller you're returning text while your ajax request awaits json data, look at these lines of codes, I think you should get your answer:

if(Request::ajax()) {
        $province = Input::get('selectedProvince');
        //Get all cites for a province
        if ($cityList = City::where('province_id','=', $province)) {
            return Response::make($cityList->get(['id', 'name']));
        }
        return Response::json(array('success' => false), 400);
    }

Upvotes: 1

Related Questions