How to change view in Knockout JS - javascript

i have a short question. I am using Knockout JS and having this view and ViewModel:
var LoginViewModel = function () {
var self = this;
self.userName = ko.observable();
self.userPassword = ko.observable();
self.signin = function () {
data = ko.toJSON(self);
$.ajax({
url: "/signin",
type: "post",
data: ko.toJSON(self),
contentType: "application/json",
success: function (data, textStatus, xhr) {
alert(xhr.status);
// If status == 200(OK) change view
},
error: function (jqXHR, textStatus, errorThrown) {
alert("failure");
}
});
}
}
ko.applyBindings(new LoginViewModel());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.0/knockout-min.js"></script>
<div class="container">
<div class="col-md-4 col-md-offset-4" data-bind="visible: isVisible">
<div class="panel panel-default">
<div class="panel-heading" style="text-align: center;">
<strong class="">SEHA</strong>
</div>
<div class="panel-body">
<form class="form-horizontal">
<div class="form-group">
<label for="username" class="col-sm-3 control-label">Name</label>
<div class="col-sm-9">
<input class="form-control" required="" type="text" data-bind="value: userName">
</div>
</div>
<div class="form-group">
<label for="password" class="col-sm-3 control-label">Password</label>
<div class="col-sm-9">
<input class="form-control" required="" type="password" data-bind="value: userPassword">
</div>
</div>
<div class="form-group last">
<div class="col-sm-offset-3 col-sm-9">
<button class="btn btn-success btn-sm" data-bind="click: signin">Sign in</button>
</div>
</div>
</form>
</div>
<div class="panel-footer">
~
</div>
</div>
</div>
</div>
I want now to change the "view" if the user logs in. How can i accomplish that?
I also would to like to select a new view model for the next view. How would i do that?
That are my first steps with javascript / knockout, so please be kind.

If you handle the Server part of your application, you might want to return a Redirect Code 301 and specifying the URL to redirect.
Else, you can handle this Client Side, with the javascript code:
window.location.replace("./Home.html");

Related

ajax submit multiple times

I have created an application in the php, I am using the bootstrap model to update user details using AJAX. Now there are two forms: first updates the user's details and adds comments to another user. When I try to submit a form to AJAX and I try to submit a form, it does not work, when i use ajaxComplete function then my form data has been submitted successfully, but at the time it submits the form multiple times at the same time.
$(document).ajaxComplete(function() {
$("#add-remarks").on('submit', (function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: $("#add-remarks").attr("action"),
cache: false,
context: this,
data: $("#add-remarks").serialize(), //only input
success: function(data) {
var obj = JSON.parse(data);
$("#add-remarks")[0].reset();
if (obj['msg'] == 'isuccess') {
notification('insert');
} else {
notification('error');
}
}
});
}));
<div class="modal-body">
<div class="row">
<div class="col-md-12">
<div class="card-group-control card-group-control-right" id="accordion-model">
<div class="card">
<form method="post" name="update-user-details" id="update-user-details" action="">
<div class="row">
<div class="col-md-4">
<div class="form-group form-group-float">
<label class="d-block font-weight-semibold">First Name</label>
<input type="text" class="form-control" placeholder="First Name" name="customer_name" id="customer_name">
</div>
</div>
<div class="col-md-4">
<div class="form-group form-group-float">
<label class="d-block font-weight-semibold">Mobile</label>
<input type="text" class="form-control" placeholder="Mobile" name="mobile_number" id="mobile_number">
</div>
</div>
<button type="submit" class="btn bg-blue">Save Changes</button>
</div>
</form>
<form method="post" name="remarks" id="remarks" action="">
<div class="row">
<div class="col-md-4">
<div class="form-group form-group-float">
<label class="d-block font-weight-semibold">Remarks</label>
<input type="text" class="form-control" placeholder="Remarks" name="remarks" id="remarks">
</div>
</div>
<button type="submit" class="btn bg-blue">Save Changes</button>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
Move this piece of code outside of your ajaxComplete() function. You are probably somehow triggering the ajaxComplete function multiple times, causing multiple event listeners for the form submit.
$("#add-remarks").on('submit', (function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: $("#add-remarks").attr("action"),
cache: false,
context: this,
data: $("#add-remarks").serialize(), //only input
success: function(data) {
var obj = JSON.parse(data);
$("#add-remarks")[0].reset();
if (obj['msg'] == 'isuccess') {
notification('insert');
} else {
notification('error');
}
}
});
}));

