retrieve database password from php file using ajax - php

I have a js file that creates a form to collect clients contact info. When the form is submitted it sends a url string to the database. However the string needs to include a token and password to login to the database. So i need to somehow hide the token and password in a php file and add it to the string when the client hits submit. so far ive been able to get the data from a php file using .get or .ajax, but the js file already uses an .ajax request and i'm not sure how to combine them together. Any ideas? Thank you!
function initPopup() {
// open on load
if (xanadu_settings['show_popup'] == 'open') {
openXanadu();
}
// open on mouse out
else {
$('html > body').mouseleave(function() {
if (!popup_visible) {
openXanadu();
}
});
}
}
// This gets the login string i need to add to the form subit string below
var dataString = 'login';
$.ajax({
type: 'GET',
url: "login.php",
data: {data : dataString},
success: function(data) {
returnedvalue = data;
console.log(data);
}
});
$("#xanadu_wrapper form").validate({
rules: {
name: "required",
email: {
required: true,
email: true
}
},
messages: {
name: "Please specify your name",
email: {
required: "We need your email address to contact you",
email: "Your email address must be valid"
}
},
submitHandler: function(form, data) {
var report_url = "http://myLinkToTheAPI";
var submit_data = {
// token: $(form).find('input.token').val(),
// pass: $(form).find('input.pass').val(),
campaignId: $(form).find('input.campaignId').val(),
ipAddress: $(form).find('input#ipAddress').val(),
source: $(form).find('input.source').val(),
name: $(form).find('input.name').val(),
email: $(form).find('input.email').val(),
phone: $(form).find('input.phone').val(),
}
var form_submitted = false;
var submit_data = $(form).serialize();
$.ajax({
type: 'GET',
url: report_url,
data: submit_data,
complete: function() {
if ( ($(form).attr('action') != '') && (form_submitted == false) ) {
$(form)[0].submit();
form_submitted = true;
}
$(form).find('input, button').attr('disabled', '');
//Thank you! We will contact you shortly.
$(form).after('<p class="success-alert">' + xanadu_settings['success_message'] + '</p>');
$(form).next('.success-alert').fadeIn();
console.log(form);
console.log(form_submitted);
if (xanadu_settings['prevent_after_submission'] == 'true') {
setBlockCookie();
}
}
});
setTimeout(function(){
if ( ($(form).attr('action') != '') && (form_submitted == false) ) {
$(form)[0].submit();
form_submitted = true;
}
}, 500);
}
});

Just do your updates / inserts in the AJAX call?
When they hit submit, serializeArray() the form, pass your form data to the receiving page, and handle all database interaction on the server. You should never store database information on the client.

Related

php ajax auto login without form action

php ajax auto login works well in form action, but is it possible to execute without form action?
$email = 'xxx#gmail.com';
$password = 'password';
<script>
var user = <?php $email; ?>;
var pass = <?php $password; ?>;
console.log(email=' + user + ', password=' + pass);
$.ajax({
url: 'http://www.example.com/login',
type: 'POST',
data: JSON.stringify({ email: user, password: pass }),
success: function(data, status) {
// do something after login
console.log('success');
},
error: function() {
console.log('error');
}
});
return false;
</script>
You should use GET method instead.
$email = 'xxx#gmail.com';
$password = 'password';
<script>
var user = <?php $email; ?>;
var pass = <?php $password; ?>;
$.ajax({
url: 'http://www.example.com/login',
type: 'GET', //send it through get method
data: {
email: user,
password: pass
},
success: function(response) {
//Do Something
},
error: function(xhr) {
//Do Something to handle error
}
});
</script>
Then check in your login page if email and password parameters have been set by GET or POST methods.
<?php
if (isset($_GET['email']) && isset($_GET['password']) || isset($_POST['email']) && isset($_POST['password'])){
// check your database and take actions.
}else{
// do nothing and show the post from again.
}
?>
Following code may work on page load if the username and password is auto-filled.
I hope this may help you.
<script>
$(document).ready(function(){
var user = $('[name="username"]').val();
var pass = $('[name="password"]').val();
if(user !== '' && pass!== ''){
$.ajax({
url: 'http://www.YourUrl.com/login',
type: 'POST',
data: {
email: user,
password: pass
},
success: function(response) {
//When successfully logged in
},
error: function() {
//If error on server side script
}
});
}
});
As here we have created POST request, you need to handle is by $_POST server side.

ajax form validation in laravel 5

I am new in laravel and need help.
These are the values I'm getting via ajax, all values are to be stored in db, but how do I validate[check] if there are existing values or not before submitting a form using ajax?
$("#submit").click(function(e){
e.preventDefault();
var url = "{!! URL::to('/') !!}";
var id="{!! #$department->id !!}";
var token = "{!! csrf_token() !!}";
var customer_id = $("#customer_id").val();
var visiting_address1 = $("#visiting_address1").val();
var department_id = $("#department_id").val();
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: url+"/customer/"+customer_id+"/popup_store",
data: { '_token':token, 'rest':'true', 'customer_id':$("#customer_id").val(), 'main_address':$("#main_address").val(),'visiting_city':$("#visiting_city").val(),'visiting_address':$("#visiting_address1").val(),'visiting_zip':$("#visiting_zip").val()},
async : false,
success : function(data) {
if(data == "success")
{
$("#addrecords").modal('hide');
}
else
alert(data);
}
});
});
First of all define you Jquery validation for you form like this:
$("#myForm").validate({
// Specify the validation rules
rules: {
name: "required",
},
// Specify the validation error messages
messages: {
name: "Please enter name",
},
submitHandler: function (form) {
// leave it blank here.
}
});
And then in your click button of submit button, write if condition to check validations:
$("#submit").click(function (e) {
if ($('#myForm').valid()) {
// your Ajax Call Code
} else {
return false;
}
});

