php jquery, validate remote , array - validation

I have some problems to run the following code, the js:
$(document).ready(function(){
$.validator.addMethod("name", function(value, element) {
return $("#identiPIC_selected_0").val() !== '' && $("#identiPIC_selected_1").val() !== '' ;
}, "Required!");
$("#signin").validate({
groups:{
name : 'identiPIC_selected[]'
},
rules: {
'identiPIC_selected[]': {
required: true,
remote: {
url:"check3.php",
type:"post",
cache: false,
async:false,
data: {
'identiPIC_selected[0]': function() {
return $.trim($("#identiPIC_selected_0").val());
},
'identiPIC_selected[1]': function() {
return $.trim($("#identiPIC_selected_1").val());
}
}
}
}
}
});
});
the php is the following:
<?php
$captcha = $_POST['identiPIC_selected'];
$identiPIC[0] = "Apple";
$identiPIC[1] = "Flower";
if($captcha === $identiPIC){
echo "true";
} else {
echo "false";
}
?>
and the html:
<form id="signin" action="check3.php" method="POST">
<select id="identiPIC_selected_0" name="identiPIC_selected[]">
<option value="">Click to identify</option>
<option>Apple</option>
<option>Cat</option>
<option>Clock</option>
<option>Flower</option>
<option>Fork</option>
</select>
<select id="identiPIC_selected_1" name="identiPIC_selected[]">
<option value="">Click to identify</option>
<option>Apple</option>
<option>Cat</option>
<option>Clock</option>
<option>Flower</option>
<option>Fork</option>
</select>
<input type="submit" id="save" name="save" value="Save"/>
</form>
This code works well when, except when the user selects the second "select" option wrong, presses submit and then fixes his mistake and then he presses submit it just doesnt submit anymore, so what i mean is for example:
User selects: Apple + Cat and click on save button, displays error,
User fixes the problem: Apple + Flower and click on save button, it doesnt submit, even all the picks are good.
I added this :
$("#identiPIC_selected_0").change(function () {
$("#identiPIC_selected_0").removeData("previousValue");
});
$("#identiPIC_selected_1").change(function () {
$("#identiPIC_selected_1").removeData("previousValue");
});
but it doesnt seem to do anything for me.
Anyone any ideas?
Thanks!!!

ok... after different tries i think i found the solution, this seems to work:
$('#signin').submit(function(){
$("#identiPIC_selected_0").removeData('previousValue');
$("#identiPIC_selected_1").removeData('previousValue');
})

Related

MVC 4.x Validate dropdown and redirect to next page

Beginner question:
I have an MVC app where there are three dropdowns on a page. Currently I'm using AJAX to evaluate a drop down on form submission and modify a CSS class to display feedback if the answer to the question is wrong.
HTML:
<form method="post" id="formQuestion">
<div class="container-fluid">
<div class="row">
<div class="col-md-4">
<p>This is a question:</p>
</div>
<div class="col-md-4">
<select id="Question1">
<option value=""></option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
</div>
<div class="col-md-4 answerResult1">
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<button class="btn btn-success" type="submit" id="btnsubmit">Submit Answer</button>
</div>
</div>
</form>
AJAX:
#section scripts {
<script>
$(document).ready(function () {
$("#formQuestion").submit(function (e) {
e.preventDefault();
console.log($('#Question1').val())
$.ajax({
url: "/Home/DSQ1",
type: "POST",
data: { "selectedAnswer1": $('#Question1').val() },
success: function (data) { $(".answerResult1").html(data); }
});
})
});
</script>
}
Controller:
public string DSQ1(string selectedAnswer1)
{
var message = (selectedAnswer1 == "3") ? "Correct" : "Feed back";
return message;
}
I have three of these drop downs, that all get evaluated by AJAX in the same way. My question is, how would I go about evaluating all three and then returning a particular View if all three are correct.
I would like to avoid using hard-typed http:// addresses.
You could declare a global script variable prior to your document ready function, this will determine if the fields are valid. See var dropdown1Valid = false, ....
Then on your ajax success function, you could modify the values there. Say in the ajax below, your answering with first dropdown, if your controller returned Correct, set dropdown1Valid to true.
Lastly, at the end of your submit function, you could redirect check if all the variables are true, then redirect using window.location.href="URL HERE or use html helper url.action window.location.href="#Url.Action("actionName");
#section scripts {
<script>
var dropdown1Valid = false;
var dropdown2Valid = false;
var dropdown3Valid = false;
$(document).ready(function () {
$("#formQuestion").submit(function (e) {
e.preventDefault();
console.log($('#Question1').val())
$.ajax({
url: "/Home/DSQ1",
type: "POST",
data: { "selectedAnswer1": $('#Question1').val() },
success: function (data) {
$(".answerResult1").html(data);
if(data == "Correct"){
// if correct, set dropdown1 valid to true
dropdown1Valid = true;
}
// option 1, put redirect validation here
if(dropdown1Valid && dropdown2Valid && dropdown3Valid){
// if all three are valid, redirect
window.location.href="#Url.Action("actionName","controllerName", new { })";
}
}
});
// option 2, put redirect validation here
if(dropdown1Valid && dropdown2Valid && dropdown3Valid){
// if all three are valid, redirect
window.location.href="#Url.Action("actionName", "controllerName", new { })";
}
})
});
</script>
}