Javascript code returns Unhandled Promise Rejection: AbortError: The operation was aborted

I am trying to run a simple contact form with html and javascript. I am trying to get filled out a contact form and then post the data to api. Upon page load I immediately get an error for Unhandled promise rejection.
HTML is:
<form id="contact-form"method="post" class="form-horizontal contact-form" action="#">
<!-- Honeypot SPAM Protection -->
<input type="text" name="cf[honeypot]" style="display: none">
<!-- END Honeypot SPAM Protection -->
<div class="form-group">
<div class="col-md-6">
<input type="text" name="cf[name]" class="form-control required" placeholder="İsim">
</div>
<div class="col-md-6">
<input type="email" name="cf[email]" class="form-control required email" placeholder="Email">
</div>
</div>
<div class="form-group">
<div class="col-md-6">
<input type="url" name="cf[url]" class="form-control url" placeholder="URL">
</div>
<div class="col-md-6">
<input type="text" name="cf[subject]" class="form-control required" placeholder="Konu">
</div>
</div>
<div class="form-group">
<div class="col-md-12">
<textarea name="cf[message]" rows="6" class="form-control required" placeholder="Mesaj"></textarea>
</div>
</div>
<div class="form-group">
<div class="col-md-12">
<input type="submit" value="Gönder" class="btn btn-sm btn-block btn-primary">
</div>
</div>
</form>
<script type="text/javascript" src="assets/js/signup.js"></script>
And the javascript code is:
$(document).ready(function() {
$("contact-form").submit(function(e){
e.preventDefault();
var form=this;
var URL = "https://v9jg33e7pa.execute-api.us-east-1.amazonaws.com/beta/sendemail/";
var data = {
name: $(form).find("#cf[name]").val(),
email: $(form).find("#cf[email]").val(),
urlContact: $(form).find("#cf[url]").val(),
subject: $(form).find("#cf[subject]").val(),
message: $(form).find("#cf[message]").val()
};
console.log(data);
if (""===$(form).find("#cf[honeypot]").val()){
$.ajax({
type: "POST",
url: URL,
dataType: "json",
contentType: "application/json",
data: JSON.stringify(data),
success: function () {
// clear form and show a success message
alert("yay");
},
error: function () {
// show an error message
alert("boo");
},
});
}
});
});
But when loading the page I get the following error:
Could not figure out what I am doing wrong?

Pass data to PHP file using Ajax

