pass $SESSION variable to javascript [closed] - javascript

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed last year.
Improve this question
User inputs his phone number in an HTML form and then fills the google recaptcha, and presses a button. If the phone number section and recaptcha section are successfully completed, then a function named "sendOTP" is called from a javascript file, which uses the phone number to send an OTP to that number. Everything seems to be working, [except that I get this error]. I believe the phone number(which is represented as $_SESSION['Telephone'] is not passed successfully on to the javascript file to be used.
In this case, how can I pass on the variable to the javascript so that it can successfully send an OTP to the number?
Here is the validate-captcha.php code which validates the captcha, and if successful, it sends calls the sendOTP():
<?php
session_start();
$ph_number = '';
if (isset($_POST['g-recaptcha-response']))
{
$secret = "key1";
$ip = $_SERVER['REMOTE_ADDR'];
//echo $ip;
$response = $_POST['g-recaptcha-response'];
$url = "https://www.google.com/recaptcha/api/siteverify?secret=$secret&response=$response&remoteip=$ip";
$fire = file_get_contents($url);
//echo $fire;
$numero = $_SESSION['Telephone'];
$data = json_decode($fire);
if ($data->success == true)
{
echo '<script type="text/javascript">
var $("#mobile").val() = "<?php echo"$numero"?>";
</script>';
echo '<script src="jquery-3.2.1.min.js" type="text/javascript"></script>';
echo '<script src="verification.js">
</script>';
echo '<script>sendOTP()</script>';
return 1;
}
else
{
echo "Please fill captcha";
echo $numero;
}
}
?>
Here's the javascript (verification.js) code:
function sendOTP() {
$(".error").html("").hide();
var number = $("#mobile").val();
if (number.length == 8 && number != null && (number.indexOf(5)==0 || number.indexOf(6)==0 || number.indexOf(9)==0)) {
var input = {
"mobile_number" : number,
"action" : "send_otp"
};
$.ajax({
url : 'controller.php',
type : 'POST',
data : input,
success : function(response) {
$(".container").html(response);
}
});
} else {
$(".error").html('Please enter a valid Hong Kong number!')
$(".error").show();
}
}
async function verifyOTP() {
var that = this;
$(".error").html("").hide();
$(".success").html("").hide();
var otp = $("#mobileOtp").val();
var input = {
"otp" : otp,
"action" : "verify_otp"
};
if (otp.length == 6 && otp != null) {
const handlerA = async function() {
var res = false
try {
await $.ajax({
url : 'controller.php',
type : 'POST',
dataType : "json",
data : input,
success : function(response) {
$("." + response.type).html(response.message);
$("." + response.type).show();
if (response.type=='success') {
res = true
} else if (response.type == 'error') {
res = false
}
},
error : function(response) {
console.log ('fail')
//console.log(data)
alert("Error encountered. Please try again later.");
}
});
return res;
} catch (err) {
console.error( err )
}
}
const handlerB = async function () {
await $.ajax({
url : 'submission.php',
type : 'POST',
data : input,
dataType : "json",
success : function(response) {
$(".container").html(response);
}
})
}
let $resultA = await handlerA()
// Now exec B
if ($resultA == true) {
let $resultB = await handlerB();
$resultB;
}
} else {
$(".error").html('You have entered wrong OTP.')
$(".error").show();
}
}
If necessary, then here is the PHP file(controller.php) where the sendOTP() function is defined:
<?php
session_start();
error_reporting(E_ALL & ~ E_NOTICE);
require ('textlocal.class.php');
include('config/db_connect.php');
class Controller
{
function __construct() {
$this->processMobileVerification();
}
function processMobileVerification()
{
switch ($_POST["action"]) {
case "send_otp":
$mobile_number = $_POST['mobile_number'];
$sender = 'me';
$otp = rand(100000, 999999);
$_SESSION['session_otp'] = $otp;
$message = "Your One Time Password is " . $otp;
$numbers = array(
$mobile_number
);
$url = 'https://www.something.hk/s.php';
$data = array(
"user" => "user",
"pass" => "password",
"to" => $mobile_number,
"from" => $sender,
"unicode" => 0,
"mess" => $message,
"otp" => 1,
"schtime" => 0
);
// use key 'http' even if you send the request to https://...
$options = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => http_build_query($data)
)
);
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
if ($result === FALSE) { /* Handle error */ }
require_once ("verification-form.php");
break;
case "verify_otp":
$otp = $_POST['otp'];
$MPF_account = $_SESSION['MPF_account'];
$Telephone = $_SESSION['Telephone'];
$Gender = $_SESSION['Gender'];
$Job = $_SESSION['Job'];
$Monthly_salary = $_SESSION['Monthly_salary'];
$Existing_loan = $_SESSION['Existing_loan'];
$Residential_Type = $_SESSION['Residential_Type'];
$Existing_loan = $_SESSION['Existing_loan'];
$Job_Type = $_SESSION['Job_Type'];
$Existing_loan_amount = $_SESSION['Existing_loan_amount'];
if ($otp == $_SESSION['session_otp']) {
unset($_SESSION['session_otp']);
echo json_encode(array("type"=>"success", "message"=>"Thank You! Your form has been successfully submitted." ,"MPF_account"=>$MPF_account,
"Telephone"=>$Telephone,"Gender"=>$Gender,"Job"=>$Job,"Monthly_salary"=>$Monthly_salary,"Existing_loan"=>$Existing_loan,
"Residential_Type"=>$Residential_Type,"Existing_loan"=>$Existing_loan,"Job_Type"=>$Job_Type,"Existing_loan_amount"=>$Existing_loan_amount
));
}
else {
echo json_encode(array("type"=>"error", "message"=>"Mobile number verification failed"));
}
break;
}
}
}
$controller = new Controller();
?>
Also, here is the HTML form that was used at the first stage:
<!DOCTYPE html>
<html>
<head>
<title>OTP SMS</title>
<link href="style.css" type="text/css" rel="stylesheet" />
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
<script src="jquery-3.2.1.min.js" type="text/javascript"></script>
<script src="verification.js"></script>
<?=(isset($_POST['g-recaptcha-response']) && $data->success) ? "<script>sendOTP()</script>" : ""?>
</head>
<body>
<div class="container">
<div class="error"></div>
<form action="validate-captcha.php" id="frm-mobile-verification" method="POST">
<div class="form-heading">Mobile Number Verification</div>
<div class="form-row">
<input type="number" id="mobile" class="form-input" placeholder="Enter the 8 digit mobile" value="<?php echo $_SESSION['Telephone'] ?>">
</div>
<div method="post" class="g-recaptcha" data-sitekey="key2"></div>
<input type="submit" name="submit" value="Submit" class="btn brand z-depth-0">
</form>
</div>
<script src="jquery-3.2.1.min.js" type="text/javascript"></script>
<script src="verification.js"></script>
</body>
</html>

