Ajax form data not saved in database - javascript

I am trying to save user input into database using Ajax in Laravel-5.2.
This is my route.php
Route::get('xxxxx/{task_id?}',function($task_id){
$task = App\XXXXX::find($task_id);
return response()->json($task);
});
Route::put('xxxxx/{task_id?}',function(Request $request,$task_id){
$task = App\XXXXX::find($task_id);
$task->Name = $request->Name;//
$task->Email = $request->Email;
$task->Telephone = $request->Telephone;
$task->save();
return response()->json($task);
});
In my view, the save button is used as.
<div class="modal-footer">
<button type="button" class="btn btn-primary" id="btn-save" value="update">Save changes</button>
<input type="hidden" id="task_id" name="task_id" value="0">
</div>
my js file created using this tutorial..
I am getting the popup, Save button is not working.What is the wrong here? I m new for Ajax.
Thanks in advance.

This is route.php
Route::match(['get','post'], 'my/save-data','MyController#SaveData');
This is your html:
Save changes
This is your Controller file: MyController.php
public function SaveData( Request $request )
{
$input = $request->all();
try{
// You can now use the Subscribe model without its namespace
// as you referenced it by its namespace in a use statement.
$subscribe = new Subscribe();
// If you want to use a class that is not referenced in a use
// statement then you must reference it by its full namespace.
$otherModel = new \App\Models\Other\Namespace\OtherModel();
$otherModel = $input['Name'];
$otherModel = $input['Email'];
$otherModel = $input['Telephone'];
// save
$otherModel->save();
}
catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e)
{
\Log::error( $e->getMessage(), $context );
}
catch (Exception $e){
\Log::error( $e->getMessage(), $context);
}
return response()->json( ['status'=>'success', 'message'=>'Completed successfully'] );
}
This is your Js file:save.js
function save() {
getData = {
name: "value", // from get eliment
email: "value", // from get eliment
telephone: "value" // from get eliment
};
$.ajax({
type: 'post', // POST Request
url: 'localhost/my/save-data', // localhost/my/save-data // Url of the Route (in this case user/save not only save)
data: getData, // Serialized Data
beforeSend: function (xhr) {
// Function needed from Laravel because of the CSRF Middleware
var token = $('meta[name="csrf_token"]').attr('content');
if (token) {
return xhr.setRequestHeader('X-CSRF-TOKEN', token);
}
},
success: function (data) {
// Successfuly called the Controler
// Check if the logic was successful or not
if (data.status == 'success') {
console.log('alles ok');
} else {
console.log(data.msg);
}
},
error: function (data) {
// Error while calling the controller (HTTP Response Code different as 200 OK
console.log('Error:', data);
}
});
}

Related

How to make a post request without form and without getting error 400

I'm sending a post request without a form in asp.net. I'm getting error 400.
AJAX
function deteleCategorieBtn(id) {
if (confirm("Are you sure you want to delete ?")) {
$.ajax({
type: "POST",
url: 'categories/delete/' + id,
success: function () {
var dataTable = $('#kt_datatable').DataTable();
dataTable.ajax.reload(null, false);
},
error: function (request, error) {
console.log(request, error);
}
})
}
CONTROLLER
// POST: Categories/Delete/5
[Route("delete/{id?}")]
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Delete(int id)
{
var category = await _context.Categories
.FirstOrDefaultAsync(m => m.Id == id);
if(category != null){
_context.Categories.Remove(category);
await _context.SaveChangesAsync();
}
else
{
return Json(new { error = true, messages = "Categorie doesn't exist" }, new Newtonsoft.Json.JsonSerializerSettings());
}
return Json(new { success = true, messages = "Registered well" }, new Newtonsoft.Json.JsonSerializerSettings());
}
}
On the console, the url is correct
I tried changing the type from POST to DELETE in ajax part, and HttpPost to HttpDelete - Didn't work
I used the very same controller code successfully with a form that looks like that :
<form asp-action="Delete" asp-route-id="#item.Id" onclick="return confirm('Are you sure you want to delete ? ?');">
<button type="submit" value="Delete" class="btn btn-sm btn-clean btn-icon"></button>
</form>
EDIT :
Found this error message :
System.InvalidOperationException: The provider for the source IQueryable doesn't implement IDbAsyncQueryProvider. Only providers that implement IDbAsyncQueryProvider can be used for Entity Framework asynchronous operations.
You need to add an Antiforgery token while doing the ajax post.
Add an antiforgerytoken like below in your page
#Html.AntiForgeryToken()
This will be added in a hidden input field
While doing the ajax post, send the token like below
$.ajax({
type: "POST",
url: 'categories/delete/' + id,
beforeSend: function (xhr) {
xhr.setRequestHeader('XSRF-TOKEN',
$('input:hidden[name="__RequestVerificationToken"]').val());
},
success: function () {
var dataTable = $('#kt_datatable').DataTable();
dataTable.ajax.reload(null, false);
},
error: function (request, error) {
console.log(request, error);
}
});