I'm trying to pass data to PHP file using Ajax and then save to MySQL database. From some reasons it's not working. I tested PHP code with passing data from HTML form and it's working. When use Ajax, after click on submit button nothings happen. I think that the problem is in Ajax data parameter.
Here is the code:
HTML
<body>
<div class="container">
<form class="search" action="" method="">
<div class="form-group">
<div class="input-group input-group-lg">
<span class="input-group-addon"><i class="fa fa-search" aria-hidden="true"></i></span>
<input type="text" class="form-control form-control-lg" id="trazi" name="trazi" placeholder="Pretražite artikle - upišite naziv, barkod ili šifru artikla">
</div>
</div>
</form>
<form class="articles" id="novi_artikl" action="" method="">
<div class="form-group row">
<label for="sifra" class="col-sm-4 col-form-label col-form-label-lg">Šifra artikla</label>
<div class="col-sm-8">
<input type="text" class="form-control form-control-lg" id="sifra" name="sifra" placeholder="Upišite šifru">
</div>
</div>
<div class="form-group row">
<label for="barkod" class="col-sm-4 col-form-label col-form-label-lg">Barkod artikla</label>
<div class="col-sm-8">
<input type="text" class="form-control form-control-lg" id="barkod" name="barkod" placeholder="Upišite barkod">
</div>
</div>
<div class="form-group row">
<label for="naziv" class="col-sm-4 col-form-label col-form-label-lg">Naziv artikla</label>
<div class="col-sm-8">
<input type="text" class="form-control form-control-lg" id="naziv" name="naziv" placeholder="Upišite naziv artikla" required>
</div>
</div>
<div class="form-group row">
<label for="mjera" class="col-sm-4 col-form-label col-form-label-lg">Jedinična mjera</label>
<div class="col-sm-8">
<input type="text" class="form-control form-control-lg" id="mjera" name="mjera" placeholder="Upišite mjeru" required>
</div>
</div>
<div class="form-group row">
<label for="cijena" class="col-sm-4 col-form-label col-form-label-lg">Cijena artikla</label>
<div class="col-sm-8">
<div class="input-group input-group-lg">
<input type="text" class="form-control form-control-lg text-right" id="cijena" name="cijena" placeholder="Upišite cijenu" required>
<span class="input-group-addon">KM</span>
</div>
</div>
</div>
<div class="form-group row">
<label for="kolicina" class="col-sm-4 col-form-label col-form-label-lg">Količina artikla</label>
<div class="col-sm-8">
<input type="text" class="form-control form-control-lg text-right" id="kolicina" name="kolicina" placeholder="Upišite količinu" required>
</div>
</div>
<div class="form-group row">
<label for="ukupno" class="col-sm-4 col-form-label col-form-label-lg">Ukupna vrijednost artikla</label>
<div class="col-sm-8">
<div class="input-group input-group-lg">
<input type="text" class="form-control form-control-lg text-right" id="ukupno" name="ukupno" placeholder="Ukupna vrijednost" required>
<span class="input-group-addon">KM</span>
</div>
</div>
</div>
<br>
<div class="float-right">
<button type="submit" class="btn btn-primary btn-lg" id="spremi" name="spremi">Spremi</button>
<button type="submit" class="btn btn-primary btn-lg" id="ponisti" name="ponisti">Poništi</button>
</div>
</form><!-- Content here -->
</div>
<script src="https://code.jquery.com/jquery-3.2.1.js" integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE=" crossorigin="anonymous"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js" integrity="sha256-T0Vest3yCU7pafRw9r+settMBX6JkKN06dqBnpQ8d30=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js" integrity="sha384-vFJXuSJphROIrBnz7yo7oB41mKfc8JzQZiCq4NCceLEaO4IHwicKwpJf9c9IpFgh" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js" integrity="sha384-alpBpkh1PFOepccYVYDB4do5UnbKysX5WZXm3XxPqe5iKTfUKjNkCk9SaVuEZflJ" crossorigin="anonymous"></script>
<script src="https://use.fontawesome.com/38d56b17e3.js"></script>
<script src="script.js" type="text/javascript"></script>
JavaScript
$('#spremi').click(function(){
var sifra = $('#sifra').val();
var barkod = $('#barkod').val();
var naziv = $('#naziv').val();
var mjera = $('#mjera').val();
var cijena = $('#cijena').val();
var kolicina = $('#kolicina').val();
var ukupno = $('#ukupno').val();
$.ajax({
type: 'POST',
url: 'insert.php',
contentType: "application/json; charset=utf-8",
dataType:'json',
data: ({sifra: sifra}, {barkod: barkod}, {naziv: naziv}, {mjera: mjera}, {cijena: cijena}, {kolicina: kolicina}, {ukupno: ukupno}),
success: function(response){
alert(response);
}
});
});
PHP code
<?php
include("connection.php");
if ($_POST["sifra"]) {
$sifra = $_POST["sifra"];
$barkod = $_POST["barkod"];
$naziv = $_POST["naziv"];
$mjera = $_POST["mjera"];
$cijena = $_POST["cijena"];
$kolicina = $_POST["kolicina"];
$ukupno = $_POST["ukupno"];
$query = "INSERT INTO lista (sifra, barkod, naziv, mjera, cijena, kolicina, ukupno) VALUES ('$sifra', '$barkod', '$naziv', '$mjera', '$cijena', '$kolicina', '$ukupno')";
$results = mysqli_query($dbc, $query);
if($results){
echo "Artikl je uspješno spremljen.";
}
else {
echo "Artikl nije spremljen. Došlo je do pogreške.";
}
}
mysqli_close($dbc);
?>
You should provide the values to the data property of $.ajax as a single object not as a collection of them:
data: {
sifra: sifra,
barkod: barkod,
naziv: naziv,
mjera: mjera,
cijena: cijena,
kolicina: kolicina,
ukupno: ukupno
},
Also, it's very important that you note your PHP code is wide open to SQL injection attacks. You should change the logic to use prepared statements ASAP.
The cause of your problem is the fact you are using type: 'POST'. To quote the docs :
An associative array of variables passed to the current script via the
HTTP POST method when using application/x-www-form-urlencoded or
multipart/form-data as the HTTP Content-Type in the request.
POST is a more "old fashioned" method, typically you would POST a <form> where the content automatically is serialized, i.e urlencoded, but you try to POST data in a JSON format. What you should do is either consider whether you really need POST. If you change it to GET (or simply remove type: 'POST') and access the passed data by $_GET then it will work (as long as you correct data as well).
If not, change the content type to indicate incoming urlencoded data :
$.ajax({
type: 'POST',
url: 'insert.php',
contentType: "application/x-www-form-urlencoded",
data: {sifra: sifra, barkod: barkod, naziv: naziv, mjera: mjera, cijena: cijena, kolicina: kolicina, ukupno: ukupno},
success: function(response){
alert(response);
}
});
I am pretty sure your code will work now, i.e the $_POST works and any message is properly received as plain text you can alert.

