I have 2 pages, process page and form page.
So basically the form page consists of a lot of input text and once the user click the submit button, it runs the ajax call and call the process page. the process page requires user's credentials like id and password.
My ajax call basically success run, but the process page is not running. When there is no user logged in, the process page will output the undefined index message. In this case is the id or password, because basically there is no data passed(ID and Password) to the process page.
This is my ajax call function
function postTweet(){
$.ajax({
url : 'blablabla',
type : 'POST',
data : blablabla,
success: function() {
div1.append("Success!");
}})
.fail(function(data){
console.log(data);
});
}
So basically after the non-loggedin user click the submit button, the Success message will still be displayed out, eventhough basically there is no process running in the process page.
What I want is, if the process basically is not running, I should prompt out a proper message.
Can someone help me please?
Any help given is highly appreciated. Thanks
Your success function can handle arguments (look at ajax success here)
For example:
PHP File
<?php
echo json_encode(array('test' => "hello world")); // echo any array data
exit(); // Stop php from processing more, you only want the json encoded data to be echoed
?>
Javascript File
...
dataType: 'json', // This is needed to convert the echoed php data to a json object
success: function (response) { // "response" will be the converted json object
console.log(response);
},
...
The console.log(response); would look something like Object {test: "hello world"}
EDIT
In your case, you could do something like this:
<?php
if ( ! isset($username) ) {
echo json_encode(array('success' => FALSE, 'message' => "Username is incorrect."));
}
...
exit();
?>
To alert the above error message in javascript:
...
success: function (response) {
if (response.success) {
alert('success!');
} else {
alert(response.message);
}
},
...
There are 2 ways to handle this issue.
if form page contain login credential input then you can validate login credentials are filled or not in java script and then call ajax process.
you can validate login credentials in ajax file using isset() method and if login credentials are not validated then you can send a simple message to ajax calls about login failed.
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 have a form that the users complete and then press "Submit" button to register.
I wanted to preview the data to the user before the form is submitted, so i used AJAX to do this. The procedure is as follows:
1) User clicks "submit" button (ex. registration.php)
2) JS script, prevents the default action (which is to submit it) and calls another PHP script via AJAX (registrationAJAX.php), that:
a) Performs some database changes
b) stores some variables in a $_SESSION array
$_SESSION['userID'] = $uID;
$_SESSION['userEmailAddress'] = $email;
$_SESSION['hash'] = $hash;
c) json_encodes the following array:
$results = array(
'result' => 'success',
'message' => 'registration was successful'
);
echo json_encode($results);
d) then exits
exit();
3) Back to JS script and on AJAX success, i check to see whether the result is "success" and then redirect the user to a script that sends an automated email for account verification:
$.ajax({
type: "POST",
url: "js/ajax/registrationAJAX.php",
data: {form data...},
cache: false,
success: function(output){
var outputJSON = $.parseJSON(output);
var status = outputJSON.result;
if(status == 'success')
{
location.href = "https://domain.com/verify.php";
}
}
});
The verify.php script MUST have access to the $_SESSION variables to be executed correctly.
//the code will only executed if the $_SESSION['hash'] is set:
if(isset($_SESSION['hash']))
{
//SEND EMAIL ACTIVATION EMAIL TO USER
//INFORM THE DATABASE THAT THE EMAIL IS SENT
}
Sometimes i see that some of my users don't receiver the activation email. This will happen if the verify.php script doesn't have the $_SESSION variables i stored during registrationAJAX.php and then fail (as shown at the code above).
Question:
1)Is there a possibility that the variables delay to get stored in the $_SESSION and the redirection to verify.php is performed with no $_SESSION variables?
2) Does the exit() command cause a problem?
You should consider move to OAuth authentication to avoid the issue with the cookies disabled:
http://www.sitepoint.com/creating-a-php-oauth-server/
Regards,
I am developing a web app using HTML, PHP and JavaScript. I found a way to call PHP methods that run database operations from the client-side (HTML and JS) using AJAX, here's an example:
if (confirm('Sure you want to do that?')) {
$.ajax({
url: "myScripts.php",
type: "POST",
data: {
paramForOperation: myParam,
option: "doAction1"
},
cache: false,
success: function(response) {
//Here I reload or load another page after server is done
window.open("myPage.php", "_self");
}
});
}
So here I call the php file with the script that does an INSERT/ DELETE / WHATEVER on the database. It works fine, but what if I couldn't insert because the index already exists or any other reason? What if some type of data is wrong and I can't insert it? I know I can validate that on the server side using PHP, but how do I return a message saying "Operation complete" or "You should use numbers on X field"?
I thought of something like alert(response); but what will it return? An echo($msg); from my PHP functions? Is there a way to send the result message on that response thing in AJAX?
Thank you for your help.
Any output of the PHP script will be received in response. Remember, the PHP script runs on the server and just generates output. The PHP code itself never reaches the client.
So, you can just echo a message, and alert it in Response.
Bringing it up a notch, you can return a small piece of JSON or XML that can be parsed and which can contain an error message and some error code, so you script can also respond to that, and maybe change its behaviour (if the insert succeeded, add the new data to the page, for instance).
And of course, instead of returning always code 200 (meaning OKAY) from PHP, you could consider returning other HTTP status codes, so the code already indicates whether something went wrong or not. Depending on the status code, jQuery will execute either the success or the error handler, so it's easy to make different handlers for different situation.
Let your server respond with appropriate HTTP Status Codes and meaningful error messages. Use the error function of the ajax call.
$.ajax({
url: "myScripts.php",
type: "POST",
data: {},
success: function(response) {
/* no error occured, do stuff... */
}
error: function(jqXHR, textStatus, errorThrown) {
/* handle the error, add custom error messages to any DOM objects, ... */
console.log(textStatus, errorThrown);
}
Some docs: $.ajax and HTTP Status Codes
I am creating a login page in PHP. On entering wrong username/password I am showing a javascript alert box. I now want to navigate user back to login page on clicking "OK" button of alert box . Am using "header(location:url)", but then javascript code is not working.
Is there any other way to do this.
You can try this
echo "<script language='javascript' type='text/javascript'>alert('error');
</script>";
echo "<meta http-equiv='refresh' content='1; URL=login.php'>";
For JS redirect, try;
window.location.href="http://url";
Hope this helps :)
Put this code in the login error page ..
<script>
alert('Wrong Username/Password');
window.location = "http://www.google.com";
</script>
But if you are familiar with jquery i advice you to do the login process with ajax request and show the notifications in the same page instead of navigating back and forth.
If you need i can create a simple one in plnkr
For the js redirect, u can use
window.location.href='http://whereEver';
Note: Username/ password validations are server side. Assuming its an ajax call, after you get the validation results, instead of triggering an alert, have a div in the page itself where you can inject the server response. Alerting looks unprofessional.
Better approach would be something like
HTML
<div class="response"></div>
CSS
.response {
display:none;
}
.error {
color: red; // find a better color
}
PHP
On validation failure, have a variable, lets call it status and make it false.
The validation response can be something like,
$response = ['status' => false, 'message' => 'Username / password mismatch'];
Then send back the results
die(json_encode($response));
Note: If you are using PHP < 5.4, use
$response = array('status' => false, 'message' => 'Username / password mismatch');
JS
$.ajax({
url: 'url-to-post',
type: 'POST',
data: $('form[name="your-form-name"]').serialize(),
dataType: 'json',
success: function(data) {
if (!data.status) {
// inject into response
$('.response').addClass('error').html(data.message).show();
}
else
{
// redirect them to home page, i assume
window.location.href = '/home';
}
}
});
I have an HTML form that is processed via PHP, and it's a simple login script. This works fine, but I want to catch the error with AJAX. Basically, if the PHP function to check the login returns false, it should write that error onto the DOM via jQuery. However, if I catch the form submission with AJAX, it will stop the PHP file from doing the redirect. I want to stop the form from redirecting only if the PHP file returns false. Any help would be much appreciated. Here's some code to illustrate what I'm talking about:
controller_login.js
$(document).ready(function(){
$('form.loginSubmit').on('submit',function(){
var that = $(this),
url=that.attr('action'),
type=that.attr('method'),
data={};
that.find('[name]').each(function(index,value){
var that=$(this),
name=that.attr('name');
value=that.val();
data[name]=value;
});
$.ajax({
url: url,
type: type,
data: data,
success: function(response){
errorHandle(response);
}
});
return false;
});
});
function errorHandle(error)
{
console.log(error);
}
This is the file that will eventually modify the DOM if there is a PHP error. For now, it just logs.
checkLogin.php
if($verifySqlRequest==1){
session_register("loginUsername");
session_register("loginPassword");
header("location:http://localhost/asd/dashboard.html");
echo "login success!";
}
else{
echo "Wrong user name or password...";
}
This is just a snippet of the login authentication, but essentially I want that last echo to be communicated to controller_login.js, but it should continue the redirect if the login is successfully authenticated. Any help would be much appreciated!, thanks!
The browser isn't going to respond to a 302 or 301 (redirect) from an Ajax call. You can still certainly respond with that code, but, you'll have to handle the redirect manually via script:
window.location.replace("http://localhost/asd/dashboard.html");
or you can do it like this
> echo '<script>window.location.replace("http://localhost/asd/dashboard.html")</script>';
and
$.ajax({
url: url,
type: type,
data: data,
success: function(response){
$('#response_element').html(response);
}
The point of using Ajax is to avoid reloading the page. If the user is going to be redirected upon login you may as well just submit the form synchronously and let PHP display the error.
Just for the sake of argument, if you wanted to do an Ajax function and display a message returned from the server you would NOT do:
<?php
echo 'this is the message';
?>
You would do
<?php
$response = array('message' => 'this is my message');
return json_encode($response);
?>
However, you can't redirect AND return data.