Asynchronous Add/Update save method not updating

I am building a .NET page for a project that adds a new City and State for a new user or updates the City and state if their ID is already in the database. Everything is working fine except for the fact that if a past user clicks submit to update their information, an entirely new entry is added to the database.
I have created the method already in the repository listed below.
public async Task<LocationViewModel> SaveLocationAsync(LocationViewModel model)
{
try
{
var location = new Location()
{
City = model.City,
State = model.State
};
if (model.Id != 0)
{
location.Id = model.Id;
}
_dbcontext.Location.AddOrUpdate(location);
await _dbcontext.SaveChangesAsync();
return model;
}
catch (Exception ex)
{
model.Error = true;
model.ErrorMessages = new List<string>()
{
string.Format("Something went wrong - Message: {0} \n Stack Trace: {1}", ex.Message,
ex.StackTrace)
};
return model;
}
}
I have also built a controller that saves and updates existing records asynchronously shown below.
[System.Web.Mvc.AllowAnonymous]
[System.Web.Http.HttpPost]
public async Task<LocationViewModel> SaveLocationApiAsync(LocationViewModel model)
{
var result = new LocationViewModel();
if (ModelState.IsValid)
{
result = await _locationRepository.SaveLocationAsync(model);
}
return result;
}
In addition, I have added added all of my routes and references.
Why is a new entry put in the database instead of the current one updating? The Javascript is shown below.
self.Submit = function () {
if (self.errors().length !== 0) {
self.errors.showAllMessages();
return;
}
if (isNumber(locationId)) {
self.Location().LocationId(locationId);
swal("Success", "Thank you for your submission \nYour information has been updated.", "success");
}
var newData = ko.mapping.toJSON(self.Location());
var url = "/Admin/SaveLocationApiAsync/Post/";
$.ajax({
url: url,
method: "POST",
data: newData,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (result) {
if (result.Error === true) {
swal("Error", result.ErrorMessages.join('\n'), "error");
} else {
//TOdo
}
},
error: function () {
swal("Error", "Something went wrong.\nPlease contact help.", "error");
}
});
};
I apologize if it is a lot. I have checked everything repeatedly and have fixed all bugs. I am out of ideas.
Thanks in advance.
Your url looks to the controller action seems incorrect. You have var url = "/Admin/SaveLocationApiAsync/Post/"; when it should be var url = "/Admin/SaveLocationApiAsync";
Another approach to getting the correct url would be:
var url = '#Url.Action("SaveLocationApiAsync", "<ControllerName>")';
Also, in your ajax error handler you can get the HTTP status code and error message, which would help.
error: function (jqXHR, textStatus, errorThrown) {
swal("Error", "Something went wrong.\nPlease contact help.", "error");
}
EDIT:
I should have prefaced that using Url.Action works when your JavaScript is in a view (assuming Razor view in this case).
Fiddler is great tool to use when debugging ajax calls.

Symfony2 Save Form Data via Ajax

I have a form in Symfony that needed to be submitted via ajax call. I worte the code but it's not saving any data in db but also doesn't give/show any error.
send_dict = {
type: 'POST',
url: $(this).attr('action'),
processData: true,
data: $('#Form').serialize(),
beforeSend: function(request) {alert('before send');},
success: function (data) {alert("success")},
error: function(xhr, textStatus, thrownError) {
alert('Some Thing Went Wrong, Please Refresh and Try Again...');
}
}
$.ajax(send_dict);
public function createAction(Request $request)
{
$user = $this->getUser();
$address = new Addresses();
if($request->isXmlHttpRequest()) {
// Do something...
if ($request->isMethod('POST')) {
$request = $this->get('request');
$permanent_is_present = $request->get('permanent_is_present');
$present_address = $request->get('present_address');
$present_address_country = $request->get('present_address_country');
// Persisting Objects to the Database
if($permanent_is_present==true){
$address->isIsPresent(true);
$address->isIsPermanent(true);
}else{
$address->isIsPresent(true);
}
$address->setUser($user);
$address->setStreet1($present_address);
$address->setCountry($present_address_country);
$address->setState($present_address_state);
$address->setCity($present_address_city);
//exit(\Doctrine\Common\Util\Debug::dump($address));
// Entity Manager To Get Connected with Doctrine
$em = $this->getDoctrine()->getManager();
// Persists the entire objects....
$em->persist($address);
// Flush queries into database
$em->flush();
$output = array();
$response = new Response();
$output[] = array('success' => true);
$response->headers->set('Content-Type', 'application/json');
$response->setContent(json_encode($output));
return $response;
}else{
return $this->render('AddressBundle:Addresses:new.html.twig');
}
} else {
return $this->redirect($this->generateUrl('address_new'));
}
}
both alerts in before send and success on ajax function are showing. but the data is not saved in the database? New to symfony, also don't know how to trace/debug this?
UPDATE:
One more thing i notice that there is no user login in the system, and em trying to made ajax calls. and it is sending to controller and because user id is not found so it is not saving into database
You need to serialize form data. Give your form an Id attribute then:
data: $('#Form').serialize(),