Laravel 5.2 Modal popup for forget Password displaying 500 internal server Error while running ajax function

I am trying to Check weather email exist or not to send reset password link.
For that am using ajax function but its showing 500 internal server error before runing ajax.
I knw 500 is for token miss match error but do i need token to check email existing or not.
But I think so, with the form tag token is auto generated and then also am using {{ csrf_field() }}
But it showing same error 500 Internal server. Just Help how can resolve this issue and do i need to generate token manually.
Views : login.blade.php
{!! Form::open(array('url' => '/auth/login', 'class' => 'form- login')) !!}
<div class="form-title"> <span class="form-title">Login</span> </div>
<div class="form-group">
<label class="control-label visible-ie8 visible-ie9">Username</label>
<input class="form-control form-control-solid placeholder-no-fix required" type="text" autocomplete="off" placeholder="Email" name="email" />
</div>
<div class="form-group">
<label class="control-label visible-ie8 visible-ie9">Password</label>
<input class="form-control form-control-solid placeholder-no-fix passwordclass required" type="password" autocomplete="off" placeholder="Password" name="password" />
</div>
<div class="form-actions">
<button type="submit" class="btn red btn-block uppercase clicklogin" style="background-color:#d5ed31 !important;border-radius:4px !important;border:1px solid #ddd;">Login</button>
</div>
<div class="form-actions">
<div class="pull-left">
<label class="rememberme mt-checkbox mt-checkbox-outline">
<input type="checkbox" name="remember" value="1" />
Remember me <span></span> </label>
</div>
<div class="pull-right forget-password-block"> <a class="btn-link" data-target="#modalforget" data-toggle="modal">Forgot Password? </a></div>
</div>
{!! Form::close() !!}
<!-- END LOGIN FORM -->
<!-- BEGIN FORGOT PASSWORD FORM-->
{!! Form::open(array('url'=>'password/reset','class' => 'form-horizontal create_forget_form','method'=>'POST', 'id' =>'forgetdata', 'files' => true)) !!}
{{ csrf_field() }}
<div class="modal fade" id="modalforget" tabindex="-1" data-width="760px" >
<div class="modal-dialog" style="width:760px !important;">
<div class="modal-content" style="background-color:#26344b;padding:20px;border-radius:12px !important;">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true"></button>
<div class="form-title"> <span class="form-title">Forget Password</span> </div>
</div>
<div class="modal-body" style="height:auto !important;">
<div class="row">
<div class="col-md-12">
<div class="form-group">
<strong style="color: #ffffec; font-size: large; "> Please enter your email. A password reset link will be sent to this email.</strong>
</div>
</div>
</div>
<div class="row"></div>
<div class="row">
<div class="col-md-10">
<div class="form-group">
<div class="col-md-2"></div>
<div class="col-md-10">
<input class="form-control required" type="email" autocomplete="off" placeholder="Email" id="forget_email" name="forget_email"style="font-size: large;" />
<span class="my-error-class" id="email_status"></span>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" value="Submit" id="submitButton" class="btn green">Submit</button>
<button type="button" value="Cancel" class="btn default red" data-dismiss="modal">Cancel</button>
<button type="reset" value="Clear" class="btn blue">Clear</button>
</div>
</div>
</div>
</div>
</div>
</form>
Ajax function in login.blade.php
<script type="text/javascript">
$('#submitButton').click(function(){
var formdata=new FormData($(this)[0]);
$.ajax({
url:"{{ URL::to('password/reset') }}",
type: 'POST',
data: formdata,
async: false,
cache: false,
contentType: false,
processData: false,
context:this,
dataType: "json",
success: function (returndata)
{
if(returndata == 0)
{
$( '#email_status' ).html('This Email does not Exists');
return false;
}
else
{
$( '#email_status' ).html("");
return false;
}
},
error: function(data)
{
console.log(data);
}
});
});
</script>
Route file:
Route::group(['middleware' => 'auth'], function()
{
Route::post('password/reset','Auth\AuthController#resetPassword');
}
Controller Auth\AuthController#resetPassword:
public function resetPassword()
{
$email =Input::get('forget_email');
$user_email = DB::table('users')->where('email', $email)->whereNull('deleted_at')->first();
if($user_email)
{
return '1';
}
else
{
return '0';
}
}
Screen Shot Of Error
I think you have to write your route outside auth group.
Route::post('password/reset','Auth\AuthController#resetPassword');
The issue is you are using POST request with ajax and for every post request you have to pass the csrf-token with the request like:
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
Put this in your ajax code and everything will be fine.
Or if you want to exclude the specific URI from CSRF verification, go to project/app/Http/Middleware, there is a file VerifyCsrfToken.php in which put the routes list in:
protected $except = [
// route list here
];
All the routes defined here excludes from csrf-token check.

Returning data from POST using KnockoutJS + DurandalJS

I've been working on this for too long.... And since jsfiddle doesn't support Durandal was hoping someone could shine some light on where the problem is. I am leaning towards my data bindings.
HTML:
<section>
<div class="row row-centered">
<div class="col-sm-6 col-sm-4 col-sm2 col-centered">
<div class="panel panel-info">
<div class="panel-heading">
Contact
</div>
<div class="panel-body">
<form role="form">
<div class="form-group">
<label for="inputName">Name</label>
<input type="text" class="form-control" id="inputName" data-bind="value: name, valueUpdate: 'afterkeydown'" placeholder="Username">
</div>
<div class="form-group">
<label for="inputEmail">E-mail</label>
<input type="email" class="form-control" id="inputEmail" data-bind="value: email, valueUpdate: 'afterkeydown'" placeholder="Email">
</div>
<div class="form-group">
<label for="inputText">Message</label>
<textarea class="form-control" id="inputText" data-bind="value: msg, valueUpdate: 'afterkeydown'" placeholder="Message"></textarea>
</div>
<div class="form-group">
<button type="submit" class="btn btn-info" data-bind="click:sendEmail, enable: name, enable: email, enable: msg">Submit</button>
</div>
</form>
</div>
</div>
</div>
</div>
<!-- ko if: debugTrue -->
<div class="row row-centered">
<div class="col-sm-6 col-sm-4 col-sm2 col-centered">
<div class="panel panel-success">
<div class="panel-heading">
Data Return
</div>
<div class="panel-body">
<ul data-bind="foreach: debugInfo(), as: 'd'">
<li data-bind="html: d"></li>
</ul>
</div>
</div>
</div>
</div>
<!-- /ko -->
</section>
Durandal:
define(function (require) {
var app = require('durandal/app'),
http = require('plugins/http'),
ko = require('knockout');
var url = '/api/api.php';
return {
name: ko.observable(),
email: ko.observable(),
msg: ko.observable(),
debugInfo: ko.observableArray([]),
sendEmail: function() {
var qs = {
method: 'email',
name: this.name(),
to: this.email(),
msg: this.msg(),
};
var that = this;
app.showMessage('Email sent to ' + this.name() + ' at ' + this.email());
return http.post(url, qs).then(function(response) {
that.debugInfo(response.items);
});
}
};
});
Returned from api.php:
{"images":1,"items":[1,2,3,4],"status":1}
So the problem is that when iterating through debugInfo() it is not populating.
ANy help appreciated.
There are a few problems with what you have so far.
var that = this; is in the wrong spot. this appears to represent the sendmail function and as such there is no debugInfo property associated with it.
You have a <!-- ko if: debugTrue --> knockout virtual element. there is no corresponding debugTrue property on the viewmodel.
the binding that you need to use the foreach with an as: d is as follows
<ul data-bind="foreach: {data: debugInfo, as: 'd'}">
<li data-bind="html: d"></li>
</ul>
Here is a jsFiddle Demo then will hopefully help

Categories

Resources