How to create private channel name dynamically

I woluld like to create real-time order tracking system using laravel, vue and pusher. In admin panel I have list of all orders. The idea is when admin change order status the user (owner of this order) will get notification without refreshing page. To make it I want to use private channels. My problem is to create private channel name dynamically.
Admin panel looks like below.
<h1>Admin</h1>
<table>
#foreach ($orders as $o)
<tr>
<td>{{$o->name}}</td>
<td>{{$o->status}}</td>
<td>{{$o->getUser->name}}</td>
<td>
<update-order-status :id="{{$o->id}}"></update-order-status>
</td>
</tr>
#endforeach
</table>
There is update-order-status component which is a form used to change status of order. Id of order is passed to component via props. Content of component look like below:
///update-order-status component
<template>
<div>
<form method="GET" action="change_status">
<input type="hidden" name="id" :value=id />
<select name="status">
<option value="placed">Placed</option>
<option value="progres">Progres</option>
<option value="delivered">Delivered</option>
</select>
<input type="submit" value="update status" v-on:click="upd(id)" />
</form>
</div>
</template>
<script>
export default {
created() {
},
props: ["id"],
data: function() {
return {
};
},
methods: {
upd: function(id) {
this.$root.$emit("eve", id);
}
}
};
</script>
When admin submit form order status is updated in database and also event eve is emitted. This event is used to pass id of order to status-changed compoennt. This component is placed in user panel and contains notification that order status has been changed.
///status changed component
<template>
<div v-if="sn" class="notification is-primary">
<button class="delete" v-on:click="del()"></button>
Staus of order nr {{nr}} has been changed
</div>
</template>
<script>
export default {
created() {
this.$root.$on("eve", data => {
this.nr = data;
});
Echo.private("order" + this.nr).listen("status_changed", e => {
this.sn = true;
});
},
props: [],
data: function() {
return {
sn: false,
nr: 0
};
},
methods: {
del: function() {
this.sn = false;
}
}
};
</script>
Here is the problem. Variable nr is 0 all time. It'not changing dynamically. When nr is static or channel is public this code works fine. Please help.
Put the Echo inside the $on. Otherwise the asynchronous $on happens too late to change nr in the Echo.
created() {
this.$root.$on("eve", data => {
this.nr = data;
Echo.private("order" + this.nr).listen("status_changed", e => {
this.sn = true;
});
});
}

can't get json return in codeigniter

