cancel submit at server - javascript

I wanted to submit a form to the server, in order to run some server-side code. By using a form, it is a lot easier to harvest the variables in the form, instead of harvesting a bunch of fields by hand with Javascript.
But, I don't want the page to refresh or redirect. I would like to be able to return some Javascript that lets the page signal the outcome of the server-side code.
In short, an xmlHttp request that includes all the fields from the form.
Is that possible?

Yes, you can use XMLHttpRequest object to send the requests to the server. Feel free to learn it from MDN, https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest
Secondly, to stop the page refresh of redirect, you can use this code
event.preventDefault();
..this will stop the page from loading etc but still it will send the request to the page you're trying to access.
Example code
<form method="post">
<input type="text" name="someName" />
<input type="submit" value="Submit" onclick="sendData()" />
</form>
..in the JavaScript write
function sendData() {
// at the top of the code
event.preventDefault();
// execute the XMLHttpRequest here
}
My Recommendation
I would recommend that you use jQuery for this. jQuery is same as JavaScript as it is a library built right on JavaScript, it will minimize the long code you're going to write.
Learn it here, jquery.com
In jQuery it is as easy as
function sendData() {
$.ajax({
url: 'page.html',
// as barmar has suggested in comments
data: $("#formID").serialize(),
success: function (data) {
alert('Message from server' + data);
}
});
}
The above code would send the request, and you will get the results in the success function's data object.

Related

Problems with $.post

I am doing some checks on my website to assure that the web browser can run it. If the browser pass the requirements, I want to reload the webpage and send a post argument with jQuery like this.
I have tried the $.post function on jQuery like this:
$.post("index.php", {
correcto_obligatorio: true
});
window.location.reload("index.php")
However, when the browser reloads the web, there is no correcto_obligatorio parameter on $_POST. I used the var_dump php function to print it and all I get is NULL
$.post is a separate asynchronous request.
window.location.reload just reloads a page, but doesn't consider all of your async requests.
If you print $_POST['correcto_obligatorio'] not with var_dump, but log to file you will see the value there.
There is two solutions for you.
1) Await for the ajax result and respond to it.
$.post( "index.php", {
correcto_obligatorio: true
}, function (data) {
if (data.passed_validation) {
window.location.reload("index.php")
}
});
2) Second is to post a form
<form action="/index.php" method="POST" id="my_form">
<input type="hidden" name="correcto_obligatorio" value="1"/>
</form>
<script>
function myFunc() {
$("#my_form").submit()
}
</script>
The most common and rightful one is the first solution.
your code does not wait for the post to finish. You basically send the request and redirect the browser to index.php without waiting for the server to answer you. Consider using a callback function:
$.post( "index.php", {
correcto_obligatorio: true
}, function( result) {
if (result.passed) {
window.location.reload("index.php")
}
});
That is assuming that the server responds with a valid json object that contains the parameter passed (content type should be set to application/json )

Ajax post isn't working

Quick question. I know this is a problem solved many times on stackoverflow, but if I try to make it work it no methodes work out for me. Am I doing it so bad? Here is my code:
$('.submit').click(function(){
$.ajax({
type: 'POST',
url: 'http://localhost/clicky%20game/index.php',
data:
{
userScore:score
},
succes: function(){
alert('succes');
}
});
});
This piece of code is inside a script.js (linked to click.php) and it sould send the data to index.php. But it doesn't, I check this with the code (inside index.php):
if (isset($_POST['userScore'])){
echo $_POST['userScore'];
}
It just keeps showing nothing, hope someone can help me with this, thanks in advance!
That's not how Ajax works. $_POST is a PHP method that stores global variables from page to page. If you pass a javascript variable to a page then PHP will never see it. If this was possible to do then everyone would be hacked in a matter of seconds. You should look into REST APIs. That's what Ajax requests are for. HTTP POST and PHP POST are two very different things, but they do the exact same thing.
What you want to do is store a POST variable with PHP with a Form using the POST method. Then you can send that to index.php.
<form action="index.php" method="POST">
<inputs></inputs>
</form>
Since you are using a regular button to click, you will have to prevent the default submission of the form:
$('.submit').click(function(e){ // added the `e` for the `event`
e.preventDefault(); // this will prevent the default action of the submission of the form.
$.ajax({
type: 'POST',
url: 'http://localhost/clicky%20game/index.php',
data:
{
userScore:score
},
succes: function(){
alert('succes');
}
});
});

