0

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

8
  • 1
    I am in laravel 5, so maybe this won't work for you, but I send the JSON response back using return Response::json(array('successMessage' => 'Success', 'payload' => $response));. Also can you put logs inside your controller so that we can be sure its a problem in client side, not the server side. Also if your button .edit_button is submitting some form, you might want to do e.preventDefault() function before you send the ajax request. Do the above steps and let me know what the results were Commented Jun 29, 2015 at 2:51
  • 1
    laravel comes with a log facade. Look into your app.php inside config folder. There must be a facade named Log. In your controller at the top write use Illuminate\Support\Facades\Log and wherever you want to log just write Log::error("some log"); This is in laravel 5. Dont know about 4 but will check if you can't find it. Commented Jun 29, 2015 at 3:22
  • 1
    Also you mentioned earlier that you get 500 Error when you executed my code. Can you specify the reason why? Maybe you forgot to define $response and hence the error. Commented Jun 29, 2015 at 14:17
  • 1
    Hi. Check my answer. Hope you like it. If there is anything else, let me know. :) Commented Jun 30, 2015 at 2:47
  • 1
    Let us continue this discussion in chat. Commented Jun 30, 2015 at 3:43

2 Answers 2

1

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"];
Sign up to request clarification or add additional context in comments.

1 Comment

hm wait a minute...get a little confused i will update my question
1

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

1 Comment

please see my extended question

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.