Fixing JavaScript output by PHP
You have this in your code:
var $("#mobile").val() = "<?php echo"$numero"?>";
This is not valid JavaScript you are outputting.
var must be used with a variable name. That is what the syntax error is supposed to tell you.
What you intended is to set the value. Look at the jQuery documentation on how to do that:
https://api.jquery.com/val/#val2
That leaves us with this solution...
$("#mobile").val("' . $numero . '");
...which puts the value for $numero from the PHP variable into the input field with id mobile.
Fixing the order of JavaScript
Your PHP code now outputs this:
echo '<script type="text/javascript">
var $("#mobile").val() = "' . $numero . '";
</script>';
echo '<script src="jquery-3.2.1.min.js" type="text/javascript"></script>';
Notice you add jQuery after you do $("#mobile").val(), which requires jQuery. So you have to add jQuery first (includes the fix from before):
echo '<script src="jquery-3.2.1.min.js" type="text/javascript"></script>';
echo '<script type="text/javascript">
$(document).ready(function(){
$("#mobile").val("' . $numero . '");
});
</script>';
Notice I also added a document.ready handler to load the HTML document first before calling the JavaScript.
Please respect the comments
Please read the comments again. They were trying to help you discover the JavaScript error there. You were insisting your code is okay - or at least your wording indicated you don't see the problem at all - you "just need the solution".
They were hinting you should rethink and you were showing no signs of understanding the syntax error is fault of your code.
You are supposed to go "Oh maybe the syntax is wrong, I will check the documentation again how to do that".

Related

updating data with JavaScript functions not working properly