I have a login page, that sends a ajax request to the server when someone tries to log in. The ajax, goes to the server, cause they get logged in I've been able to confirm. But the problem is it seems my jQuery isn't receiving the JSON.
The function in my controller is:
public function login(){
$this->load->model('users_model');
if((!!$this->input->post('email')) || (!!$this->input->post('password'))){
$ret = $this->users_model->login($this->input->post('email'), $this->input->post('password'));
echo json_encode(array('status' => "OK", 'msg' => 'Logged in!')); //also tried return
}else{
echo json_encode(array('status' => 'FAIL', "msg" => 'Invalid Email or Pass'));
}
}
and the AJAX function is:
<script type="text/javascript">
$(document).ready(function() {
$("#login").ajaxForm(function(json) {
alert(json);
if(json.status == true) {
alert(json.msg);
//window.location = '<?php echo base_url(); ?>';
} else {
alert("Problem");
$(".error_msg").html(json.msg);
};
});
});
</script>
if I alert the json variable, it's blank, and if I do json.msg it say undefined. So... what do I have to do to get this to give the callback, a json object, or an object of any kind? Please explain it so I understand the problem, not just how to fix it. Thanks a lot!
EDIT:
Here's the form too:
<span class="error_msg"></span></br>
<form id="login" action="<?php echo base_url(); ?>users/login" method="POST" enctype="multipart/form-data">
Email: <input name="email" type="text"/></br>
Password: <input type="password" name="password"></br>
<input type="submit"/>
</form>
Ah, I think I understand.
Is this the plugin you are using? http://www.malsup.com/jquery/form/#api
In that case, use ajaxSubmit, not ajaxForm.
Other examples online do something like this:
$(document).ready(function() {
$('#login').submit(function() {
$("#login").ajaxSubmit({
success: function(json) {
alert(json);
if(json.status == true) {
alert(json.msg);
//window.location = '<?php echo base_url(); ?>';
} else {
alert("Problem");
$(".error_msg").html(json.msg);
}
}
});
return false;
});
});

Knockout Validation & Proper way to clear controls

I have the following code and it works fine, EXCEPT when you clear the property after you have inserted an item. The error shows up right away.
ko.validation.configure({
insertMessages: false,
decorateElement: true,
errorElementClass: 'error'
});
FirstName: ko.observable().extend({
required: true
}),
and I have add method in the knockout viewmodel
addItem: function () {
if (!viewModel.isValid()) {
viewModel.errors.showAllMessages();
return false;
} else {
//DO SOMETHING
this.SomeCollection.push(newInterviewee);
this.FirstName(null);
}
},
I have the following in the HTML:
<div>
<label>First Name</label>
<input data-bind="value: FirstName, validationElement: FirstName, valueUpdate: 'keyup'" class="input" type="text">
</div>
<div>
<div>
<input data-bind="click: addItem" class="button" type="button">
</div>
The problem is that after I call this.FirstName(null). The error shows up right away! I want the error to show up only when they press the button even after the property is cleared
Here is the solution that is provided by Steve Greatrex: https://github.com/Knockout-Contrib/Knockout-Validation/issues/210
We had the same issue on our project. We solved this by forcing isValid to true.
addItem: function () {
if (!viewModel.isValid()) {
viewModel.errors.showAllMessages();
return false;
} else {
//DO SOMETHING
this.SomeCollection.push(newInterviewee);
this.FirstName(null);
viewModel.isValid(true);
}
},
To be able to do this, you need to overwrite ko.validation's definition for the isValid computed as follows:
observable.isValid = ko.computed({
read: function() {
return observable.__valid__();
},
write: observable.__valid__
}
);

Ajax Contact form validation and submit

