In my code, I get the first_name, last_name, email and password from the user. Then, I get the location of the user with his/her consent in the second page. So, I save all the information of the first page as session variables. Then, I have a button that looks like this:
<button onclick="signUp()" class="btn btn-primary"> Let's go! </button>
And, the signUp function looks like this:
function signUp(){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.post("/sign-up-user",
{
user_latitude: latitude,
user_longitude: longitude
}, function(data){
alert(data);
});
}
And, I have the route for the request as:
Route::post("/sign-up-user", "PagesController#signUpFinalUser");
And, my PagesController function signUpFinalUser looks like this:
// Finally acquire the user with location and store him/her in the database
public function signUpFinalUser(Request $request){
// Get all required variables
$final_first_name = Session::get("user_first_name");
$final_last_name = Session::get("user_last_name");
$final_email = Session::get("user_email");
$final_password = Session::get("user_password");
$final_latitude = (float) $request->user_latitude;
$final_longitude = (float) $request->user_longitude;
// Create a new instance of the User model
$user = new User;
// Fill all the required columns of the database of the user
$user->first_name = $final_first_name;
$user->last_name = $final_last_name;
$user->email = $final_email;
$user->password = $final_password;
$user->latitude = $final_latitude;
$user->longitude = $final_longitude;
// Save the user i.e store the user in the database
$user->save();
// Get the id of the user
$user_id = $user->id;
// Destroy all the sessions variable
Session::destroy();
// Create a session variable named 'user_id'
Session::put("user_id", $user_id);
// Return a response back
return 1;
}
But, the problem is, it shows an error that looks like this:
jquery.min.js:2 POST http://localhost:8000/sign-up-user 500 (Internal Server Error)
But, the surprising thing is, when I comment out the database query and run it again, the response data i.e "1" gets alerted. So, what am I doin wrong?
You destroed session before put user_id
// Destroy all the sessions variable
Session::destroy();
// Create a session variable named 'user_id'
Session::put("user_id", $user_id);
Related
hello I have this php file with the name ** request.php ** that has this Code:
<?php
$Password_user = 'AIzaSyA';
?>
and I have a Index.html file, and I also have a Local Storage with that name user_pass so I created a variable with the name get_spass that looks like this:
var get_spass= localStorage.getItem('user_pass');
so how can i create a request in Ajax that is able to check if the value of the Storage location is equal or not gives it Variable ** Password_user of request.php?
You have to change your php file to:
<?php
$Password_user = 'AIzaSyA';
echo $Password_user;
?>
In your html file you can fetch the file and check the password value with this code:
var get_spass= localStorage.getItem('user_pass');
var passIsCorrect = checkPassword(get_spass);
if (passIsCorrect) {
//do stuff...
}
async function checkPassword(get_spass) {
const passwordPhp = await fetch("request.php");
if (get_spass === passwordPhp) {
return true;
}
return false;
}
Note that everyone can get the request.php content. If the password need to be secret you have to implement some sort of authentication to assure the request.php file can be read only by authorized users or person.
I have a registration form in my Laravel project. I submit that registration form data to laravel controller using ajax from javascript. After successfully stored those registration data in database I return the insertedID from controller to javascript and use console.log() function to show that id. In my javascript, console.log() shows that id and auto disappear after half mili second. But I don't want it to disappear.
Here is my js code
var name = $('#reg_name').val(); //reg_name is the id of the input field
var email = $('#reg_email').val(); //reg_email is the id of the input field
$.get( 'signup', {'name': name, 'email': email,'_token':$('input[name=_token]').val()}, function( data )
{
//Here 'signup' is my route name
console.log(data);
});
Here is my controller function
public function signup(RegistrationFormValidation $request)
{
$data = new User();
$data->name = $request->name;
$data->email = $request->email;
$data->save();
$lastInsertedId = $data->id;
if($lastInsertedId > 0)
{
return $lastInsertedId;
}
else
{
return 0;
}
}
Here I concise my code.
What's the problem in my javascript ?
If you are loading a new page, the default behaviour of the Chrome Dev Tools is to clear the logs. You can enable the Preserve log checkbox at the top of the console to prevent this behaviour.
In other situations, the data emitted to the console is modified after the logging to reflect subsequent updates. To prevent this, one can log a JSON serialized version of the data:
console.log(JSON.stringify(data))
(but probably this is not your case).
I have built a cart using localStorage and I'm using the PayPal PHP SDK to process the payment.
On clicking to pay by PayPal, via AJAX, I am posting $_POST the localStorage data (the cart) and form data (the user's details) to a PHP page where I have the PayPal API setup, which then grabs the $_POST data (to create the items, transaction, payment, redirectURLs) and on success it returns the approved URL to redirect to PayPal (using window.location.href, and this all works fine.
var formData = form.serialize();
var cartData = JSON.parse(localStorage.getItem('drfStorage'));
$.ajax({
url: rootURL + 'api/payment__paypal.php',
type: 'POST',
data: { formData: formData, cartData: cartData },
beforeSend: function() {
console.log('processing');
},
success: function(data) {
console.log('success!');
console.log(data);
window.location.href = data;
},
error: function(xhr,err) {
console.log('readyState: '+xhr.readyState+'\nstatus: '+xhr.status);
console.log('responseText: '+xhr.responseText);
}
});
Then my returnURL which is set as redirect__paypal.php?pp_success=true is visited, which if the $_GET request is 'success' then it validates and takes the payment.
This all works well up until this point. The next stage is that I want to send an email receipt to the user containing some of the data from the localStorage HOWEVER the issue is that on this returnURL there's no longer the localStorage stored in the $_POST request. I could obviously pass all this information as a $_GET request but don't really want this information in the URL (?email=&address=&order=) etc.
Is there any way or advice you can see me being able to access the localStorage OR $_POST data before it went off to PayPal on the returnURL?
Below is what is currently contained within my redirect__paypal.php to aid with explanation.
use PayPal\Api\Payment;
use PayPal\Api\PaymentExecution;
// Require relevent libraries
require_once('./sendgrid/sendgrid-php.php');
require_once('./api__paypal.php');
// SendGrid API init
$sgAPIKey = "REMOVED FROM EXAMPLE";
if (isset($_GET['pp_success'])) {
$approved = $_GET['pp_success'] === 'true';
if ($approved) {
$payerID = $_GET['PayerID'];
$paymentID = $_GET['paymentId'];
$payment = Payment::get($paymentID, $api);
$execution = new PaymentExecution();
$execution->setPayerId($payerID);
$payment->execute($execution, $api);
// Set email confirmation settings
$email_admin = 'REMOVED FROM EXAMPLE'; // Client
$email_customer = 'REMOVED FROM EXAMPLE';
$email_admin_subject = 'You have a new order from Testing McTest via PayPal';
$email_admin_customer = 'Your Testing McTest order';
ob_start();
require_once './confirmation__email--admin.php';
$email_admin_body = ob_get_contents();
ob_end_clean();
ob_start();
require_once './confirmation__email--customer.php';
$email_customer_body = ob_get_contents();
ob_end_clean();
// SendGrid init
function send_email($from_email, $to_email, $subject, $body/*, $attachments*/) {
global $sgAPIKey;
$from = new SendGrid\Email(null, $from_email);
$to = new SendGrid\Email(null, $to_email);
$content = new SendGrid\Content("text/html", $body);
$mail = new SendGrid\Mail($from, $subject, $to, $content);
//foreach($attachments as $a) {
// $mail->addAttachment($a);
//}
$sg = new \SendGrid($sgAPIKey);
$response = $sg->client->mail()->send()->post($mail);
}
// Send confirmation to customer first before it clears the attachments
if ($email_customer) {
send_email($email_admin, $email_customer, $email_admin_customer, $email_customer_body/*, $attachments*/);
}
// Send to confirmation to admin
if ($email_admin) {
send_email($email_admin, $email_admin, $email_admin_subject, $email_admin_body/*, $attachments = []*/);
}
} else {
}
}
I think you need to save your data somewhere before your redirct to PayPal.
On a redirect, all $_POST fields are lost.
The easist way is to save all data in your session ($_SESSION)
You can grab it from there when you are back from PayPal ;)
I'm a student and still new with Javascript and php, i need to make a login page for my website that can check user input in the database using ajax.
Example: When the user enter their username and password into the field given,the system will automatically check in database either the user exist or not and return the data needed such as user responsibilty from the response table to the dropdown menu below, then they can login into the system.
Below is my basic coding:
Config.php:
e$host = "localhost";
$User = "root"
$Pass = "passw";
$db = "skm_spm";
Login.php:
<?
require ("config.php");
$conn=mysqli_connect($host,$user,$pass,$db);
$duser="select * from tab_user where user_name = '".$_POST["Lname"]."'";
$uresult=myqli_query($conn,$duser);
if(!$uresult)
die("Invalid query: ".mysqli_error());
else
if(mysqli_num_rows($uresult)== 0){
echo "User does not exist";
}
else
{
$row=mysqli_fetch_array($result,MYSQL_BOTH);
if($row["User_Password"] == $_POST["Lpass"])
{
$dresp="select resp_id,resp_name from tab_resp";
$result2 = mysqli_query($conn,$dresp);
}
else
{
}
}
?>
<html>
<b>Login</b><br>
Name : <input type = "text" name="Lname" id="Lname" placeholder="Username"/><br>
Password: <input type = "password" name="Lpass" id="Lpass" placeholder="password"/><br><br>
<div class = "optresp">
<select name="sresp" id="sresp">
<option>--Responsibility--</option>
<?
while (mysqli_fetch_array($result2)){
echo "<option value='$row[1]'>$row[1]</option>";
?>
</select>
</div>
</html>
I have learn on internet and try to code with my understanding,but still failed. I need a php ajax coding that can work with code above.
Thank you.
I will provide you with some code from my recent project and hopefully you will be able to understand it and adapt it to your needs.
Firstly, you should have the login form in a separate file to the PHP login code. Then have button on the page or an enter events that run a Javascript function, in my case Login(). In this Javascript function the text within the input fields are saved to two variables and some basic checks are done on them to ensure that they have been filled in. Next, the PHP login function file (it has no visible content in just processes some data in PHP) using the $.post line. This also passed the two input variables (under the same name) to the PHP file. You can also see that depending on what is returned/echoed from the PHP file as "data" several possible outcomes may occur (Login Success, Account Banned or Invalid Login). I personally call these outcomes error messages or success messages, for example error message 6 for incorrect password/username.
//FUNCTIONS
function Login(){
var StrUsername = $("#txtUsername" ).val();
var StrPassword = $("#txtPassword").val();
if (StrUsername == "" && StrPassword == ""){
$('#pError').text('Enter your Username and Password!');
}
else if(StrUsername == ""){
$('#pError').text('Enter your Username!');
}
else if(StrPassword == ""){
$('#pError').text('Enter your Password!');
}
else{
$.post('https://thomas-smyth.co.uk/functions/php/fnclogin.php', {StrUsername: StrUsername, StrPassword: StrPassword}, function(data) {
if (data == 0){
window.location.href = "https://thomas-smyth.co.uk/home";
}
else if (data == 1){
window.location.href = "https://thomas-smyth.co.uk/banned";
}
else if (data == 6){
$('#pError').text('Username & Password combination does not exist!');
}
});
}
}
Next the PHP function file. Firstly, the variables passed by the Javascript are collected using $_POST. My SQL class is then pulled into the file, this does all my SQL DB connections. I then have my SQL statement that will search to see if the account exists. Notice the ? in it. This prevents SQL injections as the variables is bound into the statement through the SQL server meaning it won't allow people to put SQL code within my input fields to break my database. I then check whether the account exists, if it doesn't I save data to 6, which will cause the error message 6 in the Javascript to run when data is returned. I have a field in my database that contains a rank. If the login is correct then I create a SESSION variable to store their username and rank in. This is later used on pages to check whether they are logged in before displaying a page (this speeds up navigation as it means that the DB doesn't need to be searched everytime the user switches page, however does bring some issues like if you ban a user while they are logged in they will stay logged in until their session dies). You could use this on your dropdown menu to ensure the user is logged in and/or get their username. Finally, I return 0 or 1, so that the Javascript then re-directs them to the correct page.
<?php
//Retrieves variables from Javascript.
$StrUsername = $_POST["StrUsername"];
$StrPassword = $_POST["StrPassword"];
require "sqlclass.php";
$TF = new TF_Core ();
$StrQuery = "
SELECT Username, Rank FROM tblUsers
WHERE Username = ? AND Password = ?";
if ($statement = TF_Core::$MySQLi->DB->prepare($StrQuery)) {
$statement->bind_param('ss',$StrUsername,$StrPassword);
$statement->execute ();
$results = $statement->get_result ();
if($results->num_rows == 0){
$data = 6;
}
else {
while ($row = $results->fetch_assoc()) {
//Other groups
if ($row["Rank"] == "Developer" || $row["Rank"] == "Staff" || $row["Rank"] == "Cadet"){
session_start();
$_SESSION["LoginDetails"] = array($StrUsername, $row["Rank"]);
$data = 0;
}
//Banned
else if ($row["Rank"] == "Banned"){
session_start();
$_SESSION["LoginDetails"] = array($StrUsername, "Banned");
$data = 1;
}
}
}
}
echo $data;
?>
Hopefully this helps you. Please say if you need more help!
You need to make ajax call on blur of username to check if user exists in database and on success of that you can make one more ajax to check for password match of that particular user. This will give you both cases whether a user exixts or not if exixts then does the password match or not only after that user will be logged in and then you can show the responsibilities of that particular user.
For username:
$('#Lname').blur(function(){
$.ajax({
url:'url where query for matching username from database',
data:'username collected from input on blur',
type:'POST',
success:function(data){
//Code to execute do on successful of ajax
}
})
})
For Password:
The ajax call remains the same only url, data and response changes
I am trying to create a form that, once submitted, will be sent to my index.html page for other users to view. I want it so multiple users anywhere in the world can submit information and so the website displays all their information at once.
Here is my submit page's PHP code:
<form action="submit_a_message.php" method="post">
<textarea name="message" cols="60" rows="10" maxlength="500"></textarea><br>
<input type="submit">
</form>
I am trying to figure out how to make the information submited via that form appear on my index.html page. This is the code I found online, but it doesn't work. Why?
<?php>
string file_get_contents ( string $submit_a_message.php [, bool $use_include_path = false [, resource $context [, int $offset = -1 [, int $maxlen ]]]] )
<?>
Any help would be greatly appreciated.
To make submitted text avaliable on your index page, you need a place where you would store it. You can use MySQL base to do that, or (if you can't or you really don't want) you can use text file with your texts/posts (that is not really good way, i warned you).
To do that with MySQL you can use a code like this on your submit_a_message.php:
<?php
//connection to database and stuff
...
if $_POST['message'] {
$message = $_POST['message'];
$sql = "insert into `mytable` values $message"; //that is SQL request that inserts message into database
mysql_query($sql) or die(mysql_error()); // run that SQL or show an error
}
?>
In order to show desired vaues from table use above-like idea, your SQL request would be like select * from mytable where id = 123
if your not married to the idea of using php and learning how to manage and access a database you could use jquery and a trird party backend like parse.com
If your new to storing and retrieving data, I would definately reccomend the services that https://parse.com/ offeres. It makes storing and retrieving data trivial. Best of all, the service is free unless your app makes more than 30 API requests per second. I have an app that 61 users use daily and we have never come close to the 30 req per second limit.
To save your info, you could write:
$('document').ready(function(){
$('#submit_btn').on('click',function(){ // detect button click, need to add "submit_btn" as the id for your button
var Message = Parse.Object.extend("Message"); //create a reference to your class
var newObject = new EventInfo(); //create a new instance of your class
newObject.set("messageText", $("#myMessage").val()); //set some properties on the object, your input will need the id "myMessage"
newObject.save(null, { //save the new object
success: function(returnedObject) {
console.log('New object created with objectId: ' + returnedObject.id);
},
error: function(returnedObject, error) {
console.log('Failed to create new object, with error code: ' + error.message);
}
});
});
});
Retrieving that info later would be as easy as:
var Message = Parse.Object.extend("Message"); //create a reference to your class
var query = new Parse.Query(Message); //create a query to get stored objects with this class
query.find({
success: function(results) { //"results" is an array, you can fine tune your queries to retrieve specific saved objects too
for (var i = 0; i < results.length; i++) {
var object = results[i];
$(body).append("Message #" + (i+1) + object.get("messageText");
}
},
error: function(error) {
console.log("Failed to complete Query - Error: " + error.code + " " + error.message);
}
});