I want to send an Ajax request when clicking a button but it seems my request is never executed.
Here is my HTML code :
<!DOCTYPE html>
<html lang="en">
<head>
<title>User Form</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
<script src = "./actions.js"></script>
</head>
<body>
<div id="badFrm" class="container">
<h2><br>User Registration</h2>
<form id="Form" method="post">
<div class="form-group">
<label for="name">Name:</label>
<input type="name" class="form-control" id="name" placeholder="Enter Name" name="name">
</div>
<div class="form-group">
<label for="email">Email:</label>
<input type="email" class="form-control" id="email" placeholder="Enter Email" name="email">
</div>
<button id="submitBtn" class="btn btn-primary">Submit</button>
</form>
</div>
</body>
</html>
i feel there is something wrong with my javascript code but i cant figure whats wrong ! i changed a lot of it based on the comments i got earlier . what i want is when i click on the update button it changes to " submit again " and i want to replace "list items" ( name and email ) with input fields and put whatever written in them to be saved in the database instead . and eventually return to the first page which is the register form. i need help in this part !! i know this part is buggy . i need to know how to reach each list item individually ( what attribute should i add/use )
and here is my javascript code :
$(document).ready(function() {
var i ;
$("#submitBtn").click(function (e) {
e.preventDefault();
var name = $("#name").val();
var email = $("#email").val();
$.post("http://localhost/MiniProject/connect.php",
{
name: name,
email: email
}, function () {
var element = document.getElementById("badFrm");
element.remove();
showTbl();
});
function showTbl() {
$.post("http://localhost/MiniProject/Select.php",
{
name: name,
email: email
}, function (res) {
// console.log(res);
res = JSON.parse(res);
var html = '<ul id="List">';
for (i = 0; i < res.length; i++) {
var j = i +1 ;
html += '<li class = "name" >' + res[i].name + '</li><li class = "email">' + res[i].email + '</li>'+ '<div>' + '<button onclick="removeUser(this)" class="btn btn-primary">Remove</button>' + '<button onclick="updateUser(this)" class="btn btn-primary">Update</button>' + '</div>';
}
html += '</ul>';
document.body.innerHTML = html;
});
}
});
});
function removeUser(element){
var ID = element.id;
var element2 = document.getElementById("List");
element2.remove();
$.post("http://localhost/MiniProject/Remove.php",{
id : ID
}, function (res) {
console.log(res);
document.write(res);
});
//alert(element.id);
}
function updateUser(element){
// code ...
$.post("http://localhost/MiniProject/Update.php",{
id : ID2,
}, function (res) {
console.log(res);
// document.write(res);
});
}
here is connect.php :
<?php
require 'Users.php';
$name = $_POST['name'];
$email = $_POST['email'];
$conn = new mysqli('localhost','root','','mydatabasename');
if($conn->connect_error){
die('Connection Failed : '.$conn->connect_error);
}else {
$user = new Users();
$user->Insert(['name' => $name, 'email' => $email]);
echo "name is : ".$name." and email is : ".$email;
}
this is Users.php :
<?php
require 'newDB.php';
class Users extends DatabaseClass{
public $table = 'Users';
}
and this is where i handle the database commands :
<?php
class DatabaseClass{
public $connection = null;
public $table = null;
// this function is called everytime this class is instantiated
public function __construct( $dbhost = "localhost", $dbname = "myDatabaseName", $username = "root", $password = ""){
try{
// $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$this->connection = new PDO("mysql:host=$dbhost;dbname=$dbname", $username, $password);
$this->connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->connection->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
$sql = "CREATE TABLE MyGuests (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
)";
}catch(Exception $e){
throw new Exception($e->getMessage());
}
}
// Insert a row/s in a Database Table
public function Insert($parameters = [] ){
try{
$fields = array_keys($parameters);
$fields_string = '`' . implode('`,`', $fields) . '`';
$values_string = ':' . implode(',:', $fields);
$sql = "INSERT INTO `{$this->table}`({$fields_string}) VALUES ( {$values_string} )";
$this->executeStatement( $sql , $parameters );
return $this->connection->lastInsertId();
}catch(Exception $e){
throw new Exception($e->getMessage());
}
}
// Select a row/s in a Database Table
public function Select( $parameters = [] ){
try{
$fields = array_values($parameters);
$fields_string=implode(' , ',$fields);
$sql = "SELECT {$fields_string} FROM {$this->table}";
$stmt = $this->executeStatement( $sql , $parameters );
return $stmt->fetchAll();
}catch(Exception $e){
throw new Exception($e->getMessage());
}
}
// Update a row/s in a Database Table
public function Update( $parameters = [] ){
try{
$fields = array_keys($parameters);
$fields_string = 'id = '.implode($fields);
$sql = "UPDATE {$this->table} SET {$fields_string} WHERE {$fields_string} ";
echo $sql; exit ;
$this->executeStatement( $sql , $parameters );
}catch(Exception $e){
throw new Exception($e->getMessage());
}
}
// Remove a row/s in a Database Table
public function Remove( $parameters ){
try{
$fields_string = 'id = '.implode($parameters);
$sql = "DELETE FROM {$this->table} WHERE {$fields_string}";
$this->executeStatement( $sql , $parameters );
}catch(Exception $e){
throw new Exception($e->getMessage());
}
}
// execute statement
public function executeStatement( $statement = "" , $parameters = [] ){
try{
$stmt = $this->connection->prepare($statement);
$stmt->execute($parameters);
return $stmt;
}catch(Exception $e){
throw new Exception($e->getMessage());
}
}
}
and this is Update.php :
<?php
require 'Users.php';
$id = $_POST['id'];
$conn = new mysqli('localhost','root','','mydatabasename');
if($conn->connect_error){
die('Connection Failed : '.$conn->connect_error);
}else {
$user = new Users();
$result = $user->Update(['id'=>$id]);
// echo json_encode($result);
}
?>
i dont want the question to have a lot of code so hope this makes it better to understand.
I mentioned posting something without jQuery - here is a demo which does what I understand your requirement to be. There are comments below to explain what is going on.
<?php
error_reporting( E_ALL );
if( $_SERVER['REQUEST_METHOD']=='POST' && isset( $_POST['action'] ) ){
ob_clean();
/*
This emulates ALL of the PHP endpoints used in the original code
-this is for demo purposes ONLY. The data returned is DEMO data
and should be ignored. All AJAX functions should be pointed at
their original endpoints... unless you adopt a similar approach
in which case include your various PHP classes here.
The ficticious sql in the below is for example only!
Obviously you would use `prepared statements`...
*/
switch( $_POST['action'] ){
case 'insert':
// do stuff...
// send response...
$data=sprintf('name is: %s and email is: %s',$_POST['name'],$_POST['email']);
break;
case 'remove':
header('Content-Type: application/json');
$data=json_encode(array(
'action' => $_POST['action'],
'name' => $_POST['name'],
'email' => $_POST['email'],
'sql' => sprintf('delete from `TABLE` where `email`="%s"', $_POST['email'] )
));
break;
case 'update':
header('Content-Type: application/json');
$data=json_encode(array(
'action' => $_POST['action'],
'name' => $_POST['name'],
'email' => $_POST['email'],
'sql' => sprintf('update `TABLE` set `col`=? where `email`="%s"', $_POST['email'] )
));
break;
}
exit( $data );
}
?>
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8' />
<title></title>
<style>
.hidden{display:none}
</style>
<script>
document.addEventListener('DOMContentLoaded',()=>{
/*
I can see no benefit to having multiple endpoints to process
the different AJAX requests. You can structure a single script
to process each request rather like the above PHP code but
that is just an opinion. The following points ALL requests to
the same page for this demo.
The user's `email` address should be unique(?) so could be used
as the key in whatever sql query???
*/
const endpoints={
'insert':location.href, // 'MiniProject/connect.php'
'select':location.href, // 'MiniProject/Select.php'
'remove':location.href, // 'MiniProject/Remove.php'
'update':location.href // 'MiniProject/Update.php'
};
// Elements in the initial page/form
let cont=document.querySelector('div.container');
let form=document.forms.register;
let bttn=form.querySelector('button');
// the main callback - for the `Submit` button
const bttnclickhandler=function(e){
e.preventDefault();
let valid=true;
// check the form fields are not empty before continuing
let col=form.elements;
Array.from( col ).some( n => {
if( n.tagName=='INPUT' && n.value=='' ){
alert( '"' + n.name + '" cannot be empty' );
valid=false;
return true;
}
})
if( !valid )return false;
// Prepare the Payload to be sent, via AJAX POST, to the backend script/endpoint.
let fd=new FormData( form );
fd.append('action',this.dataset.action);
// Send the AJAX request
fetch( endpoints.insert, { method:'post', body:fd } )
.then( r=>r.text() )
.then( text=>{
// Hide the original form - do not remove it though... you want to reinstate this later
form.classList.add('hidden');
/*
create a clone of the template and then find the elements within
assign new values and bind event listeners.
*/
let oTmpl=document.querySelector('template#list-item').content.firstElementChild.cloneNode( true );
oTmpl.querySelector('[data-id="name"]').textContent=fd.get('name');
oTmpl.querySelector('[data-id="email"]').textContent=fd.get('email');
oTmpl.querySelectorAll('button[data-action]').forEach( n=>{
n.addEventListener('click',function(e){
let action=this.dataset.action;
let url=endpoints[ action ];
let fd=new FormData();
fd.append('action',action);
fd.append('name',e.target.parentNode.parentNode.querySelector('span[data-id="name"]').textContent);
fd.append('email',e.target.parentNode.parentNode.querySelector('span[data-id="email"]').textContent);
// send a new AJAX request
fetch( url, { method:'post', body:fd })
.then( r=>r.json() )
.then( json=>{
// the response...
console.log( json );
// show the original form and remove the clone
form.classList.remove('hidden');
cont.querySelector('ul#list').removeChild( oTmpl );
})
});
});
// Add the cloned template to the container
cont.querySelector('ul#list').appendChild( oTmpl )
})
};
// bind the event handler to the button.
bttn.addEventListener( 'click', bttnclickhandler );
});
</script>
</head>
<body>
<!--
All buttons below have dataset attributes
data-action='value' - this is used to decide
which piece of PHP code to process.
-->
<div class='container'>
<h2>User Registration</h2>
<form name='register' method='post'>
<div class='form-group'>
<label>
Name:
<input type='text' name='name' class='form-control' placeholder='Enter Name' />
</label>
</div>
<div class='form-group'>
<label>
Email:
<input type='email' name='email' class='form-control' placeholder='Enter Email' />
</label>
</div>
<button data-action='insert' class='btn btn-primary'>Submit</button>
</form>
<ul id='list'></ul>
</div>
<!--
The template will be called and populated
by ajax callback when the above `Submit`
button is clicked.
This will NOT appear in the DOM until
requested with Javascript.
The inner contents of this template
are cloned and inserted into the DOM.
-->
<template id='list-item'>
<li>
<span data-id='name'></span>
<span data-id='email'></span>
<div>
<button data-action='remove' class="btn btn-primary">Remove</button>
<button data-action='update' class="btn btn-primary">Update</button>
</div>
</li>
</template>
</body>
</html>
You say that you want to make an AJAX request (submit), but I don't see where are you doing it.
Also, it seems that you're submitting twice your form.
You should have something like this:
$.ajax({
data: $(this).serialize(),
type: "POST",
url: "http://localhost/MiniProject/connect.php",
success: function(data) {
//if it's successful, put all your code here to change names etc.
}
$(this).serialize() will work only if you change your button to a submit input:
<input type="submit" id="submitBtn" class="btn btn-primary">Submit</input>
you can also use a "button" but then you'll have to specify what data you're submitting, it's easier to use a submit input, if you ask me.
Also, if you already have an ID for name and email, it's a lot easier to change them using it's respective ID's, instead of trying to re-write the whole div element.
Anyway, I hope it helps

Pass variable from controller to javascript using PHP(Codeigniter)

I have registration module and I already done so far the validation of all fields(fields are: name, email, username and password),check if the email and username is already existing.
And trying to add a suggestion if the username is already existing. I am done in adding a prefix in the username but having a problem to pass the variable to javascript and display it in my view
This is my Controller
$get_username = clean_data($_POST['username']);
$where = array(
"username" => $get_username
);
$check_username = $this->Crud_model->count_result('username','users',$where);
if($check_username > 0)
{
$fetch_username = $this->Crud_model->user_exists('users',$where);
$last_username = strrev((int)strrev($fetch_username)); // returns last numeric value of username
if($last_username){
$count = count($last_username);//counts number of digit
$str = substr($username, 0, -($count));;// subtract numeric value from last of username
}
$newstr = $last_username+1;
$username= $get_username.$newstr;
echo json_encode("existing");
// echo "var username = ". json_encode($username).";";
}
else
{
$insert_user = array(
'first_name' => clean_data(ucwords($_POST['first_name'])),
'last_name' => clean_data(ucwords($_POST['last_name'])),
'profile_picture' => "profile-picture.jpg",
'username' => $get_username,
'email' => $_POST['email'],
'password' => hash_password($_POST['password']),
'status' => 1,
);
$this->Crud_model->insert('users',$insert_user);
echo json_encode("success");
}
this is My javascript with ajax
$(document).ready(function(){
$("#registration-form").on('submit',function(e){
$.ajax({
url: base_url+"formsubmit/new_form_submit",
type: "POST",
data: $(this).serialize(),
success:function(data)
{
var result = JSON.parse(data);
if(result === "success")
{
$("h5").html("");
success_message("#success-message-new-account","Create Successful!");
window.setTimeout(function(){location.href=base_url},2000);
}
else if(result === "existing")
{
$("h5").html("");
success_message("#existing-message-account","You may use!".$username);
// window.setTimeout(function(){location.href=base_url},2000);
}
else{
$("#first_name_error").html(result.first_name_error);
$("#last_name_error").html(result.last_name_error);
$("#username_error").html(result.username_error);
$("#email_error").html(result.email_error);
$("#password_error").html(result.password_error);
}
},
error: function(data) {
alert('error');
}
})
e.preventDefault();
})
})
This is my My View
<div id="existing-message-account"></div>
<div class="wrap-input100 validate-input">
<input class="input100" type="text" name="first_name" id="first_name">
<span class="label-input100">First</span>
</div>
<div class="wrap-input100 validate-input">
<input class="input100" type="text" name="last_name" id="last_name">
<span class="label-input100">Last</span>
</div>
After the user fill up the registration form. It will be process in my javascript, now it will be check if the username registered is already existing or not. if it is not then it will be save in my table. If it is existing then it will add a number prefix.
Example
In my table users. I have existing username abcd, if the user register abcd then there would be a message "Username is already taken, you may use abcd1"
Question: How do I pass the variable $username into my javascript?
NOTE: I tried this approach, changing echo json_encode("existing"); into this echo json_encode($username). My javascript else if(result === $username)... The message will not work anymore.
Hope this will help you :
For the existing status record do like this :
$data['username'] = $username;
$data['status'] = 'existing';
echo json_encode($data);
exit;
For the success status record return like this
$data['username'] = $username;
$data['status'] = 'success';
echo json_encode($data);
exit;
Your ajax success part should have code like this :
var result = JSON.parse(data);
if(result.status === "success")
{
$("h5").html("");
success_message("#success-message-new-account","Create Successful!");
window.setTimeout(function(){location.href=base_url},2000);
}
else if(result.status === "existing")
{
$("h5").html("");
success_message("#existing-message-account","You may use!" + result.username);
// window.setTimeout(function(){location.href=base_url},2000);
}

JQuery form submission generates a new form

I have a JQuery script that submits user input to a PHP script in the same file, and then displays the result of what the PHP script does with the input. That part works fine. The issue that I’m having is that, upon submission, the JQuery script (at least, I think it's the script) also generates a new submission box below the original.
I’m not sure why. I thought at first that it was an issue with the input type, with the asynchronous part, or even with where I had the form in the overall code, but none of those seem to be playing any role. I'm still a beginner and I'm just not seeing the issue.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<form id = "my_form">
verb <input type = "text" id ="word1"/>
<input type = "submit"/></form>
<div id="name"></div>
<script>
$(document).ready(function(){
$("#my_form").on('submit', function(e)
{
e.preventDefault();
var verb = $ ("#word1").val();
var tag = "#Latin ";
var url = "http://en.wiktionary.org/wiki/"+verb+tag;
$.ajax({
url: "Parser.php",
data: {"verb": verb},
type: "POST",
async: true,
success: function(result){
$("#name").html(result);
$("#name").append(url);
}
});
});
});</script>
RESULT:
PHP
<?php
$bank = array();
function endsWith($haystack, $needle) {
return $needle === "" || (($temp = strlen($haystack) - strlen($needle)) >= 0 && strpos($haystack, $needle, $temp) !== false);
}
function check_end_array($str, $ends)
{
foreach ($ends as $try) {
if (substr($str, -1*strlen($try))===$try) return $try;
}
return false;
}
function db_connect() {
static $connection;
if(!isset($connection)) {
$connection = mysqli_connect('127.0.0.1','username','password','Verb_Bank');
}
if($connection === false) {
return mysqli_connect_error();
}
return $connection;
}
function db_query($query) {
$connection = db_connect();
$result = mysqli_query($connection,$query);
return $result;
}
function db_quote($value) {
$connection = db_connect();
return "'" . mysqli_real_escape_string($connection,$value) . "'";
}
$y = false;
if (isset($_POST['verb'])){
$y=db_quote($_POST['verb']);
echo $y;
echo "\n";
$m = db_query("SELECT `conjugation` FROM normal_verbs WHERE (" . $y . ") LIKE CONCAT('%',root,'%')");
if($m !== false) {
$rows = array();
while ($row = mysqli_fetch_assoc($m)) {
$rows[] = $row;
}
}
foreach ($rows as $key => $value){
if (in_array("first",$value)==true){
echo "first conjugation verb\n";}
$y = $_POST["verb"];
$x = $y;
foreach ($bank as $key => $value)
(series of IF-statements)
}}?>
As Roamer-1888 says's the problem lies in server side, you are returning a html which has a input too. You need to change your code to return only the result string which you append to the div. Else if this is not possible doing at server side as it might require you to change lot of code, then you can strip off the input element from the result and then append it to the div. Like below.
success: function(result){
var div = document.createElement('div');
div.innerHTML = result;
$(div).find('input').remove();
$("#name").html(div.innerHTML);
$("#name").append(url);
}

Return response from PHP to Jquery using Ajax

I am submitting info to be saved in a MySQL database using Jquery/AJAX and PHP.
This is what i've done so far:
function Addinfo() {
var ew = document.getElementById("ew").value;
var mw = document.getElementById("mw").value;
var dataString = 'ew1=' + ew + '&mw=' + mw;
if (ew == '' || mw == '') {
alert("Please Fill All Fields");
} else {
$.ajax({
type : "POST",
url : "ajaxadd.php",
data : dataString,
dataType : 'text',
cache : false,
})
.done(function (data) {
$('#message1').html(data);
})
}
return false;
}
and my PHP code:
<?php
$ew2 = $_POST['ew1'];
$mw2 = $_POST['mw1'];
$connection = mysql_connect("localhost", "root", "");
$db = mysql_select_db("tp", $connection);
if (isset($_POST['ew1'])) {
$query = mysql_query("insert into table(ew, mw) values ('$ew2', '$mw2')");
$addresult = mysql_query("SELECT * FROM `table` WHERE `ew` = '" . $_POST['ew1'] . "' ORDER BY `id` DESC LIMIT 1");
$aircraft = mysql_fetch_assoc($addresult);
echo $aircraft;
}
mysql_close($connection); // Connection Closed
?>
It saves the information to the database successfully but I can't even get a success message let alone a variable from the PHP. I have read countless posts about asynchronous calls, callback functions and promises but I somehow can't get this to work. Any help would be appreciated.
Jquery: (main.js file)
$(document).ready(function(){
$('.ajaxform').on('submit', function(e){
e.preventDefault();
$.ajax({
// give your form the method POST
type: $(this).attr('method'),
// give your action attribute the value ajaxadd.php
url: $(this).attr('action'),
data: $(this).serialize(),
dataType: 'json',
cache: false,
})
.success(function(response) {
// remove all errors
$('input').removeClass('error').next('.errormessage').html('');
// if there are no errors and there is a result
if(!response.errors && response.result) {
// success
// loop through result and append values in message1 div
$.each(response.result, function( index, value) {
$('#message1').append(index + ': ' + value + '<br/>');
});
} else {
// append the error to the form
$.each(response.errors, function( index, value) {
// add error classes
$('input[name*='+index+']').addClass('error').after('<div class="errormessage">'+value+'</div>')
});
}
});
});
});
PHP (ajaxadd.php file)
<?php
// assign your post value
$inputvalues = $_POST;
// assign result vars
$errors = false;
$returnResult = false;
$mysqli = new mysqli('host', "db_name", "password", "database");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
// escape your values
foreach ($inputvalues as $key => $value) {
if(isset($value) && !empty($value)) {
$inputvalues[$key] = htmlspecialchars( $mysqli->real_escape_string( $value ) );
} else {
$errors[$key] = 'The field '.$key.' is empty';
}
}
if( !$errors ) {
// insert your query
$mysqli->query("
INSERT INTO `table`(`ew`, `mw`)
values ('".$inputvalues['ew1']."', '".$inputvalues['mw']."')
");
// select your query
// this is for only one row result
$addresult = "
SELECT *
FROM `table`
WHERE `ew` = '".$inputvalues['ew1']."'
ORDER BY `id` DESC
LIMIT 1
";
if( $result = $mysqli->query($addresult) ) {
// collect results
while($row = $result->fetch_assoc())
{
// assign to new array
// make returnResult an array for multiple results
$returnResult = $row;
}
}
}
// close connection
mysqli_close($mysqli);
// print result for ajax request
echo json_encode(['result' => $returnResult, 'errors' => $errors]);
exit;
?>
HTML:
<!doctype html>
<html class="no-js" lang="">
<head>
<meta charset="utf-8">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<title>Ajax form submit</title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<form class="ajaxform" action="ajaxadd.php" method="POST">
<input type="text" name="ew1" />
<input type="text" name="mw" />
<button type="submit">Submit via ajax</button>
</form>
<div id="message1"></div>
<script src="https://code.jquery.com/jquery-1.12.0.min.js"></script>
<script>window.jQuery || document.write('<script src="js/vendor/jquery-1.12.0.min.js"><\/script>')</script>
<script src="main.js"></script>
</body>
</html>
$.ajax({
type: "POST",
url: "ajaxadd.php",
ew1:ew,
mw1:mw,
data: dataString,
dataType: 'text',
cache: false,
})
In PHP code at the end where you
echo $aircraft change it to echo json_encode($aircraft); and in AJAX fucntion where you mentioned
cache:false include success:function(response){alert response;}
It will give your aircraft variable value in AJAX function.
Good Luck!
You should modify your php code as below instead of directly return mysql_fetch_assoc because it returns only the first row of your SQL result.
<?php
$ew2 = $_POST['ew1'];
$mw2 = $_POST['mw1'];
$connection = mysql_connect("localhost", "root", "");
$db = mysql_select_db("tp", $connection);
if (isset($_POST['ew1']))
{
$result = array();
$query = mysql_query("insert into table(ew, mw) values ('$ew2', '$mw2')");
$addresult = mysql_query("SELECT * FROM `table` WHERE `ew` = '" . $_POST['ew1'] . "' ORDER BY `id` DESC LIMIT 1");
while($aircraft = mysql_fetch_assoc($addresult))
{
$result[] = $aircraft;
}
#echo $aircraft; // wait until whole result is collected
echo json_encode($result);
}
mysql_close($connection); // Connection Closed
?>
Also you should edit your javascript code as below;
function Addinfo() {
var ew = document.getElementById("ew").value;
var mw = document.getElementById("mw").value;
var dataString = 'ew1=' + ew + '&mw=' + mw;
if (ew == '' || mw == '') {
alert("Please Fill All Fields");
} else {
$.ajax({
type : "POST",
url : "ajaxadd.php",
data : dataString,
dataType : 'text',
cache : false,
success: function(data)
{
//$('#message1').html(data);
alert(data);
},
error: function(data)
{
alert("Error");
}
});
}
return false;
}
In addition advice you may check $connection and $db for successful initialization of your database connection and database selection, and again an advice for your php code your should use mysqli extension instead of mysql extension which deprecated. You can just replace mysql part of your calling methods with mysqli. Also #RakhalImming's advice is quite good for security of your code.

PHP Ajax not creating post variable

A while ago i made a search function with ajax and php. You could fill in a textbox with text and it would try to find a match among all countries stored in the database.
Now i am refining the code and making it PDO, but i broke something and i cant find out what.
this is my plain HTML
<head>
<title>Ajax</title>
<link href="style/style.css" rel="stylesheet" type="text/css" />
<link rel="stylesheet" type="text/css" />
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript" src="scripts/Javascript.js"></script>
</head>
<body>
<div id="main">
<h1 class="title">Enter your country please</h1>
<input type="text" id="search" autocomplete="off" onchange="">
<h4 id="results-text">Showing results for: <b id="search-string">Array</b></h4>
<ul id="results"></ul>
</div>
</body>
here is my Jquery and javascript. note i have not changed anything to the HTML nor javascript so it can not by a type error.
$(document).ready(function() {
alert('asdf');
function search() {
var query_value = $('input#search').val();
$('b#search-string').html(query_value);
if(query_value !== ''){
$.ajax({
type: "POST",
url: "search.php",
data: { query: query_value },
cache: false,
success: function(html){
$("ul#results").html(html);
}
});
}
return false;
}
$("input#search").live("keyup", function(e) {
clearTimeout($.data(this, 'timer'));
var search_string = $(this).val();
if (search_string == '') {
$("ul#results").fadeOut();
$('h4#results-text').fadeOut();
}
else {
$("ul#results").fadeIn();
$('h4#results-text').fadeIn();
$(this).data('timer', setTimeout(search, 100));
};
});
});
And here is my Search.PHP
<?php
class SearchEngine{
private $html;
public function __construct($conn){
$this->html = '<li class="result">
<h3>NameReplace</h3>
<a target="_blank" href="ULRReplace"></a>
</li>';
if (isset($_POST["query"])) {
$search_string = $_POST['query'];
}
else{
$search_string = '';
echo('Something went wrong, post query not set');
}
//$search_string = mysql_real_escape_string($search_string);
if (strlen($search_string) >= 1 && $search_string !== ' ') {
$query = 'SELECT * FROM country WHERE name LIKE "%' . $search_string . '%"';
$result = $conn->prepare($query);
$result->execute();
$result_array = $result->fetchAll();
foreach ($result_array as $result) {
$display_name = preg_replace("/" . $search_string . "/i", "<b>" . $search_string . "</b>", $result['name']);
$display_url = 'sadf';
$output = str_replace('NameReplace', $display_name, $this->html);
$output = str_replace('ULRReplace', $display_url, $output);
echo($output);
}
}
}
}
?>
The problem:
the Post query is never created, for this i made a isset so for now when there is no Post Query created. It will create a Post Query with value "B".
Any help will be much appreciated. Please be gentle i am new to Ajax and i rather want to understand than have the solution. Thank you
You're not point the right URL! Look:
You have pointed your ajax request to search.php :
$.ajax({
type: "POST",
url: "search.php",
But you have just a class in search.php. A class don't do anything by itself. You have to Instantiate and call its methods/functions. Please compare these 2 pieces of code:
<?php
//server.php
//Doing nothing
class SearchEngine{
private $html;
public function __construct($conn){
echo "I'm executing";
}
}
?>
let's say you have this in server.php
<?php
//server.php
//It will print "I'm executing" in the screen
class SearchEngine{
private $html;
public function __construct($conn){
echo "I'm executing";
}
}
$search = new SearchEngine($conn);
?>
To solve your original problem You have to to point your ajax to the page having the INSTANTIATION code, not the class, like this:
//index.php
//Let's suppose you have this code in your index.php
$SearchEngine = new SearchEngine($conn);
So your JQuery ajax code should looks like that:
$.ajax({
type: "POST",
url: "index.php",
As Mentioned by Sean, in the comments, the $.live jquery method is deprecated in your version of jQuery.
Try utilizing $.keyup instead
$("input#search").keyup(function() {
// stuff
});

Categories

Resources