I'm trying to make a HTML contact form. Here's my code
`Get in Touch
<p class="success-sending-message">Thank you, your message has been sent!</p>
<p class="error-sending-message">There has been an error, please try again.</p>
<div id="contact-form">
<form action="" id="contactForm" class="styled" method="post">
<label for="contact_name">Name</label>
<input type="text" tabindex="3" id="contact_name" name="contact_name" value="" class="requiredField textbox" />
<label for="contact_email">Email</label>
<input type="text" tabindex="4" id="contact_email" name="contact_email" value="" class="requiredField email textbox" />
<label for="contact_subject">Subject</label>
<input type="text" tabindex="5" id="contact_subject" name="contact_subject" value="" class="requiredField textbox" />
<label for="contact_message">Your Message</label>
<div class="textarea-wrap">
<textarea cols="65" rows="9" tabindex="6" id="contact_message" name="contact_message" class="requiredField"></textarea>
</div>
<div class="form-section">
<button class="button" tabindex="7" type="submit" id="born-submit" name="born-submit">Send Message</button>
<input type="hidden" name="submitted" id="submitted" value="true" />
<span class="sending-message"><img src="css/images/loading-light.gif" /> Sending...</span>
</div>
</form>
</div>`
And here's my validation script
$(window).load(function() {
/* Ajax Contact form validation and submit */
jQuery('form#contactForm').submit(function() {
jQuery(this).find('.error').remove();
var hasError = false;
jQuery(this).find('.requiredField').each(function() {
if(jQuery.trim(jQuery(this).val()) == '') {
if (jQuery(this).is('textarea')){
jQuery(this).parent().addClass('input-error');
} else {
jQuery(this).addClass('input-error');
}
hasError = true;
} else if(jQuery(this).hasClass('email')) {
var emailReg = /^[a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
if(!emailReg.test(jQuery.trim(jQuery(this).val()))) {
jQuery(this).addClass('input-error');
hasError = true;
}
}
});
if(!hasError) {
jQuery(this).find('#born-submit').fadeOut('normal', function() {
jQuery(this).parent().parent().find('.sending-message').show('normal');
});
var formInput = jQuery(this).serialize();
var contactForm = jQuery(this);
jQuery.ajax({
type: "POST",
url: jQuery(this).attr('action'),
data: formInput,
success: function(data){
contactForm.parent().fadeOut("normal", function() {
jQuery(this).prev().prev().show('normal'); // Show success message
});
},
error: function(data){
contactForm.parent().fadeOut("normal", function() {
jQuery(this).prev().show('normal'); // Show error message
});
}
});
}
return false;
});
jQuery('.requiredField').blur(function() {
if(jQuery.trim(jQuery(this).val()) != '' && !jQuery(this).hasClass('email')) {
if (jQuery(this).is('textarea')){
jQuery(this).parent().removeClass('input-error');
} else {
jQuery(this).removeClass('input-error');
}
} else {
if (jQuery(this).is('textarea')){
jQuery(this).parent().addClass('input-error');
} else {
jQuery(this).addClass('input-error');
}
}
});
jQuery('.email').blur(function() {
emailReg = /^[a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
if(emailReg.test(jQuery.trim(jQuery(this).val())) && jQuery(this).val() != '') {
jQuery(this).removeClass('input-error');
} else {
jQuery(this).addClass('input-error');
}
});
jQuery('.requiredField, .email').focus(function(){
if (jQuery(this).is('textarea')){
jQuery(this).parent().removeClass('input-error');
} else {
jQuery(this).removeClass('input-error');
}
});
});
My form is working properly, After filling details It is showing me "Thank you, your message has been sent!" But where is this message going, I don't have any of the process.php file and all. I want that email should be send to my email id.
Bonjour ... Look in the firebug or chrome developper tools console to see the post trace.
In your php file, you can put echos or var_dump to be sure all it's ok.
Another thing ... the form action is empty.
Currently there's no where it is going. Give where it needs to go in the action="" attribute of the <form>. And also, in the actioned URL, typically, a PHP file, give this code:
<?php
if (count($_POST))
{
$name = $_POST["contact_name"];
$email = $_POST["contact_email"];
$subject = $_POST["contact_subject"];
$message = $_POST["contact_message"];
$mail = "Name: $name\nEmail: $email\nSubject: $subject\nMessage: $message";
if (mail("mymail#domain.com", "New Mail from Contact Form", $mail))
die ("OK");
else
die ("Fail");
}
?>
Also, you need to make a small correction in your JavaScript AJAX Call. Replace this way:
jQuery.ajax({
type: "POST",
url: jQuery(this).attr('action'),
data: formInput,
success: function(data){
if (data == "OK")
contactForm.parent().fadeOut("normal", function() {
jQuery(this).prev().prev().show('normal'); // Show success message
});
else
alert ("Message not sent!");
},
error: function(data){
contactForm.parent().fadeOut("normal", function() {
jQuery(this).prev().show('normal'); // Show error message
});
}
});
Test if your server supports SMTP through PHP Script
Create a small file, which has this content, say mail.php:
<?php
var_dump(mail("yourmail#gmail.com", "Testing Message", "This mail was sent from PHP Script."));
?>
And try to access the file and see what you are getting. Please update the same in your question.

Resources