jquery serialize yields an empty array - javascript

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.

Related

Ajax JQuery request doesn't get sent

It used to work fine, and I don't remember changing anything in these files, but now nothing happens when I click on submit form. What may cause the problem?
Snippet:
// And here's the ajax request file *auth_ajax.js*:
$(function() {
$('form').on('submit', function(e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'check_user.php',
dataType: 'json',
data: $('form').serialize(),
success: function(response) {
if (response['found'] === 'true') {
location.href = 'index.php';
} else {
alert('Incorrect username or password');
}
},
error: function(jqXHR, textStatus, errorThrown) {
alert(errorThrown);
}
});
});
});
<!-- Here's my php file: -->
<h1 id="header">Enter your data here</h1>
<form>
<label for="login">Login</label>
<input type="text" id="login" name="login" placeholder="Enter your login here" required><br>
<label for="password">Password</label>
<input type="password" id="password" name="password" placeholder="Enter your password here" required><br>
<input type="submit" value="Log in">
</form>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
This route work?
url: 'check_user.php',
Try yourDomain/check_user.php, check your directory for a real path

Refresh a list using AJAX after adding/deleting a user

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

Web Api 2 Login and Register Actions, JavaScript problems

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.

MailChimp Ajax Integration

I am trying to custom mailchimp signup form.
I want to the form not got to the mailchimp landing page, after the form submit. I want it reload the form and display the message, if the submission success or failed.
I have tried what have been discussed on https://stackoverflow.com/a/15120409, but it is failed.
This my html & javascript for the form :
//newsletter -start
var $form = $('#mc-embedded-subscribe-form');
if ( $form.length > 0 ) {
$('form button[type="submit"]').bind('click', function ( event ) {
if ( event ) event.preventDefault();
register_newsletter($form);
return false;
});
}
function register_newsletter($form) {
$.ajax({
type: $form.attr('method'),
url: $form.attr('action'),
data: {EMAIL:.find('#mce-EMAIL').val()},
//data: $form.serialize(),
cache : false,
dataType : 'json',
contentType: "application/json; charset=utf-8",
error : function(err) { alert("Could not connect to the registration server. Please try again later."); },
success : function(data) {
if (data.result == "success") {
$( "#mc-embedded-subscribe-form .form-group, #mc-embedded-subscribe-form button" ).remove();
$( "#mc-embedded-subscribe-form" ).append('<p>Pendaftaran Anda berhasil.</p>');
} else {
$( "#mc-embedded-subscribe-form .form-group, #mc-embedded-subscribe-form button" ).remove();
$( "#mc-embedded-subscribe-form" ).append('<p>Pendaftaran anda <strong>gagal</strong>.</p>');
}
}
});
}
//newsletter -end
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="form-sub">
<div class="row">
<div class="col-md-24 col-sm-24 col-xs-24">
<div id="mc_embed_signup">
<p><strong>Daftar & Dapatkan VOUCHER 75,000<br/>serta penawaran spesial dari MatahariMall</strong></p>
<form action="http://mataharimall.us10.list-manage.com/subscribe/post-json?u=ce402de87bc4303ab82a36695&id=912ec37292&c=?" class="form-search-opps" id="mc-embedded-subscribe-form" method="post" name="mc-embedded-subscribe-form" novalidate="" role="search" target="_blank">
<div class="form-group">
<input class="form-control" id="mce-EMAIL" name="EMAIL" placeholder="Masukkan email Anda di sini" type="text" value="" />
</div>
<button class="btn btn-red pria" id="mce-GENDER-0" name="GENDER" type="submit" value="Pria">Pria</button>
<button class="btn btn-red wanita" id="mce-GENDER-1" name="GENDER" type="submit" value="Wanita">wanita</button>
</form>
</div>
</div>
</div>
</div>
If success, mailchimp will produce this :
?({"result":"success","msg":"Almost finished... We need to confirm your email address. To complete the subscription process, please click the link in the email we just sent you."})
If failed, mailchimp will produce this :
?({"result":"error","msg":"0 - An email address must contain a single #"})

JQuery Ajax - File and Data Upload

I am trying to create a form which uploads data and an image in the same submission. I've look all over and I can only seem to find people that are having trouble to upload files alone with JQuery. If I make content-type false then the data dosen't go through only the file. Here is the code:
<form action="/secret/includes/add_listing.php" id="listingfrm" name="listingfrm" action="javascript:;" enctype="multipart/form-data" method="post" accept-charset="utf-8">
<div>
<label for="title">Title</label>
<div class="right">
<div class="row">
<div class="col-cst-1">
<input type="text" name="title">
</div>
</div>
</div>
</div>
<div>
<label for="content">Description</label>
<div class="right">
<div class="row">
<div class="col-cst-1">
<textarea name="content" rows="5"></textarea>
</div>
</div>
</div>
</div>
<div>
<label for="image">Upload a Thumbnail</label>
<!-- Browse to Upload Image (No more than 1MB) -->
<div class="right">
<div class="row">
<div class="col-cst-1">
<input type="file" name="listing_thumb" id="listing_thumb">
</div>
</div>
</div>
</div>
<input type="submit" value="Submit">
</form>
function ajax(url, type, data) {
var request
if (type != "none") {
request = $.ajax({
url: url,
type: type,
data: data,
});
} else {
request = $.ajax({
url: url
});
}
return request;
}
$(document).ready(function() {
$(document).on("submit", "#listingfrm", function(event) {
event.preventDefault();
var form = $(this);
var inputs = GetInputs(form);
var serializedForm = form.serialize();
inputs.prop("disabled", true);
var request = ajax("includes/add_post.php", "post", serializedForm)
request.done(function(response, textStatus, jqXHR) {
console.log(response)
})
request.fail = ajax(function(jqXHR, textStatus, errorThrown) {
console.error("Login Error: " + textStatus + " : " + errorThrown)
})
request.always(function() {
inputs.prop("disabled", false);
})
});
});
When using this the title and the description don't go through to the PHP file however if I don't then the image dosen't.

Categories