Ok so what I'm basically trying to do is sending a form which contains a password (predefined, no DB) through AJAX. In my php file I check the input and I try to return true or false to my JS, but this part fails as I can't manage to access the value. Here is my code:
ajaxRequest.js
// Variable to hold request
var request;
// Bind to the submit event of our form
$(".lockForm").submit(function(event){
// Prevent default posting of form - put here to work in case of errors
event.preventDefault();
// Abort any pending request
if (request) {
request.abort();
}
// setup some local variables
var $form = $(this);
// Let's select and cache all the fields
var $inputs = $form.find("input, select, button, textarea");
// Serialize the data in the form
var serializedData = $form.serialize();
// Let's disable the inputs for the duration of the Ajax request.
// Note: we disable elements AFTER the form data has been serialized.
// Disabled form elements will not be serialized.
$inputs.prop("disabled", true);
// Fire off the request to /form.php
request = $.ajax({
url: "assets/php/lockscreen.php",
type: "POST",
data: serializedData,
dataType: 'text',
success: function (data) {
console.log(data.status);
}
});
// Callback handler that will be called on failure
request.fail(function (jqXHR, textStatus, errorThrown){
// Log the error to the console
console.error(
"The following error occurred: "+
textStatus, errorThrown
);
});
// Callback handler that will be called regardless
// if the request failed or succeeded
request.always(function () {
// Reenable the inputs
$inputs.prop("disabled", false);
});
});
lockscreen.php
<?php
// You can access the values posted by jQuery.ajax
// through the global variable $_POST, like this:
$pass = isset($_POST['pass']) ? $_POST['pass'] : null;
$response = false;
function CheckInput($pass){
if($pass == "SPV" || $pass == "TEACHERS"){
$response = true;
$responseLock['status'] = 'true';
echo json_encode($responseLock);
} else {
$response = false;
$responseLock['status'] = 'true';
echo json_encode($responseLock);
}
}
?>
So far I tried changing the dataType to JSON, but then I got an unexpected end of input error. If I leave it 'text', whenever I try to access the value, I get "undefined". If I only display the console.log, without trying to access any value, I get a success message. I have no idea why though.
call your CheckInput function:
<?php
$pass = isset($_POST['pass']) ? $_POST['pass'] : null;
$response = false;
function CheckInput($pass) {
if($pass == "SPV" || $pass == "TEACHERS"){
$result = true;
} else {
$result = false;
}
return array('status' => $result);
}
echo json_encode(CheckInput($pass));
?>
Related
I have a global ajaxSuccess event and a local success function attached to an ajax request.
I want to cancel the success function if the global find status = false in the response.
like this
$(document).ajaxSuccess(function (event, xhr) {
let result = xhr.responseJSON;
if (result.status === false) {
//here the ajax should be stopped, I don't want to call the local functio
}
}
$.ajax(url, {
'method': method,
'success': function () {
//success function to call if the global ajaxSuccess is ok
}
})
can this be achieved ?
This will give you an insight into what you may be looking for. You will need to return the backend data in json.
why don't you set status to certain values
Eg. false= 0 and true = 1. You can then print success or failure based on values returned from the backend in this sample from PHP backend.
Here am sending a post variable with value of test_ok. If the value is test_ok then alert success else alert fail and
stop further action
<script>
$(document).ready(function(){
var test ='test_ok';
var datasend = "test="+ test;
$.ajax({
type:'POST',
url:'test.php',
data:datasend,
crossDomain: true,
cache:false,
success:function(result){
$('#result').fadeIn('slow').prepend(msg);
if (result.status ==0) {
alert('failed');
return false;
}
if (result.status == 1) {
alert('success');
}
}
});
});
</script>
test.php
<?php
$test = $_POST['test'];
$output = array();
if($test == "test_ok"){
$output[] = array(
"status" => '1'
);
}
if($test != "test_ok"){
$output[] = array(
"status" => '0'
);
}
echo json_encode($output);
I am using Ajax to submit a form using a nonce stored as a PHP session which, as the name suggests, unsets itself and generates a new nonce every time it is used successfully. This works perfectly the first time the Ajax is run.
If I view the source on the page after running it, the new nonce is being updated correctly in the actual code, but for some reason jQuery refuses to read the new value from the #nonce div or update the display on the page with the new $_SESSION value.
The div holding the nonce and the submit button (index.php)
echo '<input type="text" id="nonce" value="'.$_SESSION['nonce'].'">';
echo '<div id="form-test-ajax">
<input type="submit" name="submit" value="submit" id="btn">
</div>';
The jQuery functions in external file (functions.js)
$(document).ready(function() {
$('#btn').click(function() {
$.ajax({
url: 'adminapi.php',
dataType: 'json',
method: 'post',
cache: false,
data : {
"action": "testAction",
"nonce": $('#nonce').val()
},
success: function(data) {
reloadNonce();
},
error : function(xhr, status) {
alert(xhr.status);
console.log("something went wrong");
},
timeout: 30000,
});
});
function reloadNonce() {
$("#nonce").load(location.href + " #nonce");
}
});
The Ajax handler (adminapi.php)
require_once 'inc/globals.php';
header("Access-Control-Allow-Methods:POST");
header("Access-Control-Allow-Headers:Content-Type");
header("Access-Control-Allow-Credentials:true");
header("Content-Type:application/json");
// Check if the request is an AJAX request
function isAjax() {
return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
}
if (isAjax()) {
if (isset($_POST["action"]) && !empty($_POST["action"]) && isset($_POST["nonce"]) && !empty($_POST["nonce"])) {
$action = strip_tags($_POST["action"]);
$nonce = strip_tags($_POST["nonce"]);
// Validate nonce
$securityCheck = validateNonce($nonce);
// Nonce checked out
if ($securityCheck) {
admin_response(200, "Success");
exit();
} else {
// Invalid nonce, failed
admin_response(200, "Error : Security token was incorrect");
exit();
}
}
}
The other relevant PHP functions (globals.php)
// Generate nonce
function generateNonce()
{
$_SESSION['nonce'] = bin2hex(openssl_random_pseudo_bytes(16));
return;
}
// Validate nonce
function validateNonce($nonce)
{
if ($nonce == $_SESSION['nonce']) {
unset($_SESSION['nonce']);
generateNonce();
sessionTimeOut();
return true;
} else {
return false;
}
}
// Set session expiry
function sessionTimeOut()
{
$_SESSION['start'] = time();
$_SESSION['expire'] = $_SESSION['start'] + (15 * 60);
}
// Deliver admin function response
function admin_response($status, $status_message)
{
header("HTTP/1.1 $status $status_message");
$response['status'] = $status;
$response['response'] = $status_message;
$json_response = json_encode($response);
echo $json_response;
}
I've obviously left off chunks of irrelevant code PHP wise, session_start(); etc as the PHP side of this is running perfectly. It's only the jQuery I'm having an issue with.
The JQuery load() method internally uses the innerHTML function to populate the matched element with the ajax response. So I would say it's not appropriate for your use-case, as you need to set the value of an input field, instead of update the html contents of a div. I'd check out the JQuery docs for more info: http://api.jquery.com/load/
Just in case anybody else runs into a similar problem the answer was to return the new nonce in the ajax success response and then set the value to the nonce id.
Works now!
The jQuery
success: function(data) {
$("#nonce").val(data.nonce);
reloadNonce();
...
The PHP
admin_response(200, "Success", $_SESSION['nonce']);
...
and..
function admin_response($status, $status_message, $nonce)
{
header("HTTP/1.1 $status $status_message");
$response['status'] = $status;
$response['response'] = $status_message;
$response['nonce'] = $nonce;
$json_response = json_encode($response);
echo $json_response;
}
i'm building a signup form for my website i validate my signup page with jquery i want to do that when all the fields are filled with valid way then the signup page redirect or load and store the data in database...
1. first jquery code checks input fields
2. then in the jquery code there is a ajax call which check if the email already exist or not if the ajax call return true then data will be inserted in database if it return false the the page will not load and display the message that email is already exist
the problem in my code is that when the ajax call is true or false my page keep loading and insert the data in database but i want that if value is false page will not load.
here is my code
$.ajax({
type:'POST',
url:'email_validator.php',
data:{email:mail},
success:function (response){
var result = $.parseJSON(response);
if (result.status===false) {
$('#error').html("Email alreaday exist");
return false;
} if(result.status===true) {
return true;
}
}
});
and here is my email_validator.php
<?php
if(isset($_POST["email"])){
$result = array();
$email=$_POST["email"];
$db=new PDO("mysql:host=localhost;dbname=the_scops","root","");
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$STH=$db->prepare("SELECT email FROM signup WHERE email=?");
$STH->execute([$email]);
if($STH->rowCount() == 1){
//echo "Email alreday exist";
$result["status"] = false;
}
else{
$result["status"] = true;
}
echo json_encode($result);
exit(0);
}
Try this:
$.ajax({
type:'POST',
url:'email_validator.php',
data:{email:mail},
success:function (response){
if (response.status === true) {
return true;
} else {
$('#error').html("Email alreaday exist");
return false;
}
}
});
In my opinion you should invoke the PHP API method to insert the new email directly inside the success function callback:
$.ajax({
type: 'POST',
url: 'email_validator.php',
data: {email: mail},
success: function (response) {
var result = $.parseJSON(response);
if (result.status === false) {
$('#error').html("Email already exists");
}
else (result.status === true) {
// -> Call here the PHP api method to insert the new email in the database
}
}
});
You can add async option to false and return outside the ajax call:
function testAjax() {
var resultStatus = "";
$.ajax({
type:'POST',
url:'email_validator.php',
async: false,
data:{email:mail},
success:function (response){
var result = $.parseJSON(response);
resultStatus = result.status;
if (result.status===false) {
$('#error').html("Email alreaday exist");
}
}
});
return resultStatus;
}
[UPDATE]
But you do not need to check this on client side. Yo can check if email exists in your email_validator.php and immediately write it to the database if it does not exist:
email_validator.php
<?php
if(isset($_POST["email"])){
$result = array();
$email=$_POST["email"];
$db=new PDO("mysql:host=localhost;dbname=the_scops","root","");
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$STH=$db->prepare("SELECT email FROM signup WHERE email=?");
$STH->execute([$email]);
if($STH->rowCount() == 1){
//echo "Email alreday exist";
$result["status"] = false;
}
else{
$result["status"] = true;
// --> INSERT the new email into the database
}
echo json_encode($result);
exit(0);
}
I am using Ajax to post the results from a php form to a database using an API. However when the script runs, I am not getting anything in return stating that it was a success or an error. I can log into the database and see that it has added the entry but I am not getting an alert when it saves to the database.
What I would like the script to do is:
-First save to the database (Done)
-Second: Alert the user that the operation was completed successfully or error
-Third: reset the values in the form if success, keep values if error
Here is what I have tried and have so far:
$(document).ready(function () {
function showSuccess(message) {
$('#success.success').append('<h3 class="alert alert-success">' + message + '</h3>').fadeIn(1000).fadeOut(5000);
}
function showError(message) {
$('#success.success').append('<h3 class="alert alert-danger">' + message + '</h3>').fadeIn(1000).fadeOut(5000);
}
$('form#directory-create').on('submit', function (e) {
//stops the submit action
e.preventDefault();
//format the data into javascript object
var data = $(this).serializeArray();
//calls function to create record, passing participant information as arguments
createRecord(data);
});
function resetStudyInfo() {
//resets all form values to default
$('form#directory-create').find('input:text, input:radio, input:email, input:phone').val('');
return true;
}
function createRecord(data) {
//converts into json data format
var myData = JSON.stringify(data);
console.log(myData);
$.ajax({
//setup option for .ajax func
type: "POST",
url: "directory-create-record.php",
data: {
//user_data : contains all the fields and their data
user_data: myData
},
//shows output message on error or success
success: function () {
showSuccess('Study created successfully, you may now add participants to this study.');
var reset = resetStudyInfo();
return true;
},
error: function () {
showError('Unable to create the study, did you fill out everything?');
return false;
}
});
}
});
PHP side:
require "RestCallRequest.php";
function insertData($data_from_user){
$status = 2;
$url = "xxxx";
$token = "mytokenishere";
$fname = $data_from_user[0]->value;
$lname = $data_from_user[1]->value;
$title = $data_from_user[2]->value;
$school = $data_from_user[3]->value;
$facultystafftrainee = $data_from_user[4]->value;
$email = $data_from_user[5]->value;
$phone = $data_from_user[6]->value;
$record_id = $lname .'_'. $fname;
# an array containing all the elements that must be submitted to the API
$data = "record_id,f_name,l_name,title,school,facultystafftrainee,email,phone,directory_complete\r\n";
$data .= "$record_id,$fname,$lname,$title,$school,$facultystafftrainee,$email,$phone,$status";
$args = array(
'content' => 'record',
'type' => 'flat',
'format' => 'csv',
'token' => $token,
'data' => $data
);
# create a new API request object
$request = new RestCallRequest($url, 'POST', $args);
# initiate the API request
$request->execute();
$result = $request->getResponseBody();
if($result == '1'){
return 1;
}
}
Any help is greatly appreciated. Thank you
When resetting the form values, you have input:email and input:phone, javascript throws a syntax error as you do not need these values, When you remove them your code should work.... Here is the complete working code
$(document).ready(function () {
function showSuccess(message) {
$('#success.success').append('<h3 class="alert alert-success">' + message + '</h3>').fadeIn(1000).fadeOut(5000);
}
function showError(message) {
$('#success.success').append('<h3 class="alert alert-danger">' + message + '</h3>').fadeIn(1000).fadeOut(5000);
}
function resetStudyInfo() {
$('form#directory-create').find('input:text, input:radio').val('');
return true;
}
$('form#directory-create').on('submit', function (e) {
e.preventDefault();
var data = $(this).serializeArray();
createRecord(data);
});
function createRecord(data) {
var myData = JSON.stringify(data);
$.ajax({
type: "POST",
url: "directory-create-record.php",
data: {
user_data: myData
},
success: function () {
showSuccess('Study created successfully, you may now add more participants to this study.');
var reset = resetStudyInfo();
return true;
},
error: function () {
showError('Unable to create the study, did you fill out everything?');
return false;
}
});
}
});
I use this code, which was taken by another post of stackoverflow, but one part was not working for me.
<script>
// variable to hold request
var request;
// bind to the submit event of our form
$("#notification").submit(function(event){
// prevent default posting of form
event.preventDefault();
// abort any pending request
if (request) {
request.abort();
}
// let's select and cache all the fields
var $inputs = $form.find("input, select, button, textarea");
// let's disable the inputs for the duration of the ajax request
$inputs.prop("disabled", true);
//this code was added by me cause i saw that when i pass as data {notTitle:"smth"}
//it works, so i wanted to remake that structure and include all my elements.
// Apparently it does not work, maybe because i create a string and by
//{notTitle:"smth"}, notTitle is not passed as string.
x=$("form").serializeArray();
var str="{";
var size = x.length;
$.each(x, function(i, field){
if (field.value!="")
str = str.concat(field.name + ":" + field.value);
else
str = str.concat(field.name + ":" + "k");
if(i!=size-1)
str=str.concat(",");
});
str=str.concat("}");
// fire off the request to /form.php
request = $.ajax({
url: "test.php",
type: "POST",
dataType: 'json',
data: str//{notTitle:"s",notType:''}
});
// callback handler that will be called on success
request.done(function (response, textStatus, jqXHR){
alert(response.status);
});
// callback handler that will be called on failure
request.fail(function (jqXHR, textStatus, errorThrown){
// log the error to the console
alert(
"The following error occured: "+
textStatus, errorThrown
);
});
// callback handler that will be called regardless
// if the request failed or succeeded
request.always(function () {
// reenable the inputs
$inputs.prop("disabled", false);
});
});
</script>
And here is my php
<?php $result = array("status" => "1", "a" => "2");
$notificationTitle = htmlspecialchars($_POST["notTitle"],ENT_QUOTES,'ISO-8859-1');
echo json_encode($result); ?>
Before you suggest the use of serializing the form, I tried it and it does not work. What I noticed is that when I try to pass data to my php file, I cannot read them through $_POST['name of element']. So if I comment the second line of the php file and pass as data {notTitle:'s'} it works and I see the successful message.