mercredi 26 juillet 2017

Ajax call, displaying a json response instead of success?

I have a form with a clickevent on submit button like this:

           <div class="col-md-6 col-md-offset-4" id="submit_div">
             <button type="submit" id="submit" class="btn btn-warning" onclick="entity();">
                       Update Entity
              </button>
           </div>

and ajax:

$(document).ready(function() {
function entity() {
    $.ajax({
        url: 'entity/create/add',
        type: 'post',
        dataType: 'JSON',
        success: function(data) {
            $('#submit_div').html('<button type="button" class="btn.btn-success"><a href="/profile/entity/edit/'+data+'">Edit</a></button')

controller:

public function store(EntityRequestCreate $request)
    {
        $geoloc = new Geoloc;
        $geoloc->lat = $request->input('lat');
        $geoloc->lng = $request->input('lng');
        $geoloc->slug = $request->input('name');
        $geoloc->save();

        $user_id = Auth::id();
        $entity = new Entity;
        $entity->name = $request->input('name');
        $entity->type = $request->input('type');
        $entity->email = $request->input('email');
        $entity->tags = $request->input('tags');
        $entity->_geoloc()->associate($geoloc);
        $entity->save();

        $entity_id = $entity->id;

        $address = new Address;
        $address->building_name = $request->input('building_name');
        $address->address = $request->input('address');
        $address->town = $request->input('town');
        $address->postcode = $request->input('postcode');
        $address->telephone = $request->input('telephone');
        $address->entity_id = $entity_id;
        $address->save();

        $role = User::find($user_id);
        $role->role = "2";
        $role->save();

        DB::table('entity_user')->insert(array('entity_id' =>  $entity_id, 'user_id' => $user_id));

        $result = $geoloc->save();
        $result2 = $entity->save();
        $result3 = $address->save();
        $result4 = $role->save();

        if($result && $result2 && $result3 && $result4) {
            $data = $entity_id;
        }else{
            $data = 'error';
        }
        return response()->json(['results' => $data]);
    }
            },
            error: function(data) {
                alert("Oh no!");
            },
            headers: {
            'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
            }
        });
    }
    });

and route::

Route::post('entity/create/add', 'EntityController@store');

Everything seems to work, there are no errors but instead of a button from success(data) i get the actual response:

{
"results": 112
}

But I don't even know why it is happening can someone please help me? form doesn't have any action and it looks like ajax is not being called?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire