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).
Related
As the title says, i cant seem to understand why im getting this error for an on change event on a model driven app form. i have to be honest, im using code snippits and chatGPT to try and formulate this because i haven't got a clue!! but i think im close 😁
for context, when i search for the client in a new enquiry for the code is to get the account manager from the clients record in another table and put it in the enquiry form.
var SDKEnquiry = window.Sdk || {}; (function(){ // This function is called when the customer lookup field on the form is changed this.function = onChangeCustomer(executionContext){ // Get the form context var formContext = executionContext.getFormContext();
// Get the value of the customer lookup field on the enquiry form
var customerLookup = formContext.getAttribute("customerlookup_on_enquiry_form").getValue();
// Check if a customer is selected
if(customerLookup){
// Retrieve the customer account record using the WebApi
Xrm.WebApi.retrieveRecord("account",
customerLookup[0].id, "?$select=accountmanagerid_on_customer_record").then(
function success(result) {
// Get the account manager id from the response
var accountManagerId = result.accountmanagerid_on_customer_record;
// Set the account manager id on the enquiry form
formContext.getAttribute("accountmanagerid_on_enquiry_form").setValue(accountManagerId);
},
function (error) {
// Show an error message
alert(error.message);
}
);
}
} }).call(SDKEnquiry);
This is the error im getting from Power Apps when i run the app and try and use the form. posted as image because im getting a spam warning
Error
Edit:
OKay so i think ive fixed the code, im not getting any errors anymore anyway but when i select the client the field does not pupulate?
var SDKEnquiry = {};
(function(){
this.onChangeCustomer = function(executionContext) {
var formContext = executionContext.getFormContext();
var customerLookup = formContext.getAttribute("w3c_clientcompany").getValue();
if (!customerLookup) {
alert("No customer selected.");
return;
}
Xrm.WebApi.retrieveRecord("account",
customerLookup[0].id, "?$select=w3c_AccountManager")
.then(function success(result) {
var accountManagerId = result.w3c_AccountManager;
formContext.getAttribute("w3c_cam").setValue(accountManagerId);
})
.catch(function (error) {
alert(error.message);
});
};
}).call(SDKEnquiry);
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);
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 have a bit of an issue updating a calculated field of the parent form when submitting/updating a child record with a bootstrap 3 modal dialogue, from within the parent form.
I have this function in parent.js file:
function update_lineitems_subtotal() {
var qid = $j('[name=SelectedID]').val();
if (!isNaN(qid)) {
$j.ajax({
url: 'hooks/ajax_quote_subtotal.php',
data: {qid: qid},
success: function(data) {
$j('#LineItemsSubtotal').val(data);
$j('#Shipping').keyup();
}
});
} else {
$j('#LineItemsSubtotal').val('0');
$j('#Shipping').keyup();
}
};
And this is the ajax_quote_subtotal.php that runs with the ajax call above:
<?php
$currDir = dirname(__FILE__) . '/..';
include("$currDir/defaultLang.php");
include("$currDir/language.php");
include("$currDir/lib.php");
/* grant access to users with access to quotations table */
$od_from = get_sql_from('quotations');
if(!$od_from){
header('HTTP/1.0 401 Unauthorized');
echo "You do not have permission to access this page. If this behaviour is unexpected, please contact the system administrator";
exit;
}
$qid = intval($_REQUEST['qid']);
if(!qid) exit;
$parts_subtotal = sqlValue("select sum(Subtotal) from product_line_items where QuotationID='{$qid}' ");
$service_subtotal = sqlValue("select sum(Subtotal) from service_line_items where QuotationID='{$qid}' ");
$subtotal = $parts_subtotal + $service_subtotal;
sql("update quotations set LineItemsSubtotal='{$subtotal}' where QuotationID='{$qid}' ", $eo);
echo number_format($subtotal, 2);
?>
This is the function from child.js that closes the modal dialogue when the form is submitted and runs the update_lineitems_subtotal function from the parent.js
if($j('input[name=Embedded]').val()==1){
$j('form').submit(function(){
window.parent.jQuery('.modal').modal('hide');
setTimeout(function(){
parent.update_lineitems_subtotal();
}, 100);
})
}
This works as long as I do not remove setTimeout,however I do not feel like it is a good solution.
If the setTiemout is removed the record is created but it looks like the function runs before the child record is submitted, so the value of the subtotal field in the parent excludes the latest added record.
I have also tried this:
if($j('input[name=Embedded]').val()==1){
$j('form').submit(function(e){
e.preventDefault();
this.submit();
window.parent.jQuery('.modal').modal('hide');
parent.update_lineitems_subtotal();
})
}
This had similar results in Chrome and refused to even create a child record in Firefox.
Any help would be appreciated.
P.S. I am new to this, if you have time to explain the code you may suggest it would be greatly appreciated.
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);
}
});