Ajax Mandrill send email on form submit - ajax

If i go through this code step by step in firebug it works, but it wont work on button press. Using a button outside form to call it works ok.....It seems that complete: line does not get executed at all.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#salji').click(function() {
var testing = false;
$.ajax({
type: "POST",
url: "https://mandrillapp.com/api/1.0/messages/send.json",
data: {
'key': 'Vv_8cJDX9*****',
'message': {
'from_email': 's****#gmail.com',
'to': [
{
'email': 'd*****#gmail.com',
'name': 'Test',
'type': 'to'
}
],
'autotext': 'true',
'subject': 'New subject',
'html': 'YOUR EMAIL CONTENT HERE! YOU CAN USE HTML!'
}
},
complete: function() {
testing = true;
$('#forma').attr('action', 'http://%SERVERIP%/signup1?%PARAMS%');
$('#forma').submit();
}
}
)
})
})
</script>
<div class="form1" align="center"><input class="button" value="#CONTINUE#" name="signup" type="submit" id="salji">

You don't have a form on the page, therefore .submit won't do anything.
Change your DIV to a form and give it the correct ID, "form1" is a class atm.

Related

Print automatically on form close

I have a button that prints something and it works well.
I would like to print automatically when the form is closed.
At the moment the form sends an email to my customers with order details (it works very well) but now I would like to print automatically without requiring the user to push a button.
Please help me. I am a beginner here.
Relevant code:
<a
href="#!"
target="_blank"
id="save-and-print"
type="submit"
title="Speichern & Drucken">
<i class="fa fa-print"></i>
</a>
<script type="text/javascript" src="/js/summernote.js?v=0.72"></script>
<script>
$( function() {
$('#save-and-print').on('click', function (e) {
e.preventDefault();
var url = 'myOrders/replacement/' + '{{ $data->id }}';
}
});
$.ajax({
type: "PATCH",
url: '/myOrders/replacement/' + '{{ $data->id }}',
data: $("form").serialize(),
dataType: 'json',
success: function (data) {
window.location.reload();
location.href = '{{ route('print', [$data->id, 'option' => 'advance']) }}';
},
error: function (data) {
$('body').pgNotification({
style: 'flip',
message: 'Error',
position: 'top-right',
type: 'danger',
timeout: 4000
})
},
});
</script>
If you want the same action to take place on the submit event of your form as what happens when your id="save-and-print" button is being pressed, you could do something like this:
function printSomething(event) {
var url = 'myOrders/replacement/' + '{{ $data->id }}';
}
const form = document.getElementById('form');
form.addEventListener('submit', printSomething);

Running Ajax request not working

I just migrated to a different bootstrap template now my ajax functions is not working and my php file which handles the functions is not appearing in the XHR inspect tool of chrome.
I only have this jquery script ? is this enough for running an ajax function? I
<!-- Jquery Core Js -->
<script src="../dashboard-assets/plugins/jquery/jquery.min.js"></script>
HTML CODE
<form id="upload_book_form" method="POST">
<p>Upload Books</p>
<input type="file" id="uploadbookinfo" name="uploadbookinfo" value="Import" />
</form>
SCRIPT FUNCTION
<script type="text/javascript">
$(document).ready(function() {
//upload book
$('#uploadbookinfo').change(function() {
$('#upload_book_form').submit();
});
$('#upload_book_form').on('submit', function(event) {
event.preventDefault();
$.ajax({
url: "adminfunctions.php",
method: "POST",
data: new FormData(this),
contentType: false,
processData: false,
success: function(data) {
var getdata = data.trim();
if (getdata == "SUCCESS") {
swal({
title: 'Success!',
text: 'Book Added , Try refreshing the page',
type: 'success',
confirmButtonClass: "btn btn-success",
buttonsStyling: false
}).then(function() {
$("#uploadbookinfo").val(null);
});
} else if (getdata == "ERRORFILETYPE") {
swal({
title: 'Oops...',
text: 'File type is not supported',
type: 'error',
confirmButtonClass: "btn btn-danger",
buttonsStyling: false
}).then(function() {
$("#uploadbookinfo").val(null);
});
} else {
swal({
title: 'Sorry for the inconvenience!',
text: "There's a problem. Please contact the technical support for any concerns and questions.!",
type: 'error',
confirmButtonClass: "btn btn-info",
buttonsStyling: false
}).then(function() {
$("#uploadbookinfo").val(null);
});
}
},
error: function(jqXHR, exception) {
console.log(jqXHR);
}
});
});
});
</script>

React, update DOM elements on submit on posted data without refresh

I am playing around with React and Rails and I am working on a function to submit a post to the server, which works as intended, but then re-renders the DOM elements without refreshing the page.
I am aware I am missing a function that would get the new JSON object and map it over the DOM again but am unsure how to properly formulate this.
From my research, I would have to do a new $.ajax request on the '/posts' route, which is already set up as a JSON only render pulling all posts.
My code is below:
var New = React.createClass ({
handleClick(e) {
e.preventDefault();
let text = this.refs.text.value;
$.ajax({
url: '/new',
type: 'POST',
data: { post: { text: text} },
success: (post) => {
this.handleSubmit(post);
}
});
},
handleSubmit(post) {
console.log(post);
this.refs.text.value = ""
},
render: function() {
return( <div>
<div className="post-div">
<form>
<input className="form-control" ref='text' placeholder='Post Something' />
<button className="btn btn-primary" onClick={this.handleClick}>Submit</button>
</form>
</div>
</div>
)
}
})
and the other react file:
var Post = React.createClass ({
render: function() {
return
<div className="text-box">
<p className="text">{this.props.text}</p>
<div className="text-stamps">{this.props.timestamps}</div>
</div>;
}
})
Any help would be appreciated. Thank you.
The ReactJS introductory tutorial has exactly the same functionality explained in a great detail.
I'd definitely direct you to look at it here. And here's the section that directly does what you want. POSTing a comment to the server and re-rendering it back to the client. And it also shows how to optimistically render the new comment in the UI.
Update: Here is how you can do it. The comments are the place where you will add hooks into the server call.
var posts = [
{id: 1, text: "iPhone 7 release date"},
{id: 2, text: "Samsung 7 release date"}
];
var Post = React.createClass({
render: function(){
return (<p>{this.props.text}</p>);
}
});
var PostList = React.createClass({
render: function() {
var response = this.props.posts.map(function(post){
return (<Post text={post.text}></Post>);
});
return (<div>
{response}
</div>);
}
});
var PostForm = React.createClass({
getInitialState: function() {
return {newPost: ""};
},
handleTextChange: function(e){
this.setState({newPost: e.target.value});
},
onSubmit: function(e) {
e.preventDefault();
var newPost = this.state.newPost.trim();
if(!newPost) {
return ;
}
this.props.onAddition(newPost);
this.setState({newPost: ""})
},
render: function() {
return (
<form onSubmit={this.onSubmit}>
<h4>Add some post here</h4>
<input type="text" value={this.state.newPost} onChange={this.handleTextChange}></input>
<input type="submit" value="Add Post" />
</form>
);
}
});
var Page = React.createClass({
getInitialState: function() {
return {posts: posts};
},
onAddition: function(newPost) {
console.log("Adding new: ",newPost);
posts.push({id: Date.now(), text:newPost});
//POST to the server here and set the state if successful
this.setState({posts: posts});
},
componentDidMount: function() {
//Load from there server here
//And keep reloading it from the server every few seconds
},
render: function() {
return (
<div>
<PostForm onAddition={this.onAddition}/>
<PostList posts={this.state.posts}/>
</div>
);
}
});
var div = document.getElementById("app");
ReactDOM.render(<Page/>, div);
And here's a JSBin for this. https://jsbin.com/pokoja/edit?html,js,output
A slight modification to Kumar's answer because his solution mutates state and might be difficult for people who do not use the getInitialState function.
onAddition = (newPost) => {
const posts = [...this.state.posts]
posts.push({
_id: Date.now,
text: newPost.post
})
this.setState({
posts: posts,
postForm: {
post: ''
}
})}
In this instance, the contents of posts in state are copied (using the spread operator) and assigned to a posts constant. Then the new data is pushed into the constant, which is then set as the new state (along with the copied contents of the existing state).

React Tutorial - Page Refreshing after Comments Added

I'm working through the official React tutorial and having a little trouble. When I add a comment I expect the comment to appear in the view, and for a split second it does, but then the page refreshes and the comment's gone.
On a related matter (and really just a request for a little FYI as I'm still learning AJAX), the code is supposed to add the comment to the JSON. I'm presuming that this wouldn't work on the Plunker but is there enough code there to actually update a JSON if the page is live?
Thanks for any help! Plunker link and code follows:
https://plnkr.co/edit/p76jB1W4Pizo0rDFYIwq?p=preview
<script type="text/babel">
// To get started with this tutorial running your own code, simply remove
// the script tag loading scripts/example.js and start writing code here.
var CommentBox = React.createClass({
loadCommentsFromServer: function() {
$.ajax({
url: this.props.url,
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)
});
},
handleCommentSubmit: function(comment) {
var comments = this.state.data;
// Optimistically set an id on the new comment. It will be replaced by an
// id generated by the server. In a production application you would likely
// not use Date.now() for this and would have a more robust system in place.
comment.id = Date.now();
var newComments = comments.concat([comment]);
this.setState({data: newComments});
$.ajax({
url: this.props.url,
dataType: 'json',
type: 'POST',
data: comment,
success: function(data) {
this.setState({data: data});
}.bind(this),
error: function(xhr, status, err) {
this.setState({data: comments});
console.error(this.props.url, status, err.toString());
}.bind(this)
});
},
getInitialState: function() {
return {data: []};
},
componentDidMount: function() {
this.loadCommentsFromServer();
setInterval(this.loadCommentsFromServer, this.props.pollInterval);
},
render: function() {
return (
<div className="commentBox">
<h1>Comments</h1>
<CommentList data={this.state.data} />
<CommentForm onCommentSubmit={this.handleCommentSubmit} />
</div>
);
}
});
var CommentList = React.createClass({
render: function() {
var commentNodes = this.props.data.map(function(comment) {
return (
<Comment author={comment.author} key={comment.id}>
{comment.text}
</Comment>
);
});
return (
<div className="commentList">
{commentNodes}
</div>
);
}
});
var CommentForm = React.createClass({
getInitialState: function() {
return {author: '', text: ''};
},
handleAuthorChange: function(e) {
this.setState({author: e.target.value});
},
handleTextChange: function(e) {
this.setState({text: e.target.value});
},
handleSubmit: function(e) {
e.preventDefault();
var author = this.state.author.trim();
var text = this.state.text.trim();
if (!text || !author) {
return;
}
this.props.onCommentSubmit({author: author, text: text});
this.setState({author: '', text: ''});
},
render: function() {
return (
<form className="commentForm" onSubmit={this.handleSubmit}>
<input
type="text"
placeholder="Your name"
value={this.state.author}
onChange={this.handleAuthorChange}
/>
<input
type="text"
placeholder="Say something..."
value={this.state.text}
onChange={this.handleTextChange}
/>
<input type="submit" value="Post" />
</form>
);
}
});
var Comment = React.createClass({
rawMarkup: function() {
var md = new Remarkable();
var rawMarkup = md.render(this.props.children.toString());
return { __html: rawMarkup };
},
render: function() {
return (
<div className="comment">
<h2 className="commentAuthor">
{this.props.author}
</h2>
<span dangerouslySetInnerHTML={this.rawMarkup()} />
</div>
);
}
});
ReactDOM.render(
<CommentBox url="comments.json" pollInterval={2000} />,
document.getElementById('content')
);
</script>
As you said, your problem is that the information in the json file is static (see last paragraph), so every time the comments are refreshed, you lose the new one. The way you could handle it is using the json file during the first load and then just prevent refreshing them, just adding the new ones to the comment box state (after all this is just a example and you just want to see some eye candy, don't you?).
Checking the browser's console you can see that your AJAX request to store the new file is failing, you cannot update it on Plunker, that file is immutable.

Redirecting a successful ajax call with React-Router

I'm getting Cannot read property 'router' of undefined with the code below.
this.transitionTo('home') is bugging, and I'm guessing it's because of the context of this. I tried binding the ajax call to this, and it didn't help either.
Any thoughts on how to simply redirect to either 'home' or '/' after this successful ajax call?
I've tried both the Navigation (transitionTo) and the History (this.pushState) mixins.
Edit: In the meantime I found a hacky working solution that uses a page refresh. Within the ajax .done section:
history.pushState({},'','/')
window.location.reload()
Code:
var Router = ReactRouter;
var Route = ReactRouter.Route;
var Routes = ReactRouter.Routes;
var Navigation = ReactRouter.Navigation;
var History = ReactRouter.History;
var Login = React.createClass({
mixins: [ History ],
mixins: [ Navigation ],
getInitialState: function(){
return{
email: "",
password: ""
}
},
submit: function(e){
e.preventDefault()
var data = {
email: this.state.email,
password: this.state.password,
}
// Submit form via jQuery/AJAX
$.ajax({
type: 'POST',
url: '/sessions',
data: data
})
.done(function(data) {
App.logIn(data.email)
alert('login successful!')
this.transitionTo('home')
// this.history.pushState(null, '/home')
// this.pushState(null, '/home')
})
.fail(function(data) {
alert('No Such Email or Incorrect Password')
});
},
handleEmailChange: function(event) {
this.setState({email: event.target.value});
},
handlePasswordChange: function(event) {
this.setState({password: event.target.value});
},
render: function(){
return(
<div>
Login To Your Account
<br/>
<form onSubmit={this.submit} >
Email: <input label="Email:" onChange={this.handleEmailChange} />
<br/>
Password: <input label="Password:" type="password" onChange={this.handlePasswordChange} />
<button type="submit">Submit</button>
</form>
</div>
)
}
})
Your context is changing in the inner function. The easiest way (in my opinion) to fix this is to place var _this = this in your outer function, then use _this.transitionTo in your callback.

Resources