How to make PHP action in AJAX

I created a PHP page that Insert into the database the value in the textbox, when someone click on the button it's redirect to the php page, But I want it to make the PHP action without redirecting, So how can I do it in ajax?
Thank you
woz and dragoste are right. Use jQuery to make it happen. you can use this function, it will fit to your requirement.
Here i used jQuery validation library http://jqueryvalidation.org/ to validate the form .
$(function()
{
var form = $("#booking_form").validate();
$('#success').hide();
$('#failure').hide();
$("form#your_form").submit(function() {
if(form.valid())
{
var name = $("#txtName").val();
var email = $("#txtEmail").val();
var phone = $("#txtPhone").val();
$.ajax({
url: "process_form.php",
type: "POST",
data: {
'name': name,
'email': email,
'phone': phone
},
dataType: "json",
success: function(data) {
if(data.status == 'success')
{
$('#your_form').hide();
$('#success').show();
}
else if(data.status == 'error')
{
$('#failure').show();
}
}
});
return false;
}
});
});

Form Validation To Send Only If Username Doesn't Exist

I've created a JQuery script that checks a database for usernames and shows an error if you type in an existing name on keyup, this is workng fine but the form still submits even if this error is true. What other code can I add to check that this error doesn't exist? Here is the code I have so far:
<script>
$(function()
{
var ck_username = /^[A-Za-z0-9_]{5,15}$/;
// Username validation
$('#username').keyup(function()
{
var username=$(this).val();
if (!ck_username.test(username))
{
$('.usernameStatus').removeClass("success").addClass("error");
}
else
{
$('.usernameStatus').removeClass("success").removeClass("error");
jQuery.ajax({
type: 'POST',
url: 'check-users.php',
data: 'username='+ username,
cache: false,
success: function(response){
if(response == 1){
$('.usernameStatus').removeClass("success").addClass("error");
}
else {
$('.usernameStatus').removeClass("error").addClass("success");
}
}
});
}
});
// Submit button action
$('#registerButton').click(function()
{
var username=$("#username").val();
if(ck_username.test(username))
{
jQuery.post("register.php", {
username:username,
}, function(data, textStatus){
if(data == 1){
window.location.replace("registered.php");
}else{}
});
}else{
alert("Something went Wrong - Please Check All Fields Are Filled In Correctly");
}
return false;
});
//End
});
</script>
Thank you
please see the comments on the code
assuming that the data == 1 means that the name is already registered and you will show an error
<script>
$(function()
{
var name = false; // a variable that holds false as the initial value
var ck_username = /^[A-Za-z0-9_]{5,15}$/;
// Username validation
$('#username').keyup(function()
{
var username=$(this).val();
if (!ck_username.test(username))
{
$('.usernameStatus').removeClass("success").addClass("error");
}
else
{
$('.usernameStatus').removeClass("success").removeClass("error");
jQuery.ajax({
type: 'POST',
url: 'check-users.php',
data: 'username='+ username,
cache: false,
success: function(response){
if(response == 1){
$('.usernameStatus').removeClass("success").addClass("error");
}
else {
$('.usernameStatus').removeClass("error").addClass("success");
name = true; // on success , if the name isnt there then assign it to true
}
}
});
}
});
// Submit button action
$('#registerButton').click(function()
{
var username=$("#username").val();
if(ck_username.test(username) && name == true) // check for the value of name
{
jQuery.post("register.php", {
username:username,
}, function(data, textStatus){
if(data == 1){
window.location.replace("registered.php");
}else{}
});
}else{
alert("Something went Wrong - Please Check All Fields Are Filled In Correctly");
}
return false;
});
//End
});
</script>
Instead of checking the username against the regex, you should check the status of $('.usernameStatus') because it is possible that it passes the regex test but still fails the duplicate test returned from your db.
So
$('#registerButton').click(function()
{
var username=$("#username").val();
if(ck_username.test(username))
{
should instead be:
$('#registerButton').click(function()
{
var username=$("#username").val();
if(!$('.usernameStatus').hasClass('error'))
{
Even better would be to introduce a variable that holds the validity of the name field so you don't need to get the DOM Element all the time and check it's class.
I think your error might be because of a bad data syntax
It should be like this:
data: 'username:'+ username,
Debug your PHP code to see if its receiving the username properly at the moment though

validate form without refreshing page and showing error through validationEngine

I'm using in the same page a validation engine with date picker.
Datepicker: http://jqueryui.com/demos/datepicker/
Validationengine: http://www.position-relative.net/creation/formValidator/demos/demoValidators.html
I've added a jQuery.noConflict(); to make it work (at the beginning of the code).
Now, I need to make my insert through a PHP file, but without refreshing the page, and by displaying an error message in the same bubble of validationEngine (for example when the email is already registered in the BDD).
should I import jQuery to make my insert in the same page
without causing conflicts, or can I use one on the query already used
for the same purpose?
How do I display a server response through the validationEngine?
My code is the following one.
$(".btn_newsletter").live('click', function() {
$.ajax(
{
url: "php/functions/signin.php"+nomfichier,
success: function(data) {
if (data.check==0) {alert('Error : Sorry '); return false;}
if (data.check==1) {alert('yep!!!');
}
},
cache: false,
type: "POST",
dataType: 'json'
});
}
This is my PHP code.
$ip= $_SERVER["REMOTE_ADDR"];
$select = "select * from av_newsletter where email='".$_POST['email']."'";
$exist = $_BASE->query_array($select);
if ($exist) {
$check = "0";
}
else {
$ajout="INSERT INTO av_newsletter(id,sub_date,email,ip) VALUES (NULL,now(),'$email','$ip')";
$add=$_BASE->query($ajout);
if ($add) {
$check="1";
}
}
$return_arr["check"] = $check;
echo json_encode($return_arr);
It doesn't work; I've no alert, but also no errors.
If you are not tied in too deeply to your 'Validationengine' I would recommend using this one, is has served me well for years, it has support for making remote checks so you could do something like this:
$(document).ready(function(){
var save_options = {
success: userSaved, //callback function
url: '/users/save',
response: 'json',
method: 'post'
};
var validationObj = {
rules: {
name: "required",
email: {
email: true,
required: true,
remote: "/user/check_email/"
}
},
messages: {
name: "Please name yourself",
email: {
required: "Please enter your email address",
email: "Invalid email address",
remote: "Email already in use."
}
},
errorPlacement:function(error, element) {
error.appendTo( element.next() );
},
submitHandler: function(form) {
$(form).ajaxSubmit(save_options);
},
success:function(label) {
label.html(" ").addClass("checked");
}
};
});
And then on the PHP side at the '/users/check_email' endpoint the PHP does the following:
echo $emailExists ? json_encode(false) : json_encode(true);
Ok, before we spam the comments and get to far off topic, please execute this code which should get you started in getting it to work eventually.
$(".btn_newsletter").live('click',function() {
alert('clicked'); // click is executed
$.ajax({
url: "php/functions/signin.php"+nomfichier,
success: function(data) {
alert(data); // should alert the data
if(data.check==0){ alert('Error : Sorry '); return false; }
if(data.check==1){ alert('yep!!!'); }
},
error: function(request, status, error) {
alert('failed '+status);
},
cache: false,
type: "POST",
dataType: 'json'
});
});
it works :)
$(".btn_newsletter").live('click',function() {
var data ="email="+$('#email').val();
$.ajax({
url: "php/functions/signin.php"+"?"+data,
success: function(data) {
if(data.check=='1'){ alert('yep!!!'); }
if(data.check=='0'){ alert('Error : Sorry '); return false; }
},
cache: false,
type: "POST",
dataType: 'json'
});
});
and in my signin.php I catch the value of the input like this $email=$_REQUEST['email']
Thanks a lot! time for me to see about validation engine how to link this with :)

Categories