I need to execute two functionalities: Adding and Deleting a User to/from the database (using Mongoose). However, on execution I get a 200 OK page and a blank username.
Is there an issue with the ajax calls?
I am trying to extract user input from a Form (for adding) and make ajax calls to refresh the updated list.
The code for it is below:
frontend.js
console.log('Frontend Reached');
$(document).ready(function() {
/*$(".delete_user").click(function(){
});*/
var url = '/users/delete_user';
var user_url = '/users/add_user';
function load_users(e) {
$.ajax({
url: 'userview.ejs',
dataType: 'text',
type: 'post',
ContentType: 'application/x-www-form-urlencoded',
data: $('#list').serialize(), //$('#user_form').serialize()
success: function(data, textStatus, jQxhr) {
$('#list').load('userview.ejs #list');
//$('#user_form').submit( load_users );
},
error: function(jqXhr, textStatus, errorThrown) {
console.log(errorThrown);
}
});
e.preventDefault();
}
$('#user_form').on('submit', '#user_form', function(e) {
e.preventDefault();
var user_name = $("#nameinput").val();
var user_age = $("#ageinput").val();
$.ajax({
url: 'userview.ejs',
dataType: 'text',
type: 'post',
ContentType: 'application/x-www-form-urlencoded',
data: {
'user_name': user_name,
'user_age': user_age
},
success: function(data, textStatus, jQxhr) {
$('#user_form').submit(load_users);
load_users();
},
error: function(jqXhr, textStatus, errorThrown) {
console.log(errorThrown);
}
});
e.preventDefault();
}); //onclick
$(document).on('click', '.delete_user', function(e) {
e.preventDefault();
var user_id = $(this).attr('data-id');
//console.log(user_id);
var data = {
user_id: user_id
};
$.ajax({
url: 'userview.ejs',
dataType: 'text',
type: 'post',
ContentType: 'application/x-www-form-urlencoded',
data: {
data
},
success: function(data, textStatus, jQxhr) {
// $('#list').html( data );
load_users();
},
error: function(jqXhr, textStatus, errorThrown) {
console.log(errorThrown);
}
});
e.preventDefault();
}); //onclick delete
}); //document ready
userview.ejs
<meta charset="UTF8">
<link href="javascripts/frontend.js">
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<link rel="stylesheet" href="/stylesheets/userlist.css">
<link href='//fonts.googleapis.com/css?family=Amatic SC' rel='stylesheet'>
<link href='//fonts.googleapis.com/css?family=NTR' rel='stylesheet'>
<html>
<head>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script type="text/javascript" src="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css"></script>
<script>
</script>
<title>Userlist</title>
<script src="javascripts/frontend.js"></script>
</head>
<div class="container-fluid">
<div class="row">
<h1><strong>FORM</strong></h1>
<hr id="hr2" style="border: 6px solid palevioletred">
<div id="black">
<form class="form-horizontal" method="post" action="/users/add_user" id="user_form">
<fieldset>
<!-- Text input-->
<div class="form-group">
<label class="col-md-4 control-label" for="textinput">Name : </label>
<div class="col-md-4">
<input id="nameinput" name="name" placeholder="Enter Username" class="form-control input-md" type="text" value="Name" onfocus="if (this.value=='Name') this.value='';">
</div>
</div>
<!-- Text input-->
<div class="form-group">
<label class="col-md-4 control-label" for="textinput">Age : </label>
<div class="col-md-4">
<input id="ageinput" name="age" placeholder="Enter Age" class="form-control input-md" type="number">
</div>
</div>
<!-- Button -->
<!-- Button (Double) -->
<div class="form-group">
<div class="col-md-8">
<button id="singlebutton" name="button1id" class="btn btn-success"><b>Add User</b></button>
</div>
</div>
</form>
<body>
<h1><strong>USERS</strong></h1>
<hr id="hr1" style="border: 6px solid #7ec4ec;">
<ul id="list" class="triangle">
<!-- Link trigger modal -->
<!-- Modal -->
<div class="modal fade" id="openModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Edit :</h4>
</div>
<div class="modal-body">
<form>
Name:<input type="text" name="modal_username" id="nameId" value="" /> Age:
<input type="number" name="modal_age" id="ageId" value="" />
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
<% for(var i=0; i<userlist.length; i++) {%>
<li>
<%= userlist[i].name %> :
<%= userlist[i].age %> Delete || <a data-toggle="modal" href="#openModal" data-target="#openModal" data-id="<%= userlist[i]._id %>" id="update" title="Update user info"
class="update_user">Update</a></li>
<% } %>
</ul>
</body>
</fieldset>
</div>
</div>
</div>
</html>
This is userController.js
var User = require('../models/usermodel.js');
var userService = require('../services/userService');
var userController = {
add: function(request, response) {
var user_name = request.body.user_name;
var user_age = request.body.user_age;
var newUser = new User({
name: user_name,
age: user_age
});
console.log(newUser);
userService.add(newUser, function(err, added) {
if (err != null) {
response.send(500);
} else {
response.send(200);
}
});
},
delete: function(request, response) {
var userId = request.body.user_id;
userService.delete(userId, function(err, deleted) {
if (err != null) {
response.send(500)
} else {
response.send(200);
}
});
}
};
module.exports = userController;
console.log('Frontend Reached');
$(document).ready(function() {
var url = '/users/delete_user';
var user_url = '/users/add_user';
function load_users() {
$.ajax({
url: 'userview.ejs',
dataType: 'text',
type: 'post',
ContentType: 'application/x-www-form-urlencoded', //not advisable or use html instead
data: $('#list').serialize(), //it should be refer to form tag
success: function(data, textStatus, jQxhr) {
console.log(data);
//#list should be the html wrapper to where you load the response data
$('#list').html(data); //view the response in html
},
error: function(jqXhr, textStatus, errorThrown) {
console.log(errorThrown);
}
});
}
$('#user_form').on('submit', '#user_form', function(e) {
e.preventDefault();
var user_name = $("#nameinput").val();
var user_age = $("#ageinput").val();
$.ajax({
url: 'userview.ejs',
dataType: 'text',
type: 'post',
ContentType: 'application/x-www-form-urlencoded',
data: {
'user_name': user_name,
'user_age': user_age
},
success: function(data, textStatus, jQxhr) {
load_users();
},
error: function(jqXhr, textStatus, errorThrown) {
console.log(errorThrown);
}
});
e.preventDefault();
}); //onclick
$(document).on('click', '.delete_user', function(e) {
e.preventDefault();
var user_id = $(this).attr('data-id');
$.ajax({
url: 'userview.ejs',
dataType: 'json',
type: 'post',
ContentType: 'application/x-www-form-urlencoded',
data: {
user_id: user_id
},
success: function(data, textStatus, jQxhr) {
load_users();
},
error: function(jqXhr, textStatus, errorThrown) {
console.log(errorThrown);
}
});
e.preventDefault();
}); //onclick delete
}); //document ready
Related
I have implemented a Jquery loader in my function which gets call on button click.
Here is the sample code
function fnLoadVendorData() {
var vendorSel = $("#ddlVendorName option:selected").text();
var strCircle = $("#lblRole").text();
// $('#imgLoader').show();
if (vendorSel != "--Select Vendor--" && typeof (vendorSel) != 'undefined') {
$.ajax({
type: "POST",
url: "Ipfee.aspx/GetVendorData",
data: JSON.stringify({ "vendorName": vendorSel, "strCircle": strCircle }),
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
success: function (response) {
if (response.d != "NoDataFound") {
$('#imgLoader').show();
var getDatalist = JSON.parse(response.d);
Create_vendorDataTable(getDatalist);
$('#imgLoader').hide();
} else {
// $('#imgLoader').hide();
jAlert("Data not available !!", "Information");
return false;
}
$('#imgLoader').hide();
},
error: function (response, textStatus, errorThrown) {
// $('#imgLoader').hide();
jAlert(textStatus, "Information");
}
});
}
}
<img src="Images/ipload.gif" id="imgLoader" style="display: none; width: 100%; height: 100%; z-index: 9999;" />
<div class="row">
<div class="col-md-4">
<div class="form-group">
<select name="ddlVendorName" id="ddlVendorName" class="form-control">
<option value="--Select Vendor--">--Select Vendor--</option>
<option value="1032">IPFEE_INDUS</option>
<option value="1028">IPFEE_TVIPL</option>
<option value="1033">IPFEE_ASCEND</option>
<option value="1029">IPFEE_BIL</option>
<option value="1031">IPFEE_GTL</option>
</select>
<label>Vendor Name</label>
</div>
</div>
<div class="col-md-3 filterButton">
<div class="form-group">
<button type="button" class="btn btn-danger button" id="btnFilterClick"><i class="fa fa-filter" aria-hidden="true"></i>Filter</button>
</div>
</div>
</div>
Please suggest what I am doing wrong here.
After searching a lot on internet and other post on stackoverflow, I found that the async call false was making it stop from loading the gif. So I set it to true like below
async : true;
After changing that it worked.
I am using Laravel 6 and i would also like to say that i am not that much experienced working on Laravel.
I have searched SO and google as well but not got any solution to this problem. Below are the files and code
PordController.php
<?php
namespace App\Http\Controllers\Admin;
use Illuminate\Support\Facades\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Prod;
use App\Section;
use Illuminate\Support\Facades\Validator;
class ProdsController extends Controller
{
function __construct () {
$this->middleware('role:admin');
}
public function index(Request $request)
{
$tasks = Prod::orderBy('id', 'desc')->get();
$section = Section::all();
$arr['tasks'] = $tasks;
$arr['sections'] = $section;
return view('admin.pords',$arr);
}
public function store(Request $request)
{
$validator = Validator::make($request->input(), array(
'name' => 'required',
));
if ($validator->fails()) {
return response()->json([
'error' => true,
'messages' => $validator->errors(),
], 422);
}
if ($files = $request->file('fileUpload')) {
$destinationPath = public_path('images'); // upload path
$profileImage = rand() .".". $files->getClientOriginalExtension();
$files->move($destinationPath, $profileImage);
}
$task = Prod::create($request->all());
return response()->json([
'error' => false,
'task' => $task,
], 200);
}
public function show($id)
{
$task = Prod::find($id);
return response()->json([
'error' => false,
'task' => $task,
], 200);
}
public function update(Request $request, $id)
{
$validator = Validator::make($request->input(), array(
'name' => 'required',
));
if ($validator->fails()) {
return response()->json([
'error' => true,
'messages' => $validator->errors(),
], 422);
}
$task = Prod::find($id);
$task->name = $request->input('name');
$task->save();
return response()->json([
'error' => false,
'task' => $task,
], 200);
}
public function destroy($id)
{
$task = Prod::destroy($id);
return response()->json([
'error' => false,
'task' => $task,
], 200);
}
}
prods_add.blade.php
<!-- Add Task Modal Form HTML -->
<div class="modal fade" id="addTaskModal">
<div class="modal-dialog">
<div class="modal-content">
<form id="frmAddTask" enctype="multipart/form-data" method="POST">
<div class="modal-header">
<h4 class="modal-title">
add
</h4>
<button aria-hidden="true" class="close" data-dismiss="modal" type="button">
×
</button>
</div>
<div class="modal-body">
<div class="alert alert-danger" id="add-error-bag">
<ul id="add-task-errors">
</ul>
</div>
<div class="form-group">
<label>
name
</label>
<input class="form-control" id="name" name="name" required="" type="text">
</input>
</div>
<div class="form-group">
<label>
desc
</label>
<input class="form-control" id="desc" name="description" required="" type="text">
</input>
</div>
<div class="form-group">
<label>
member
</label>
<input class="form-control" id="member" name="member" required="" type="number">
</input>
</div>
<div class="row">
<div class="col-md-4">
<div class="form-group">
<label>
isfiles allow
</label>
<input class="form-control" type="checkbox" id="isfile" name="isfile" value="true" checked>
</input>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label>
camera allow
</label>
<input class="form-control" type="checkbox" id="isvideo" name="isvideo" value="true" checked>
</input>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label>
mic allow
</label>
<input class="form-control" type="checkbox" id="ismic" name="ismic" value="true" checked>
</input>
</div>
</div>
</div>
<div class="form-group">
<label>
sections
</label>
<select id="section_id" name="section_id" class="form-control">
#foreach ($sections as $section)
<option value="{{$section->id}}">{{$section->name}}</option>
#endforeach
</select>
</div>
<div class="form-group">
<div class="form-group">
<label for="file"> <div class="btn btn-primary btn-sm float-left">
<span>Choose file</span>
</div></label>
<input style="color:black" type="file" class="form-control-file" id="file" name="fileUpload">
</div>
</div>
</div>
<div class="modal-footer">
<input class="btn btn-default" data-dismiss="modal" type="button" value="cancel">
<button class="btn btn-info" id="btn-add" type="button" value="add">
add
</button>
</input>
</div>
</form>
</div>
</div>
</div>
pords.js
$(document).ready(function() {
$("#btn-add").click(function() {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
var car = 0;
var car1 = 0;
var car2 = 0;
var x = document.getElementById("isfile").checked;
if(x === true){
car = 1;
}
if(document.getElementById("isvideo").checked === true){
car1 = 1;
}
if(document.getElementById("ismic").checked === true){
car2 = 1;
}
console.log($("#file").get(0).files[0]);
var filess = $("#file").get(0).files[0];
$.ajax({
type: 'POST',
url: '/admincp/prods',
data: {
name: $("#frmAddTask input[name=name]").val(),
description: $("#frmAddTask input[name=description]").val(),
display: 1,
sessionid: 'sadasdasdasdasd',
password: 'sadasdasdasdasd',
fileUpload: filess,
img: "path",
member: $("#frmAddTask input[name=member]").val(),
isfile: car,
isvideo: car1,
ismic: car2,
section_id: $("#frmAddTask select[name=section_id]").val(),
},
processData: false,
dataType: 'json',
success: function(data) {
$('#frmAddTask').trigger("reset");
$("#frmAddTask .close").click();
window.location.reload();
},
error: function(data) {
var errors = $.parseJSON(data.responseText);
$('#add-task-errors').html('');
$.each(errors.messages, function(key, value) {
$('#add-task-errors').append('<li>' + value + '</li>');
});
$("#add-error-bag").show();
}
});
});
$("#btn-edit").click(function() {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: 'PUT',
url: '/admincp/prods/' + $("#frmEditTask input[name=id]").val(),
data: {
name: $("#frmEditTask input[name=name]").val(),
},
dataType: 'json',
success: function(data) {
$('#frmEditTask').trigger("reset");
$("#frmEditTask .close").click();
window.location.reload();
},
error: function(data) {
var errors = $.parseJSON(data.responseText);
$('#edit-task-errors').html('');
$.each(errors.messages, function(key, value) {
$('#edit-task-errors').append('<li>' + value + '</li>');
});
$("#edit-error-bag").show();
}
});
});
$("#btn-delete").click(function() {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: 'DELETE',
url: '/admincp/prods/' + $("#frmDeleteTask input[name=id]").val(),
dataType: 'json',
success: function(data) {
$("#frmDeleteTask .close").click();
window.location.reload();
pushnotify('تم الحذف بنجاح ');
},
error: function(data) {
console.log(data);
}
});
});
});
function addTaskForm() {
$(document).ready(function() {
$("#add-error-bag").hide();
$('#addTaskModal').modal('show');
});
}
function editTaskForm(task_id) {
$.ajax({
type: 'GET',
url: '/admincp/prods/' + task_id,
success: function(data) {
$("#edit-error-bag").hide();
$("#frmEditTask input[name=name]").val(data.task.name);
$("#frmEditTask input[name=id]").val(data.task.id);
$('#editTaskModal').modal('show');
},
error: function(data) {
console.log(data);
}
});
}
function deleteTaskForm(task_id) {
$.ajax({
type: 'GET',
url: '/admincp/prods/' + task_id,
success: function(data) {
$("#frmDeleteTask #delete-title").html("Delete Task (" + data.task.name + ")?");
$("#frmDeleteTask input[name=id]").val(data.task.id);
$('#deleteTaskModal').modal('show');
},
error: function(data) {
console.log(data);
}
});
}
The error in js file because without fetching the image value works great
When I add a value the image gets the error
The problem could be here:
$task = Prod::create($request->all());
try to make
public function store(Request $request)
{
dd($request->all());
}
and in network see the response.
also, when you make Prod::create($request->all());
it request everything like __token and so on
//Here is my multipart/form-data form
<form id="addNewRoomForm" enctype="multipart/form-data">
<div class="form-group">
<label for="room_title">Room Title</label>
<input type="text" class="form-control" id="room_title" name="room_title" placeholder="Enter Room Title">
</div>
<div class="form-group">
<label for="room_category">Room Category</label>
<select class="form-control" id="room_category" name="room_category">
<option value=""></option>
<option value="1">Standard Room</option>
<option value="2">Family Room</option>
</select>
</div>
<div class="form-group">
<label for="room-images">Room Images</label>
<div class="input-images"></div><!--Here im using image-uploader.js Plugin By Christian Bayer-->
</div>
<div class="form-group">
<label for="room_description">Room Description</label>
<textarea class="form-control" id="room_description" name="room_description" rows="3"></textarea>
</div>
<button type="submit" class="btn btn-success btn-icon-split" id="addRoomBtn">
<span class="icon text-white-50">
<i class="fas fa-arrow-right"></i>
</span>
<span class="text">Add Room</span>
</button>
</form>
//Here is my ajax form submission for the above form which is working fin
$("#addNewRoomForm").on('submit', function(e){
var process_url = "<?php echo base_url();?>";
e.preventDefault();
var formData = new FormData(this);
$.ajax({
type: 'POST',
url: process_url + 'admin/rooms/process_add_room',
data: formData,
// dataType: 'json',
contentType: false,
cache: false,
processData:false,
beforeSend: function(){
alert("sending...");
},
success: function(msg){
alert(msg)
}
});
});
// but when I using the same code inside the jquery-validation.js submitHandler function, it is showing the "message : Undefined_index: room_title" in alert function. below are the codes showing error:
$('#addNewRoomForm').validate({ // initialize the plugin
rules: {
room_title: {
required: true,
},
room_category: {
required: true,
}
},
messages: {
room_title: {
required: "Please Enter Room Title",
},
room_category: {
required: "Select Room Category",
}
},
highlight: function (input) {
console.log(input);
$(input).addClass('is-invalid');
},
unhighlight: function (input) {
$(input).removeClass('is-invalid');
},
errorPlacement: function (error, element) {
// $(element).parents('.input-group').append(error);
$(element).parents('.form-group').append(error);
},
submitHandler: function (form) {
var process_url = "<?php echo base_url();?>";
// e.preventDefault();
var formData = new FormData(this);
$.ajax({
type: 'POST',
url: process_url + 'admin/rooms/process_add_room',
data: formData,
// dataType: 'json',
contentType: false,
cache: false,
processData:false,
beforeSend: function(){
alert("sending...");
},
success: function(msg){
alert(msg)
}
});
return false;
}
});
I want to submit the multipart/form-data with jquery-validation. I've tried all the ways now want your help.
i am trying to use jquery serialize to pass some values from a form in an ajax post request to my server but the serialize function returns an array full of nulls, the values aren't serialized. i do not understand why the values are not serialized, i added the relevant code, here it is hope someone has an idea:
<div class="modal fade" id="modal_form" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h3 class="modal-title">Contact Form</h3>
</div>
<div class="modal-body form">
<form action="#" id="form" class="form-horizontal">
<input type="hidden" value="" name="id"/>
<div class="form-body">
<div class="form-group">
<label class="control-label col-md-3">first name</label>
<div class="col-md-9">
<input name="first_name" placeholder="first name" class="form-control" type="text">
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">last name</label>
<div class="col-md-9">
<input name="last_name" placeholder="last name" class="form-control" type="text">
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">phone</label>
<div class="col-md-9">
<input name="phone" placeholder="phone" class="form-control" type="text">
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">email</label>
<div class="col-md-9">
<input name="email" placeholder="email" class="form-control" type="text">
</div>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" id="btnSave" onclick="save()" class="btn btn-primary">Save</button>
<button type="button" class="btn btn-danger" data-dismiss="modal">Cancel</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
<script type="text/javascript">
$(document).ready( function () {
$('#table_id').DataTable();
} );
var save_method; //for save method string
var table;
function add_contact()
{
save_method = 'add';
$('#form')[0].reset(); // reset form on modals
$('#modal_form').modal('show'); // show bootstrap modal
//$('.modal-title').text('Add Person'); // Set Title to Bootstrap modal title
}
function edit_contact(id)
{
save_method = 'update';
$('#form')[0].reset(); // reset form on modals
//Ajax Load data from ajax
$.ajax({
url : "<?php echo site_url('index.php/contacts/ajax_edit/')?>/" + id,
type: "GET",
dataType: "JSON",
success: function(data)
{
console.log(data);
$('[name="id"]').val(data.id);
$('[name="first_name"]').val(data.first_name);
$('[name="last_name"]').val(data.last_name);
$('[name="phone"]').val(data.phone);
$('[name="email"]').val(data.email);
$('#modal_form').modal('show'); // show bootstrap modal when complete loaded
$('.modal-title').text('Edit Contact'); // Set title to Bootstrap modal title
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error get data from ajax');
}
});
}
function save()
{
var url;
if(save_method == 'add')
{
url = "<?php echo site_url('contacts/contact_add')?>";
}
else
{
url = "<?php echo site_url('contacts/contact_update')?>";
}
// ajax adding data to database
$.ajax({
url : url,
type: "POST",
data: $("#form").serialize(),
dataType: "JSON",
contentType: 'application/json; charset=utf-8',
success: function(data)
{
console.log(data);
e.preventDefault();
//if success close modal and reload ajax table
$('#modal_form').modal('hide');
location.reload();// for reload a page
},
error: function (jqXHR, textStatus, errorThrown)
{
console.log(errorThrown);
alert('Error adding / update data');
}
});
}
function delete_contact(id)
{
if(confirm('Are you sure delete this data?'))
{
// ajax delete data from database
$.ajax({
url : "<?php echo site_url('index.php/contacts/contact_delete')?>/"+id,
type: "POST",
dataType: "JSON",
success: function(data)
{
location.reload();
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error deleting data');
}
});
}
}
</script>
.serialize() does not produce JSON it produces application/x-www-form-urlencoded. Setting the content type as JSON is wrong just dont set the content type and jQuery will set it as application/x-www-form-urlencoded for you.
$.ajax({
url : url,
type: "POST",
data: $("#form").serialize(),
dataType: "JSON",
// remove contentType: 'application/json; charset=utf-8',
success: function(data)
{
console.log(data);
//e.preventDefault();
//if success close modal and reload ajax table
$('#modal_form').modal('hide');
location.reload();// for reload a page
},
error: function (jqXHR, textStatus, errorThrown)
{
console.log(errorThrown);
alert('Error adding / update data');
}
});
Also, I don't know what you expect e.preventDefault(); in the success handler to do but its definitely not doing it.
Today I'm trying Web Api 2 Login and Register Actions. I'm using Standard Template from Visual Studio 2015. I created JavaScript Client on web side, but I do not see alerts and registration is not working.
Here is my code:
<div class="form-group">
<div class="input-group">
<input type="email" class="form-control" placeholder="Email" id="email">
</div>
</div>
<div class="form-group">
<div class="input-group">
<input type="password" class="form-control" placeholder="password" id="password">
</div>
</div>
<div class="form-group">
<div class="input-group">
<input type="password" class="form-control" placeholder="Password again" id="confirmpassword">
</div>
</div>
<div class="form-group">
<div class="input-group">
<input type="submit" id="submit" value="Register" class="btn btn-info">
</div>
#section scripts{
#Scripts.Render("~/bundles/jqueryval")
<script>
$(function () {
$('#submit').click(function (e) {
e.preventDefault();
var data = {
Email: $('#email').val(),
Password: $('#password').val(),
ConfirmPassword: $('#confirmpassword').val()
};
$.ajax({
type: 'POST',
url: '/api/Account/Register',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(data)
}).success(function (data) {
alert("Registration success");
}).fail(function (data) {
alert("Error message");
});
});
})
</script>
}
Update:
Here is code for login process:
div class="userInfo" style="display:none;">
<p>You are loged in as: <span class="userName"></span></p>
<input type="button" value="Log out" id="logOut" />
</div>
<div class="loginForm">
<h3>Log in</h3>
<label>Enter email</label><br />
<input type="email" id="emailLogin" /> <br /><br />
<label>Password</label><br />
<input type="password" id="passwordLogin" /><br /><br />
<input type="submit" id="submitLogin" value="Log in" />
</div>
#section scripts{
<script type="text/javascript">
$(function () {
//...........................
var tokenKey = "tokenInfo";
$('#submitLogin').click(function (e) {
e.preventDefault();
var loginData = {
grant_type: 'password',
username: $('#emailLogin').val(),
password: $('#passwordLogin').val()
};
$.ajax({
type: 'POST',
url: '/Token',
data: loginData
}).success(function (data) {
$('.userName').text(data.userName);
$('.userInfo').css('display', 'block');
$('.loginForm').css('display', 'none');
// store sessionStorage auth token
sessionStorage.setItem(tokenKey, data.access_token);
console.log(data.access_token);
}).fail(function (data) {
alert('Error on login');
});
});
$('#logOut').click(function (e) {
e.preventDefault();
sessionStorage.removeItem(tokenKey);
});
})
</script>
}
Update 2
On registration here is F12 console code:
(index):88 Uncaught TypeError: $.ajax(...).success is not a function
at HTMLInputElement.<anonymous> ((index):88)
at HTMLInputElement.dispatch (jquery-3.1.1.js:5201)
at HTMLInputElement.elemData.handle (jquery-3.1.1.js:5009)
(anonymous) # (index):88
dispatch # jquery-3.1.1.js:5201
elemData.handle # jquery-3.1.1.js:5009
But registration passes and I have new record in database. Can anyone explain me what does it mean?
do it like this :
$.ajax({
type: 'POST',
url: '/api/Account/Register',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(data)
success: function(html){
alert("Registration success");
}
});
Well, I found that I've used submit type button, it's first misstake - if I want operate request using jquery I've use type="button" instead submit.
Another moment is that json properties is not difined in right case:
var data = {
email: $('#email').val(),
password: $('#password').val(),
confirmPassword: $('#confirmpassword').val()
};
this will be correct
Now about error in console: correct is like #Mustapha answered
for example:
$.ajax({
type: "GET",
url: "/api/rooms",
success: function (rooms) {
}
});
Here is fixed ajax code:
$.ajax({
type: 'POST',
url: '/Token',
data: loginData
success: function(data) {
$('.userName').text(data.userName);
$('.userInfo').css('display', 'block');
$('.loginForm').css('display', 'none');
// store sessionStorage auth token
sessionStorage.setItem(tokenKey, data.access_token);
console.log(data.access_token);
},
error: function (data) {
alert('Error on login');
});
});
Here is, but I've done it using angular :)
Thanks.