jQuery $.post and $.ajax POST requests don't work with app.post() method in Express

I need to send data from the front-end of my Express application, to the back-end, and then render a page using EJS which needs to display that data.
The problem is the app.post() method, and subsequently the res.render() function do not seem to execute fully or properly when I make a "manual" POST request via $.post or $.ajax
Suppose I make this POST request via JQuery
$.post("/test", {
testData: 'Some test data.'
});
Or this POST request via AJAX
$.ajax({
type: 'POST',
data: {
testData: 'Some test data here.'
}),
url: '/test',
})
And I configure my app.post() method to handle that route in Express
app.post('/test', function(req, res) {
res.render('./test.ejs', {
testMessage: req.body.testData
});
});
The variable testData will be sent through and received by the app.post() method. So say if I did this: console.log(req.body.testData), the output would be Some test data, so there's no problem there.
The problem is with the res.render() function, it simply doesn't work at all if the POST request is made through $.post or via AJAX$.ajax. The res.render() function does not execute or render the page through POST requests made through $.post or $.ajax.
Strangely, if did the same POST request via a form (which I do not want to do in my application because the POST request is not supposed to send data received from an input), with the EXACT same app.post() route handler in Express it works perfectly.
For example, using a form like the one below works and allows res.render() to display the page, whereas the $.post() and $.ajax methods do not. Why is that so?
<form id="form-test" role="form" action="/test" method="post">
<input type="text" name="testData" placeholder="Test Data Goes Here" class="form-control" required>
<button class="btn" type="submit">Submit</button>
</form>
I've found another question on StackOverflow extremely similar to mine, but with no clear workaround other than the form option (which I cannot use) : Express.js Won't Render in Post Action
Any suggestions?
The point of using Ajax is that the HTTP response is returned to JavaScript and does not replace the whole page.
If you want to load a new page, then don't use Ajax. Use a form.
If you want to handle the response in JavaScript then you need to add a handler for it.
$.post("/test", {
testData: 'Some test data.'
}).done(function( data, textStatus, jqXHR ) {
// Do something smarter than
alert(data);
});
As others have pointed out, jQuery .post, .ajax, etc doesn't expect a redirect, it expects JSON, so that doesn't work. However, you can get the effect you're looking for with some easy JavaScript. This is how I did it when I had a similar problem:
First, I created a URL string, appending the data I wanted to pass to the server as query parameters
var urlString = 'http://hostaddress/myRoute?data1='+myData1+'data2='myData2;
Second, I did a window.location.replace like so:
window.location.replace(urlString);
Third, I made a GET route in Express to handle the incoming request:
app.get('/myRoute', function(req,res){
var myData1 = req.query.data1;
var myData2 = req.query.data2;
res.render('myView',{data1:myData1,data2:myData2});
Hope that helps.
I faced the same problem and solved it without using $.post or $.ajax. First of all, I took button out from form element:
<form id="form-test" role="form" action="/test" method="post">
<input type="text" name="testData" placeholder="Test Data Goes Here">class="form-control" required>
</form>
<button class="btn" type="submit">Submit</button>
And I binded posting form condition to click event of button. I could also post my desired value. For example:
$(".btn").click(function(){
if($(".form-control").val() ){
$(".form-control").val("Desired Value");
$("#form-test").submit();
}else
alert("TestData is empty");
});

How to get a value to one php page to another without reload with Ajax and JavaScript [duplicate]

This question already has answers here:
How can I make an AJAX call without jQuery?
(24 answers)
Closed 7 years ago.
<html>
<body>
<div id="main_login_div">
<form name="form1" id="main_form" method="post" target="_parent" action="checklogin.php">
<input name="myusername" type="text" id="myusername" placeholder="User Name Here">
<input name="mypassword" type="password" id="mypassword" placeholder="Password Here">
<input type="submit" name="Submit" id="gogogo" value="Login">
<p id="msg" name="msg"><?php echo $_GET['msg']; ?></p>
</form>
</div>
</body>
</html>
So this is my login form, I use GET method to get message password is wrong or not, so problem is that when I click on submit page goes refresh, and I don't want my page to reload, is there any way to get results without reloading page with Ajax and JavaScript not JQuery
Here's a simple ajax request using simple vanilla JavaScript
function request(url, callback) {
var req = new XMLHttpRequest();
req.onreadystatechange = function() {
if (req.readyState !== XMLHttpRequest.DONE) return;
switch (req.status) {
case 200:
return callback(null, req.responseText);
case 404:
return callback(Error('Sorry, 404 error'));
default:
return callback(Error('Some other error happened'))
}
};
req.open("GET", url, true);
req.send();
return req;
}
You can use it like this
var req = request('/some-data.json', function (err, res) {
// check for error
if (err) return console.error(err);
// do something with the data
console.log(JSON.parse(res));
});
Note, you'll have to do a little additional research to support this on older IE browsers.
As far as I know, there are 3 ways to get information passed between client and server:
Page Load
AJAX
Websockets
AJAX is normal JavaScript, and depending on your browser support, you may need to implement it several different ways to support older ones as well as newer ones. Most people use jQuery's $.ajax() functions because it makes it easier to write (and to read).
If you don't want AJAX or page reload, the only other option is using websockets, but there are a lot of dependencies on specific server-side and client-side software. It is relatively new, so there isn't a lot of "beginners guide"s out there.
This might get you started, though: http://www.phpbuilder.com/articles/application-architecture/optimization/creating-real-time-applications-with-php-and-websockets.html
The only way is with AJAX and it's much easier with JavaScript too. It gets REALLY easy with $.post() from the jQuery library.
Example (with jQuery):
<script type="text/javascript">
$("form#main_form").submit(function(e){
e.preventDefault(); //stops the form submitting normally
var formData = $(this).serializeArray(); //make an array of the form data
$.post("checklogin.php", formData, function(response){ //POST the form data to 'checklogin.php'
console.log(response); //output PHP response to console
});
});
</script>

HTML form using jQuery AJAX

I need to retrieve data from server using jQuery AJAX on HTML form then store the response data in a php string variable. So far my code is:
<form method="post" name="myform" id="myform" action="https://domain.com/cgi-bin/cgi.exe">
<input name="exec" value="viewproduct" type="hidden">
<input name="customer" value="customer_name" type="hidden">
<input name="sku" value="sku_number" type="hidden">
<input name="submit" type="button">
</form>
<div id="results"></div>
<script type="text/javascript">
jQuery("#myform").submit(function(e){
var postData = jQuery(this).serializeArray();
var formURL = jQuery(this).attr("action");
jQuery.ajax(
{
url : formURL,
type: "POST",
data : postData,
success:function(data, textStatus, jqXHR)
{
jQuery('#results').html(data.toString());
},
error: function(jqXHR, textStatus, errorThrown)
{
alert('fail');
}
});
e.preventDefault();
});
jQuery(document).ready(function() {
jQuery("#myform").submit();
});
</script>
But I still haven't see any result. If I just use the form normally without any js code, then I'll get the raw response data from the server/database directly on the browser. How can I save that raw response data on the browser into a string variable in php?
Change your submit() handler to include this in the first line:
jQuery("#myform").submit(function(e){
e.preventDefault(); // <---
....
and/or add return false; to the end of it.
If that stops it from reloading but doesn't show anything in your #results div, troubleshoot by changing your success() in the AJAX to use this:
jQuery('#results').html(data.toString());
If that shows something, go to your server code and split up your data into individual properties that your Javascript can separate and use individually (or combine it all into one big string if you want).
.html() takes an input of String, not an object (which data is in this case).
You won't be able to store the Javascript value into a PHP variable because PHP runs on the server and returns a response to the browser where Javascript runs on the browser. What you could do is call your script with AJAX and then set your form values with jQuery using
$("input[name=customer]").val(data);
You could either have an AJAX call for each input or you could parse out the return string to get each value. The first may be more straight forward.
If the action is becoming an issue, remove the entirely and just add an onClick to the submit button that calls a function that makes the AJAX calls.
Hope this helps!

Categories