How to serialize forms and post using jQuery Ajax

I'm trying to remove records from my DB......
this is how my form looks like.........
#using (Html.BeginForm("RemoveDoctor", "Doctor", FormMethod.Post, new { #id = "form" }))
{
#Html.AntiForgeryToken()
#Html.HiddenFor(model => model.Id)
#Html.HiddenFor(model => model.Name)
<div class="form-actions no-color">
<input type="submit" value="Delete" class="btn btn-default" id="submit" /> |
</div>
}
I'm trying to get these records from the view and pass to my controller Action method............................. i'm trying to serialize this form and send it to that action method as following...................
var jsonObj = $('#form').serialize();
it serialize the form put my Ajax POST function wont run with that result......
it just gives me an error!!!!................. I just need to pass that serialize value to my Action method............... This is how my Script looks like.....................
$('#submit').click(function () {
var jsonObj = $('#form').serialize();
alert(jsonObj);
$.ajax({
type: "POST",
url: '../Doctor/RemoveDoctor',
data: JSON.stringify({ "doctor": jsonObj }),
success: function (data) {
alert(data.Message);
},
error: function () {
alert("Error!!!");
}
});
return false;
});
This is how my action method looks like....................
public ActionResult RemoveDoctor(DoctorModel doctor)
{
bool confirmationResult = doctorManager.RemoveDoctor(doctor.Id);
string displayMessage = string.Empty;
if (confirmationResult == true)
displayMessage = "You have successfully removed your record!!";
else
displayMessage = "Error!! Some Thing Went Wrong, Please Try Again!!";
return Json(new { Message = displayMessage });
}
I'm trying to send this 'displayMessage' to my jQuery code........ please some give me an idea how to solve this....... thanks!!!!!
Try this
$.ajax({
type: "POST",
url: '../Doctor/RemoveDoctor',
data: $('#form').serialize(),
success: function (data) {
alert(data.Message);
},
error: function () {
alert("Error!!!");
}
});
It will serialize your form.
Use only $('#form').serialize() for serialization.
Edit
If you don't want to refresh page then you should use type="button" instead type="submit"
And
You should do this also
[HttpPost]
public ActionResult RemoveDoctor(DoctorModel doctor)
{
//...................
return Json(new { Message = displayMessage } , JsonRequestBehavior.AllowGet);
}
And change ajax error function to this (For getting error )
error: function(jqXHR, textStatus, errorThrown)
{
alert("Error: "+errorThrown+" , Please try again");
}

Catching data in controller

I have a question about javascript and cakephp, I need to send data via Post and recive it in the other side (the controller) and make the normal process that I already have. But I don't know how can I catch the data. I'm working with Ajax
function editFun(clicked_id){
var id = clicked_id;
$("#Content").empty();
$('#Content').html("<b>Loading response...</b>");
$.ajax({
type: 'POST',
url: '/Posts/edit',
data: (id)
})
.done(function(data){
console.log(data);
$('#Content').html(data);
})
.fail(function(data){
$('#Content').html(data);
});
}
public function edit($id = null) {
if (!$id) {
throw new NotFoundException(__('Invalid post'));
}
$post = $this->Post->findById($id);
if (!$post) {
throw new NotFoundException(__('Invalid post'));
}
if ($this->request->is(array('post', 'put'))) {
$this->Post->id = $id;
if ($this->Post->save($this->request->data)) {
$this->Session->setFlash(__('Your post has been updated.'));
return $this->redirect(array('action' => 'index'));
}
$this->Session->setFlash(__('Unable to update your post.'));
}
if (!$this->request->data) {
$this->request->data = $post;
}
}
In that case you should send your id in URL. So even GET method is enough, because you controller receive $id param from URL.
So all what you need to change are post arguments:
$.ajax({
type: 'POST',
url: '/Posts/edit/' + id
})

Categories