I am stuck with my specific problem.
I want to return false if the data comes using ajax.
Here is my code:
<script>
function verifydom(form)
{
var domnam = form.domname.value;
if (domnam == "")
{
alert("Please enter the Domain Name");
form.domname.focus();
return false;
}
else if(domnam.indexOf('.gov.in') <= 0){
alert("Please enter valid domain name");
form.domname.focus();
return false;
}
else{
$.ajax({
type: "get",
url: "calling.php",
data: "domnam="+domnam,
success: function(msg){
if(msg!== ""){
alert(msg);
}
}
});
return false;
}
return true;
}
</script>
<form name="frmDelegate" action="dlgdetail.php" method="POST"
onsubmit="return verifydom(document.frmDelegate);" autocomplete="off">
input type="text" name="domname" id= "domname"
onkeyup="showResult(this.value);"/> <input type="hidden"
id="chkmsg" value=""/>
<input type="submit" value="Go" name="submit" />
</form>
The ajax call under 'else condition' would return some error message, So if an error comes, I want the form not to be submitted.
Okay, the problem is 'Else will work every time whether Ajax gives a message or not.
How can I overcome this situation?
Rather than blank message I would prefer to return a JSON message from the calling.php file.
$arr = array( "status" => "error", "message" => "error found");
echo json_encode($arr);
By doing this you are easily allowed to check whether the error is there or not. If JSON have any message then you should check by below code.
$.ajax({
type: "get",
url: "calling.php",
data: "domnam="+domnam,
success: function(msg){
var data = jQuery.parseJSON(msg);
if(data.status == "error"){ // no need to check strictly
return false;
}
}
});
Related
validate Activity function with Ajax code
$(document).on('keyup','#activity_name',function () {
var error_activity = '';
var activity = $('#activity_name').val();
var _token = $('input[name="_token"]').val();
$.ajax({
type : 'post',
url : '{{ url('checkactivity') }}',
data :{activity:activity, _token:_token},
success:function (result) {
if(result == 'unique'){
$('#activity_status').html('<lable class="text-sucess" style="color: blue"></lable>');
$('#activity').removeClass('has-error');
$('#activity_btn').attr('disabled',false);
}
else
{
$('#activity_status').html('<lable class="text-danger">Try Another!</lable>');
$('#activity').addClass('has-error');
$('#activity_btn').attr('disabled','disabled');
}
}
});
});
My input field and here he is always call an event Onkeyup when ever i enters a single word in my input field and on each word he is sending a post request.
<div class="form-group">
<label for="checkbox">Group</label>
<select class="form-control form-control-sm" id="activitygroup" name="activitydeleverable">
<option>Select</option>
#foreach(App\Groups::all() as $group_name)
<option value="{{ $group_name->id }}">{{ $group_name->name }}</option>
#endforeach
</select>
</div>
<button type="submit" id="activity_btn" onclick="insertactivity()" class="btn btn-info">Insert</button>
here is my Controller Function
function checkactivity(Request $request){
$data = Activities::whereName($request->activity)->first();
if (!is_null($data)){
echo 'not_unique';
}
else
{
echo 'unique';
}
}
My code is work perfect, but i have a problem. On each single word my onkeyup Event Ajax send a post request to db and check data is available in db or not. but i have to stop this to doing again and again Post request. it's may do slow my system so i have to solve this please solve this logical issue i have to stop this Post requests or need only one post request.
You can see no of request in image
You will find all the information regarding your desired solution in this solved question:
How to delay the .keyup() handler until the user stops typing?
proper way of doing ajax request is use make it single at a time.
var req = null;
$(document).on('keyup','#activity_name',function () {
var error_activity = '';
var activity = $('#activity_name').val();
var _token = $('input[name="_token"]').val();
if (req != null) req.abort();
req = $.ajax({
type : 'post',
url : '{{ url('checkactivity') }}',
data :{activity:activity, _token:_token},
success:function (result) {
if(result == 'unique'){
$('#activity_status').html('<lable class="text-sucess" style="color: blue"></lable>');
$('#activity').removeClass('has-error');
$('#activity_btn').attr('disabled',false);
}
else
{
$('#activity_status').html('<lable class="text-danger">Try Another!</lable>');
$('#activity').addClass('has-error');
$('#activity_btn').attr('disabled','disabled');
}
}
});
});
try to make it delay method.
function delay(fn, ms) {
let timer = 0
return function(...args) {
clearTimeout(timer)
timer = setTimeout(fn.bind(this, ...args), ms || 0)
}
}
$('#input').keyup(delay(function (e) {
console.log('Time elapsed!', this.value);
}, 500));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"> </script>
<label for="input">Try it:
<input id="input" type="text" placeholder="Type something here..."/>
</label>
I am new here. Would like to seek your help for the problem that blocks me several days.
The design is simple. I have a server.js running localhost. It provides a POST (Login to acquire authentication) and a GET method (retrieving json after authentication). The login uses basic authentication to verify email/password of a user. if matches, return status 200 and put the user in the session & response. The following are the server side codes:
//Log user in Server.js
app.post('/session/login', function(req, res) {
var email = req.body.email;
var password = req.body.password;
if ( null == email || email.length < 1
|| null == password || password.length < 1 ) {
res.status(401).send("Wrong username or password");
return;
}
if (email == "xxxxx" && password == "xxxxx") {
var user = new User(email, password);
req.session.user = user;
return res.status(200).send({
auth : true,
user : user
});
}else{
return res.status(401).send("Wrong username or password");
}
});
The Get Method is having a basic auth before server can pass the json back. The following are the codes:
function Auth (req, res, next) {
if(req.session.user){
next();
}else{
console.log("Auth");
res.status(401).send({
flash : 'Please log in first'
});
}
}
app.get('/form/FormFields', Auth, function(req, res) {
fs.readFile(FORMFIELDS_FILE, function(err, data) {
if (err) {
console.error(err);
process.exit(1);
}
res.json(JSON.parse(data));
});
});
Now client side, I have two js files, one is a form to email/password to call Login above, and the other is simply get the form info using ajax in react. The navigation uses React-Router. The following are some codes:
// login.js
var LoginBox = React.createClass({
getInitialState: function () {
return {text: '', data: []};
},
handleLoginSubmit: function (data) {
$.ajax({
url: "https://localhost:3000/session/login",
dataType: 'json',
type: 'POST',
data: data,
success: function(data) {
this.setState({data: data});
}.bind(this),
error: function(xhr, status, err) {
console.error(this.props.url, status, err.toString());
}.bind(this)
});
},
render: function () {
return(
<div className="container">
<LoginForm data={this.state.data} onLoginSubmit={this.handleLoginSubmit} />
<p className="tips">{this.state.text}</p>
</div>
);
}
});
var LoginForm = React.createClass({
contextTypes: {
router: React.PropTypes.object
},
getInitialState: function () {
return {data:0,tittle: 'Login Test',text:''};
},
handleSubmit: function (e) {
e.preventDefault();
var email = this.refs.email.value.trim();
var password = this.refs.password.value.trim();
if (!email || !password) {
this.setState({text:"please input both username and password!"});
return;
}
this.props.onLoginSubmit({email:email,password:password});
this.setState({text:""});
this.refs.email.value = '';
this.refs.password.value = '';
//Routing defined in React-Router
const path = '/form';
this.context.router.push(path);
},
render: function () {
return (
<form className="loginForm" onSubmit={this.handleSubmit}>
<p>{this.state.tittle}</p>
<input type="email" placeholder="Your username" ref="email"/>
<input type="password" placeholder="Your password" ref="password"/>
<input type="submit" value="Login"/>
<p className="tips">{this.state.text}</p>
</form>
)
}
});
//code piece in form.js to call server and get form info
loadFieldsFromServer: function() {
$.ajax({
url: "https://localhost:3000/form/FormFields",
dataType: 'json',
cache: false,
success: function(data) {
this.setState({data: data});
}.bind(this),
error: function(xhr, status, err) {
console.error(this.props.url, status, err.toString());
}.bind(this)
});
},
Eventually, here is my problem. the login is ok, which I can see from network monitoring. I printed the log in server and found user is saved in the session. However when it navigates to form.js, I always retrieve 401 from server code below. from the log, i found user info in the session disappears and hence the following 401 returns.
else{
console.log("Auth");
res.status(401).send({
flash : 'Please log in first'
});
}
Please anybody help take a look at where i am wrong. Many thanks. BTW, just share more info, when I use Postman to simulate two calls to the server. Once I call login first, I can also retrieve form json successfully unless i call logout to clean the user in the session. Just dont know why it does not work in the program.
I have created an email utility which shows the email-ids from which email is received their subject line and date. Every email id has a checkbox alongside it. Whichever checkbox is clicked the email is sent to that email id. My problem is that i want to display "message sent successful" or error message on the same page without reload.
I think, it is possible with ajax, but I don't know how. Here is my view:
<?php echo form_open_multipart('accessmail/sendmail'); ?>
<div>
//here I display my emails
<div>
<div class="table_wrap1">
<div>Subject:</div>
<div><input type="text" required="required" id="subject" name="subject"></div>
</div>
<div class="table_wrap1">
<div>Email:</div>
<div><input type="email" id="replyto" name="replyto"></div>
</div>
<div id="txteditor">
<textarea name="textarea">
</textarea>
<button name="submit" value="process" type="submit">Send</button>
</div>
<?php } ?>
</div>
</form>
And my controller name is "accessmail", method name is "send mail":
public function sendmail()
{
$this->load->library('email');
$count=$this->input->post('mailcount');
$subject = $this->input->post('subject');
$msg = $this->input->post('textarea');
$replyto = $this->input->post('replyto');
//variable for checking whether any email id is selected or not
$status=0;
//for sending email to checked email id's
for($i=0;$i<$count;$i++)
{
// check whether the checkbox for a particular email id is checked or not
if(!$this->input->post('emailid'.$i))
{
continue;
}
else
{
//set the values for this email and send it
$this->email->from('abc#abc.com', 'abc');
$this->email->subject($subject);
$this->email->message($msg);
$idtosend = $this->input->post('emailid'.$i);
$this->email->to($idtosend);
if ($this->email->send())
{
$status++;
}
}
}
//for sending email to email id provide in textbox
if(!empty($replyto))
{
$this->email->from('abc#abc.com', 'Abc');
$this->email->subject($subject);
$this->email->message($msg);
$this->email->to($replyto);
if ($this->email->send())
{
$status++;
}
}
if($status>0)
{
//this message should be displayed on the same page along with other contents of the page
echo "Your message has been sent";
}
if($status==0)
{
//this message should be displayed on the same page along with other contents of the page
echo "Select any Email-id first";
}
}
my problem is the success message should be displayed on the same view preserving the contents of the page. Thanks in advance.
Yeah, that's a typical Ajax thing. But unfortunately that's a bit too big to just deliver you the answer (or I am too lazy, but you would benefit the most out of it, by figuring this out yourself).
My suggestion is, that you learn jQuery and Ajax (if you don't know that already).
For your problem, you specifically want to send the mails to your PHP-Function sendmail() via Ajax. This function either returns a Success- or an Errormessage (with json_encode() around it, that's how I'd do it). The Ajax-function then displays the message.
This is neither tested nor should be the final solution... just a hint:
The PHP Function:
<?php
function sendmail()
{
$mails = $_POST['mails'];
$countEmails = count($mails);
$success = 0;
foreach ($mails as $mail) {
// Check and send mails here
if ($this->email->send()) {
$success++;
}
}
if ($success < $countEmails) {
echo json_encode('One or more E-Mails were not sent');
return;
}
echo json_encode('E-Mails successfully sent');
}
Ajax Function (don't forget to include jquery):
$('#id_of_your_send_mails_button').bind('click', function(evt) {
evt.preventDefault();
$.ajax({
type: 'post',
url: 'path/to/sendmail',
dataType: 'json',
data: {
mails: $('#id_of_your_form').serialize();
},
success: function (data) {
$('#id_of_your_status_div').html(data);
}
});
});
Again, this is just pseudocode-ish stuff, to get you to it, but you have to do the learning on your own.
Hope that helps a bit.
EDIT
You might also try:
$('#id_of_your_send_mails_button').bind('click', function(evt) {
evt.preventDefault();
$.ajax({
type: 'post',
url: 'path/to/sendmail',
dataType: 'json',
data: {
name: $('#id_of_your_name_field').val(),
email: $('#id_of_your_name_field').val() // and so forth
},
success: function (data) {
$('#id_of_your_status_div').html(data);
}
});
});
I followed the Submit Ajax Form tutorial on tutsplus.com ,
but cannot figure out for the life of me why my data won't have addreply.php applied to it. When I look in my mysql table, the data does not get inserted. Any help would be greatly appreciated. I searched the web and have troubleshooted for many hours.
$(document).ready(function() {
$(".replyLink").one("click", function(){
$(this).parent().after("<div id='contact_form'></div>");
$("#contact_form").append("<form id='replyForm'></form>");
$("#replyForm").append("<input class='enterName' id='enterName' type='text'
name='name' placeholder='name' rows='1' cols='20' />");
$("#replyForm").append("<textarea class='enterReply' id='enterReply' name='comment'
placeholder='reply'></textarea>");
$("#replyForm").append("<input type='hidden' name='id' value=''>");
commentID= $(this).parent().attr('id');
$("#replyForm").append("<input class='replyButton' id='replyButton' type='submit' `value='reply'/>");`
$(".enterReply").slideDown();
$(".replyButton").slideDown();
});
$(".replyButton").click(function() {
var name = $("input#enterName").val();
var reply = $("textarea#enterReply").val();
var dataString = 'name='+ name.val() + '&comment=' + reply.val();
$.ajax({
type: "POST",
url: "addreply.php",
data: dataString,
success: function() {
}
});
return false;
});
**addreply.php**
<?php
session_start();
$replyID= $_POST['id'];
$name= $_POST['name'];
$comment= $_POST['comment'];
$type= $_POST['type'];
$song= $_POST['song'];
if($song == ''){
$song= 'not';
}
include 'connection.php';
if($_SESSION['signed_in'] == 'yes') {
$query1= "INSERT INTO ApprovedComments(name, comment, Authorized, type, reply_ID, song, date)
VALUES('$name', '$comment', 'YES', '$type', '$replyID', '$song', NOW());";
$insertComment= mysql_query($query1);
// echo "hi";
}
if( !isset($_SESSION['signed_in']) ) {
$query2= "INSERT INTO PreApprovedComments(name, comment, reply_ID, song, date)
VALUES('$name', '$comment', '$replyID', '$song', NOW());";
$insertComment= mysql_query($query2);
}
mysql_close();
?>
Try
$.ajax({
type: "POST",
url: "addreply.php",
data: $("#replyForm").serialize()+'name='+ encodeURIComponent(name) +
'&comment=' + encodeURIComponent(reply),
success: function() {
}
});
this will post all the fields in the #replyForm form and the name and comment fields.
i am a new bie to Ajax and currently making a form submission using php and ajax(for a wordpress plugin). My js code is
$("#submit").click(function(){
var form_data = $('.myform').serialize();
$.ajax({
type: "POST",
url: "main_form.php",
data: form_data,
success: function(html){
$('div#ajax_output').html(html);
}
});
return false;
});
and my entire page structure looks like
<div class="header"> ....</div>
<div class="navigation"> ....</div>
< ?php
if($_post) {
//form validation codes
if(condition true) echo "Success message";
else echo "Error";
}
?>
<div id="ajax_output"></div>
<form class="myform">
//form elements
</form>
//And the above javascript here(that click fn)
Now my problem is, as i am submitting the form data to the same page(it is unavoidable and cannot make it separate), the ajax returns inside <div id="ajax_output"></div> all the page contents header, navigation, etc including echo "Success message".
Can any one tell me how to output only php validation result?
output buffering may help you
<?php // insert that at the beginning of the page
ob_start();
?>
<div class="header"> ....</div>
<div class="navigation"> ....</div>
<?php
if($_post) {
//form validation codes
if(condition true) echo "Success message";
else echo "Error";
ob_end_clean();
exit(1);
} else {
echo ob_get_clean();
}
?>
<div id="ajax_output"></div>
<form class="myform">
//form elements
</form>
//And the above javascript here(that click fn)
You'd better restructure code, though. I.e. move processing of post data to the beginning of the page and then just exit if it should be processed.
Usually, such problems are solved on server side, not in javascript.
I mean, server should return correct html part w/o heading, navigation, etc., client should not parse all that stuff to get what it needs.
You may return after checking the form data, or do the form validation in another action.
The code example is not complete, but you can get the gist of it hopefully!
Add a variable to post data.
Javascript:
$("#submit").click(function(){
var form_data = $('.myform').serialize();
form_data.isAjax = true;
$.ajax({
type: "POST",
url: "main_form.php",
data: form_data,
success: function(html){
$('div#ajax_output').html(html);
}
});
return false;
});
PHP:
<?php
if(array_key_exists("isAjax", $_POST) {
if($_post) {
//form validation codes
if(condition true) {
echo "Success message";
}
else {
echo "Error";
}
}
}
else {
$mainPage = '<div class="header"/>>';
$mainPage += '<div class="navigation"/>';
$mainPage += '<div id="ajax_output"/>';
$mainPage += '<form class="myform"/>';
$mainPage += '<javascript />';
echo $mainPage;
}