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 )
Related
I basically don't seem to understand sending a variable to another page.
I've tried PHP sessions, javascript cookies and ajax POST and GET.
I'm trying to send the innerHTML of a div, with the data created by a jQuery call,
a variable called savedartists. It displays correctly in the console.log on the sending page but the $_POST['savedArtists']
is undefined in the receiving page. I have spent hours looking at different posts on this site but I haven't been able to get it to work.
Any help is appreciated.
<input class="et_pb_button et_pb_button_0 et_pb_bg_layout_light" onClick="savequote();" type="button" id="savedchoices" value="Commander la prestation" >
<script>
function savequote() {
var savedartists = document.getElementById('selectedList').innerHTML;
console.log(savedartists);
$.ajax({
type: "POST",
url: 'example.com/artiste/mise-en-relation/',
data: { savedArtists : savedartists },
success: function(data) {
console.log("success!");
location.href = "example.com/artiste/mise-en-relation/";
}
});
}
</script>
On the receiving page (example.com/artiste/mise-en-relation/)
<?php
if(isset($_POST['savedArtists']))
{
$uid = $_POST['savedArtists'];
echo $uid;
} else {
echo 'zit!';
}
?>
Thanks for your time
Capturing as an answer for future readers...
Fundamentally what's happening here is that two requests are being made to the target page. The first one is the AJAX request:
$.ajax({
type: "POST",
url: 'example.com/artiste/mise-en-relation/',
data: { savedArtists : savedartists },
success: function(data) {
//...
}
});
This is a POST request which contains the data you expect, and works just fine. However, the result of this request is being ignored. That result is available in the success callback, but the code doesn't do anything with it:
console.log("success!");
location.href = "example.com/artiste/mise-en-relation/";
Instead, what the code is doing is performing a redirect. This creates a second request to that same page (though it's essentially irrelevant that it's the same page). This is a GET request and contains no data to send to the server.
At its simplest, you should either use AJAX or redirect the user. Currently you're mixing both.
I want to redirect to the other page.
In that case AJAX is the wrong tool for the job. You may not even need JavaScript at all, unless you want to modify the elements/values of a form before submitting that form. But if all you want is to POST data to another page while directing the user to that page, a plain old HTML form does exactly that. For example:
<form method="POST" action="example.com/artiste/mise-en-relation/">
<input type="text" name="savedArtists">
<button type="submit">Submit</button>
</form>
In this case whatever value the user enters into the <input> will be included in the POST request to example.com/artiste/mise-en-relation/ when the user submits the form.
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");
});
I have tried most answers about call javascript function returned from ajax response. Every answer worked but I must call alert to show the ajax response to see the result.(If not use alert in the function refreshResults, sometime the result will show but disappear immediately) It seems the page keep refreshing.
Here is the screenshot.
I already tested the browser can receive data successfully from the server. The problem is how to show the data from the browser side.
Here is the code related to receive data from the server and how the server return data.
ajax
function sendAjaxQuery(url, data) {
$.ajax({
type: 'POST',
url: url,
data: data,
success: function (data) {
//eval(document.getElementById("refreshResults").innerHTML);
refreshResults(data);
//$("#firstname").text(data);
// alert('success '+data);
}
});
}
This is how I send data to server.
sendAjaxQuery('http://localhost:3000/results.html',JSON.stringify($('form').serializeObject()));
js
<script type="text/javascript">
function refreshResults(data){
$("#firstname").text(data);
alert(data);
}
</script>
The server side is nodejs. (The server side return a string. Status is 200). The http header is
"Content-Type": "text/plain",'Access-Control-Allow-Origin': '*'
This is the click handler.
function sendData() {
var form = document.getElementById('myform');
sendAjaxQuery('http://localhost:3000/results.html',JSON.stringify($('form').serializeObject()));
}
var sendButton = document.getElementById('sendButton');
sendButton.onclick = sendData;
This is the according html
<form id="myform">
<input type="text" name="Search" value="">
<button id="sendButton" >Search</button>
What is the whole point of the sendAjaxQuery method ?
It just recreates what the $.post does
Just use
// url and data should be whatever you pass to sendAjaxQuery now
$.post(url, data, refreshResults);
whenever you want to make an ajax call..
Update Seeing that you are submitting the contents of a form, the problem might be that you allow the form to be submitted the normal way as well (which causes a refresh of the page).
You will need to cancel the normal action of the button that started this action..
Since you are using jQuery, it is better to use that for binding the event handlers
change
var sendButton = document.getElementById('sendButton');
sendButton.onclick = sendData;
to
$('#sendButton').on('click', function(e){
e.preventDefault();
sendData();
});
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.
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!