I have this code that submits a form and sends a mail, and it opens a different page saying successful:
<input type="submit" value="submit">
Then I also have this code which is a sexy button that pops up a message that the mail has been sent (even though it hasn't):
Submit
How do I combine the code so that the mail sends with the sexy button and I get the popup, instead of landing on a new page?
I'd suggest using ajax to confirm the email sending, after which pop-up your so called sexy button.
<form method="POST" action="/your/path/to/php/file">
<input type="submit" value="submit" onclick="someFunction();">
</form>
<a id="href_id" href="submit-message.html" class="nicdark_marginbottom20_iphoneland nicdark_marginbottom20_iphonepotr nicdark_mpopup_ajax nicdark_outline white nicdark_btn nicdark_bg_bluedark medium title">Submit</a>
<script type="application/javascript">
function someFunction() {
$.ajax({
type: 'POST',
url: 'route/to/php/file',
data: {
// data goes here
},
cache: false,
headers: {
// headers(if any) fo here
},
success: function(){
$('#href_id').show();
}
});
}
</script>
The php file may look something like this:
if(mail ($to, $subject, $message, $additional_headers = null, $additional_parameters = null)) {
return true;
}
Now, clearly this is not a complete code and should not be taken as such, this is mearly a pointing in the right direction of sorts.
I'm using jQuery here simply because I'm more familiar with it, but all this can be done in pure javascript, there's no real need to use jQuery if you don't want to.
Read more about ajax, PHP and Ajax.
As a final note, the logic is as such:
Do an ajax call in the front-end
Send email in backend using PHP(or your language of choice)
Return a response that confirms or not that the email has been sent
Based on that response display the pop-up
Related
Question: how can I communicate JSON back from a controller to my html page, and embed the response in my page, instead of destroying the page?
The long story is like this:
Embedded in a quite large html page (created by a view when I open my base URL, say, http://.../home) I have a html form. It has some data fields, and the usual "Submit" button.
<form class="form-horizontal" method="POST" action="{{ route('form.user') }}">
{{ csrf_field() }}
... lots of input fields ...
<div class="form-group">
<button type="submit" class="btn btn-primary">
Submit
</button>
</div>
</form>
The receiving route ...
Route::post('form/user','ItemController#save')->name('form.user');
And the controller ...
public function save(Request $request) {
...
return response()->json(['status' => 'Saved successfully']);
}
The whole thing works like intended, if I fill the form and hit the "Submit" button, the controller receives all input fields via the $request properties.
The problem arises after the return from the controller, the html is cleared from the browser, and the JSON is displayed.
What I need is receive the JSON and display it in a div of my original html, not replace it.
Question: what do I need to do, how can I hook into the communication to intercept and handle the JSON response, so I can display the response text in my original web page (using JQuery), and not destroy the html?
Thx, Armin.
Capture the FORM submit event, and prevent the default.
Construct an AJAX request
Dictate the response type.
Convert the form data to a serialized object to be sent to the server
Capture the returned response and apply it to a DIV.
That would look something like this:
$('form').on('submit', function(e){
e.preventDefault(); //1
var $this = $(this); //alias form reference
$.ajax({ //2
url: $this.prop('action'),
method: $this.prop('method'),
dataType: 'json', //3
data: $this.serialize() //4
}).done( function (response) {
if (response.hasOwnProperty('status')) {
$('#target-div').html(response.status); //5
}
});
});
I have got a fileUpload (made with NodeJS) and i want to show the success of the upload in the html in the {{upload.message}}. I implemented it with AngularJS but it didn't work. What am I doing wrong?
HTML
<form enctype="multipart/form-data" action="/upload"
method="POST">
<div class="form-group">
<input type="file" name="file" />
<p></p>
<input type="file" name="file" />
<p></p>
<input type="file" name="file" />
<br> <br>
<input type="submit" value="Upload File" name="submit"
class="btn btn-primary">
</form>
<span>{{upload.message}}</span>
</div>
NodeJS
router.post('/upload', function(req,res){
upload(req,res,function(err) {
var fileNames = [];
req.files.forEach(function(element){
fileNames.push(element.filename);
})
console.log('Selected Files: ', fileNames);
if(err){
res.end("Error: '" , err , "'");
}else{
res.sendStatus(204);
}
});
});
AngularJS
var self = this;
this.message = "";
this.upload= function(){
$http.post('/uploads')
.then(function success(result){
self.message = "Upload worked";
},
function error(response){
self.message = "Error upload failed";
});
};
edit: You should read this book: http://www.allitebooks.com/read/index.php?id=7630
You normally make a request from browser to the server and not the other way around. I suggest using Ajax with polling. If you insist on sending a request from the server to the browser you could use Comet (but I do not recommend that solution).
With jQuery (altough not mentioned in your question), you would write something like this to poll every x seconds:
function doPoll() {
$.ajax({
url: "/uploads",
type: "POST",
data: {
//Set an empty response to see the error
xml: "<response></response>"
},
dataType: "text xml",
success: function(xml, textStatus, xhr) {
if (xhr.status == "200") {
//do the thing you wanted to do on succes
}
},
complete: function(xhr, textStatus) {
console.log(xhr.status);
}
});
setTimeout(doPoll,5000);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
P.S. Totally forgot about sockets I also like that solution, but beware sockets are not REST like HTTP.
You should think of it like this: a browser is meant to make stateless
requests, not to keep open a connection, however with commet or
websockets it's possible. With polling which I would recommend you ask
the server a lot of times for the info until you get the desired
response.
From the wiki about Comet:
None of the above streaming transports work across all modern browsers
without negative side-effects. This forces Comet developers to
implement several complex streaming transports, switching between them
depending on the browser. Consequently, many Comet applications use
long polling, which is easier to implement on the browser side, and
works, at minimum, in every browser that supports XHR. As the name
suggests, long polling requires the client to poll the server for an
event (or set of events). The browser makes an Ajax-style request to
the server, which is kept open until the server has new data to send
to the browser, which is sent to the browser in a complete response.
The browser initiates a new long polling request in order to obtain
subsequent events. Specific technologies for accomplishing
long-polling include the following:
I am trying to POST some values using my HTML form to a node JS method. Thereafter, I need to send the return result back from NODE JS and display it in the HTML page.
I am also using EJS to send back the values to the form. However, the result doesn't get displayed.
Basically, After the user clicks on the submit button on the HTML form, values should be passed to Node Js processed and send back a result Success or failed to the HTML doc where it'll display.
My code is as follows:
HTML CODE:
<form id="form-register" action="http://localhost:8089/ttt"" method="post" enctype="multipart/form-data">
<input type="logintext" value="" name="nam" class="nameC" id="mc" >
<input type="submit" name="subscribe" id="mc-submit-number">
<label >REEEEE <%= titles %></label>
</form>
NODE JS CODE:
app.post('/ttt', function (req,res){
loginProvider.signUp(params, function(err, data) {
if (err) {
res.render('index',{title: 'HOME',titles:err.stack
});
res.send('WHATTT');
}
else {
console.log('Result ' + data); // successful response
res.render('index',{title: 'HOME',titles:'SUCCESS'
});
res.end('xzxzxzxzxzx');
}
});
}
You could (or rather have to) use AJAX.
Then you can manually send your form parameters via post request to your Node server and return a response object with either an error or a success message.
The reason your code isn't working is because you have already loaded the DOM of the HTML page and when you are making that request the only way for EJS to work is if you reload the page since EJS just goes through your file and string replaces
My best solution is to have a normal AJAX call to your '/ttt' and have the Node.js do a 'res.send("SUCCESS");' and in your html you can set that label or any part of your document page to "SUCCESS"
With JQuery
$.post("/ttt", function(data, status){
$("#yourLabel").text(data);
});
Stage
Suppose an HTML page in some URL (i.e. http://mysite.com/registry.html) and this HTML file contains a HTML form, like this:
<form action="/">
<input name="firstname">
<input name="lastname">
<textarea name="message"></textarea>
</form>
If I want to prefill this form how can I do this?
Maybe I thought that I can prefill this form on URL request. But I do not know if it is possible.
Restriction
I do not have access to mysite.com server nor registry.html.
Maybe with some JavaScript sorcery, load the page (http://example.com/registry.html) via AJAX:
function loadPage()
{
jQuery.ajax({
type: "GET",
url: "http://example.com/registry.html",
success: successFn
});
}
function successFn(data)
{
var result=jQuery(data).find("#idOfTheInput").html()
//modify the default value
//re attach the input into the html
//render the html
}
The rest is up to you; dig into the dom and put the values you want.
You can try to pass parameters by the url.
Something like this:
http://test.com?param1
This url is passing a parameter (param1), so you can set up the members of this form to be able to receive these parameters.
Regards,
Otacon.
I have a form field (email signup) on the site, and the email provider wants me to submit it to their REST web service and get a response. I've never used JSON or AJAX before so floundering!
The HTML:
<form>
<input type="hidden" name="gid" value="12345678">
<input type="hidden" name="user.CustomAttribute.NewsletterPopUp" value="Global">
<input type="hidden" name="user.CustomAttribute.NewsletterOptIn" value="True">" value="True">
<input type="text" name="uemail" class="email_input_field" value="please enter your email" size="30" maxlength="64" onFocus="clearText(this)">
<input type="submit" name="signup" value="signup" class="email_submit_button">
</form>
Currently, using Javascript and using window.location to visit the URL (which creates the action instead of posting it) they want it converted to a form post action with XML response. What happens now:
$(".email_submit_button").click(function(){
var uemail = $('.email_input_field').val();
window.location = "http://example.com/automated/action.jsp?action=register&errorPage=/automated/action.jsp&gid=12345678&uemail="+uemail+"&user.CustomAttribute.NewsletterPopUp=Global&user.CustomAttribute.NewsletterOptIn=True";
return false;
}
});
I see you'r using jQuery so you can use the $.post to post to the server like this:
var url = "http://example.com/automated/action.jsp"
var data ={
"gid": form.gid,
"action": register,
"uemail": form.uemail,
"errorPage": "/automated/action.jsp",
"user.CustomAttribute.NewsletterOptIn": user.CustomAttribute.NewsletterOptIn,
"user.CustomAttribute.NewsletterPopUp": user.CustomAttribute.NewsletterPopUp
};
var success_func = function(data){
//do what you want with the returned data
};
$.post(url, data, success_func);
Documentation for $.post.
Or you can use the pure longer Ajax version it's mentioned in the documentation of the $.post.
EDIT:
I forget you can't do xhttpresuext to a different domain you need to use JSONP, here's a link to another SO post explaining everything by detail
Hope this help.
$(".email_submit_button").submit(function(e) {
// stop form from submitting
e.preventDefault();
// Grab all values
var uemail = $('.email_input_field').val();
// make a POST ajax call
$.ajax({
type: "POST",
url: "YOUR URL", // set your URL here
data: {
uemail: uemail // send along this data (can add more data separated by comma)
},
beforeSend: function ( xhr ) {
// maybe tell the user that the request is being processed
$("#status").show().html("<img src='images/preloader.gif' width='32' height='32' alt='processing...'>");
}
}).done(function( response ) {
// do something with the received data/response
//$("#status").html(response);
});
});
Not sure if ".email_submit_button" is the class given to the submit button or the form.. you need to use the id or class given to the form and not the submit button.. hope this helps