I can't figure it out, i have a form submitted by ajax and the ajax code always return false even if the form values doesn't meet the requirement.
Also the function that should happend in the form action php file when the form is correct doesn't happend so it doesnt matter if i fill in the required fields or not, or if i fill them right or wrong the ajax will call it success and the php action wont work{even if the form is correct!}
Form :
<form method="POST" onsubmit="return loginSubmit(this)">
<input type="text" name="username" placeholder="username"></br>
<input type="password" name="password" placeholder="password"></br>
<button type="submit" name="submit">login</button>
</form>
Function :
function loginSubmit(element){
var values = $(element).serialize();
$.ajax({
type: 'post',
url: 'assets/login.inc.php',
data: values,
success: function(data){
alert('success');
}
});
return false;
}
Form Action{php} :
it's kind of long and i dont want this post to look like a mess so i'm just writing the way i pull the data from the form, the php code works fine when i submit the form without ajax.
$username = mysqli_real_escape_string($conn, $_POST['username']);
$password = mysqli_real_escape_string($conn, $_POST['password']);
The jQuery success callback doesn't do what you think it does. It is triggered if the HTTP call is successful and received a normal 'OK' response.
You need to parse the data parameter within the callback to determine what your PHP code returned.
From the jQuery documentation for the 'Ajax' method call:
A function to be called if the request succeeds. The function gets passed three arguments: The data returned from the server, formatted according to the dataType parameter or the dataFilter callback function, if specified; a string describing the status; and the jqXHR (in jQuery 1.4.x, XMLHttpRequest) object.
Ref: http://api.jquery.com/jquery.ajax/
Ok i got it, in the php file i checked if the form was submitted which seems not true if you submit it trough ajax. Thanks
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.
so on submit of my form class .login this triggers an ajax call to login.php Inside of login.php there is a call to welcome.php to ensure that the encrypted password matches that in the database and that the user name entered exists in the database. It would also be helpful to mention my ajax call is succeeding in it's attempts to run, but no redirection to my welcome.php occurs. So, my question to you all, is am I going about this in the correct manor?
$('.login').on('submit', function(){
// serialize the form
var formData = $(this).serialize();
$.ajax({
type : 'POST',
url : 'login.php',
data : formData,
success: function() {
alert("Success");
},
error: function(xhr) {
alert("fail");
}
})
.done(function (data) {
})
.fail(function (error) {
console.log(data);
});
return false;
});
<html>
<body>
<?php
require 'connect.php';
if((isset($_POST['user-login']) && !empty($_POST['user-login']))||
(isset($_POST['pass-login']) && !empty($_POST['pass-login']))){
$sth = $dbh->prepare('SELECT name FROM test_table WHERE name=?;');
$passLogin = $_POST['pass-login'];
$nameLogin = $_POST['user-login'];
$sth->execute(Array($nameLogin));
if(password_verify($passLogin, $hashed_password) && $sth->rowCount() > 0) {
header("Location:welcome.php");
exit;
}
}
else{
echo 'error';
}
?>
</body>
</html>
*****************************************************************
<html>
<body>
<?php
echo 'welcome';
?>
</body>
</html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js" type="text/javascript">
<form class = "login">
<label for="user-login">Username</label>
<input id="user-login" name="user-login"></br>
<label for="pass-login">Password</label>
<input id="pass-login" name="pass-login"></br>
<input type="submit" name= "submit" value="submit" id = "submit">
<a id = "register-a">Register Now</a>
</form>
You will need to redirect your page using javascript. An Ajax request cannot redirect the users browser from server side. I recommend if your login is successful, pass back a success flag for your ajax success() function to handle then have THAT do the redirect using window.location.href.
Just a heads up in case you weren't aware, your script will always return successful. Even if you echo 'error';. You'd need to actually form a failing HTTP status code for the error function to execute, or alternatively have an error in your code!
The point of Ajax is to make an HTTP request without leaving the current page. The browser doesn't appear to redirect because the results are returned to the Ajax handler which does nothing with them (your done function is empty).
Your goal appears to be to make an HTTP request and then display the Welcome page.
You should not use Ajax. Just use a regular form submission.
If there is a problem with the submitted data (and most of the time there will not be, so it isn't worth applying Ajax for that case) then redisplay the form.
This is possible, however you are never reaching the redirect call because
$hashed_password in the if statement is not defined.
This will throw an error message but you will need to use a tool like chrome inspector > network > login.php to see the response.
Hope this helps debug in the future :)
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 am trying to send a form via Ajax, but can not figure out how to set the receiver to be a PHP script. When trying to pass thee data I get 404 page not found. I do not know how to define the PHP script where I want the data to be sent.
I tried defining the script path at the start of the page
<?php
module_load_include('php', 'mysite', 'modules/test/customer');
?>
AJAX part
$(document).ready(function() {
// process the form
$('form').submit(function(event) {
// get the form data
// there are many ways to get this data using jQuery (you can use the class or id also)
var formData = {
'id' : $('input[name=mav_id]').val(),
'sku' : $('input[name=sku1]').val(),
};
// process the form
$.ajax({
type : 'POST', // define the type of HTTP verb we want to use (POST for our form)
//redining the base path
url: Drupal.settings.basePath + "modules/test/customer" ,
data : formData, // our data object
dataType : 'json', // what type of data do we expect back from the server
encode : true
})
// using the done promise callback
.done(function(data) {
// log data to the console so we can see
console.log(data);
// here we will handle errors and validation messages
});
// stop the form from submitting the normal way and refreshing the page
event.preventDefault();
});
});
HTML form
<table>
<tr><th align="LEFT"><b><i>Cu data</b></i></th></tr>
<form action="modules/test/customer.php" method="post">
<div class='cu'>
<tr><td>Mav ID: <input type="text" name="mav_id"></td>
<td>sku: <input type="text" name="sku1"></td>
<tr> <td><input type="submit" value="Submit"></td> </tr>
I still get this error:
could not find the site you requested "/node/modules/test/customer.php
How can I get rid of the node part and get the script to send the data to right address?
remove the below code form page callback function
module_load_include('php', 'mysite', 'modules/test/customer');
and add it to hook_init
it will solve your problem.
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!