updating data with JavaScript functions not working properly - javascript

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

Related

pass $SESSION variable to javascript [closed]

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".

jQuery code is stopping the products from being inserted into the database

When I include the $.post jQuery code, the product info does not get inserted into the database. However, when I remove the $.post jQuery code, the products are successfully inserted into the database.Please help.
index.html
<html>
<body>
<h1>Enter Product Details</h1>
<form id = "product_form" method = "post" action = "insert.php">
<input type = "text" id = "n" name = "productname" placeholder = "Product name"></br>
<input type = "text" id = "b" name = "brandname" placeholder = "Brand name"></br>
<input type = "number" id = "q" name = "quantity" placeholder = "Quantity"></br>
<button id = "save_button">Save information</button>
</form>
<p id = "result"></p>
<button id = "btn">Test Button</button>
<script type = "text/javascript" src = "js/jquery.js"></script>
<script type = "text/javascript" src = "js/script.js"></script>
</body>
</html>
insert.php
<?php
$name = $_POST['productname']; //'productname' is from html input
$brand = $_POST['brandname']; //'brandname' is from html input
$quantity = $_POST['quantity']; //'quantity' is from html input
$con = new mysqli ('localhost', 'root', '', 'tutorial');
if ($con -> connect_error) {
echo 'database connect error';
}
//Prepare statement to insert into database
$stmt = $con -> prepare ("INSERT into products(name, brand, quantity) VALUES (?, ?, ?)");
// Bind the variables to the values
$stmt -> bind_param ("ssi", $name, $brand, $quantity);
//Execute
if($stmt -> execute()){
echo "success";
}
else {
echo "failure";
}
?>
script.js
$(document).ready(function(){
$('#btn').click(function(){
alert();
});
//The problem code!!!!
$('#product_form').submit(function(event){
event.preventDefault();
$.post(
'insert.php',
{
productname:$("#n").val(),
brandname:$("#b").val(),
value:$("#q").val(),
},
function(result){
if(result == "success"){
$("#result").html("Values inserted successfully!");
}
else{
$("#result").html("Error!");
}
}
);
});
});
In the second parameter to $.post you set the data to send to the server, you have
{
productname:$("#n").val(),
brandname:$("#b").val(),
value:$("#q").val()
}
So you need to change value: to quantity:, in order to have the ajax submission match what the traditional form submit would produce.

JSON Parse error: Unrecognized token '<' In angular

This is my angular code. form submit code. When click on submit button. JSON Parse error: Unrecognized token '<' this error will showing. empty records will save on the DB. I added html code and PHP server side code also for this.
$scope.submitForm = function() {
$http({
method : 'POST',
url : 'http://localhost/youtubewebservice/checkOutt.php',
data : $scope.user,
dataType: 'json',
headers : {'Content-Type': 'application/x-www-form-urlencoded'}
})
.success(function(data) {
if (data.errors) {
$scope.errorinputFName = data.errors.inputFName;
$scope.errorinputLName = data.errors.inputLName;
}
});
};
Html code
<form name="userForm" ng-submit="submitForm()">
<div class="form-group">
<label>Name</label>
<input type="text" name="inputFName" class="form-control" ng-model="user.inputFName">
<span ng-show="errorName">{{errorName}}</span>
</div>
<div class="form-group">
<label>Email</label>
<input type="text" name="inputLName" class="form-control" ng-model="user.inputLName">
<span ng-show="errorEmail">{{errorEmail}}</span>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
<div id="sendmessageresponse"></div>
</form>
**PHP code **
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json;charset=UTF-8");
$data = json_decode(file_get_contents("php://input"));
$inputFName = mysql_real_escape_string($data->inputFName);
$inputLName = mysql_real_escape_string($data->inputLName);
$con = mysql_connect('localhost', 'root', '');
mysql_select_db('look4com_lk', $con);
$qry_em = 'select count(*) as cnt from checkout where chkID ="' . $chkID . '"';
$qry_res = mysql_query($qry_em);
$res = mysql_fetch_assoc($qry_res);
if ($res['cnt'] == 0) {
$qry = 'INSERT INTO checkout (inputFName,inputLName) values ("' . $inputFName . '","' . $inputLName . '")';
$qry_res = mysql_query($qry);
if ($qry_res) {
$arr = array('msg' => "User Created Successfully!!!", 'error' => '');
$jsn = json_encode($arr);
print_r($jsn);
} else {
$arr = array('msg' => "", 'error' => 'Error In inserting record');
$jsn = json_encode($arr);
print_r($jsn);
}
} else {
$arr = array('msg' => "", 'error' => 'User Already exists with same email');
$jsn = json_encode($arr);
print_r($jsn);
}
This particular parse error indicates that the output is no valid JSON (duh). Since your output is formatted with json_encode, it should be. (Although I usually use print_r for arrays only ...) However ...
My experience tells me that your server produces an error / notice, which php usually outputs with some html, hence the <. Since you claim, that the response is clean JSON, I suggest you look at the actual responses your server sends. My assumption is, that you tested your php-script from command line (hence the php://input?) but a server possibly handles requests differently than you'd expect.
You can check the server's responses in the network tab of almost every decent browser, usually F12 -> network tab, then reload and/or resend the form. If you have problems solving your php-problem, add the php error message to your question or ask a new one.
As a final remark: Please avoid the mysql_* functions (deprecated mysql library) and either use the mysqli_* functions (mysqli library) or PDO. Also use prepared statements.
I found the error of this code. this code working properly. any one have any question ask. thanks
html code
<div ng-controller="ProductController">
<form name="userForm" ng-submit="submitForm()">
<div class="form-group">
<label>Name</label>
<input type="text" name="inputFName" class="form-control" ng-model="user.inputFName">
<span ng-show="errorName">{{errorName}}</span>
</div>
<div class="form-group">
<label>Email</label>
<input type="text" name="inputLName" class="form-control" ng-model="user.inputLName">
<span ng-show="errorEmail">{{errorEmail}}</span>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
<div id="sendmessageresponse"></div>
</form>
</div>
**PHP code **
$data = json_decode(file_get_contents("php://input"));
$inputFName = mysql_real_escape_string($data->inputFName);
$inputLName = mysql_real_escape_string($data->inputLName);
//localhost
$con = mysql_connect('localhost', 'root', '');
mysql_select_db('look4com_lk', $con);
$qry_em = 'select count(*) as cnt from checkout where inputFName ="' . $inputFName . '"';
$qry_res = mysql_query($qry_em);
$res = mysql_fetch_assoc($qry_res);
if ($res['cnt'] == 0) {
$qry = 'INSERT INTO checkout (inputFName,inputLName) values ("' . $inputFName . '","' . $inputLName . '")';
$qry_res = mysql_query($qry);
if ($qry_res) {
$arr = array('msg' => "User Created Successfully!!!", 'error' => '');
$jsn = json_encode($arr);
print_r($jsn);
} else {
$arr = array('msg' => "", 'error' => 'Error In inserting record');
$jsn = json_encode($arr);
print_r($jsn);
}
} else {
$arr = array('msg' => "", 'error' => 'User Already exists with same email');
$jsn = json_encode($arr);
print_r($jsn);
}
**controller code **
$scope.submitForm = function() {
// Posting data to php file
$http({
method : 'POST',
url : 'http://localhost/youtubewebservice/checkOutt.php',
data : $scope.user, //forms user object
headers : {'Content-Type': 'application/x-www-form-urlencoded'}
})
.success(function(data) {
if (data.errors) {
// Showing errors.
$scope.errorinputFName = data.errors.inputFName;
$scope.errorinputLName = data.errors.inputLName;
//$scope.errorMessage = data.errors.Message;
} else {
$scope.contactmessage = data.contactmessage;
//data: {Name: $scope.Name, Email: $scope.Email, Message: $scope.Message}
}
});
};

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.

Session not sending correctly through AJAX

I have the following code that I thought worked correctly, but it turns out the users session is not being sent correctly. Let's say I was on trying to make a post, it does not take my id, it takes the id of the last user who registered for my site. Why would this be?
I have this as my $userid variable and it should be taking my session. I am initializing the session at the top of the page.
What am I doing wrong?
$(document).ready(function(){
$("#submit_announcement").on("click", function () {
var user_message = $("#announcement_message").val();
//$user = this.value;
$user = $("#approved_id").val();
$.ajax({
url: "insert_announcements.php",
type: "POST",
data: {
"user_id": $user,
//"message": user_message
"user_message": user_message
},
success: function (data) {
// console.log(data); // data object will return the response when status code is 200
if (data == "Error!") {
alert("Unable to get user info!");
alert(data);
} else {
$(".announcement_success").fadeIn();
$(".announcement_success").show();
$('.announcement_success').html('Announcement Successfully Added!');
$('.announcement_success').delay(5000).fadeOut(400);
}
},
error: function (xhr, textStatus, errorThrown) {
alert(textStatus + "|" + errorThrown);
//console.log("error"); //otherwise error if status code is other than 200.
}
});
});
});
PHP and Form
$userid = ( isset( $_SESSION['user'] ) ? $_SESSION['user'] : "" );
try {
//Prepare
$con = mysqli_connect("localhost", "", "", "");
if ($user_stmt = $con->prepare("SELECT `id` FROM users")) {
$user_stmt->execute();
$user_stmt->bind_result($user_id);
if (!$user_stmt) {
throw new Exception($con->error);
}
}
$user_stmt->store_result();
$user_result = array();
?>
<div class="announcement_success"></div>
<p>Add New Announcement</p>
<form action="" method="POST" id="insert_announcements">
<input type="hidden" value="<?php echo $userid; ?>" id="approved_id" name="user_id" />
<textarea rows="4" cols="50" id="announcement_message" name="message" class="inputbarmessage" placeholder="Message" required></textarea>
<label for="contactButton">
<button type="button" class="contactButton" id="submit_announcement">Add Announcement</button>
</label>
</form>
UPDATE: PHP file to show an example
// $announcement_user_id= $_POST['user_id'];
$userid = ( isset( $_SESSION['user'] ) ? $_SESSION['user'] : "" );
$announcement_message= $_POST['user_message'];
$test = print_r($_POST, true);
file_put_contents('test.txt', $test);
//var_dump($announcement_user_id);
$con = mysqli_connect("localhost", "", "", "");
$stmt2 = $con->prepare("INSERT INTO announcements (user_id, message, date) VALUES (?, ?, NOW())");
if ( !$stmt2 || $con->error ) {
// Check Errors for prepare
die('Announcement INSERT prepare() failed: ' . htmlspecialchars($con->error));
}
if(!$stmt2->bind_param('is', $userid, $announcement_message)) {
// Check errors for binding parameters
die('Announcement INSERT bind_param() failed: ' . htmlspecialchars($stmt2->error));
}
if(!$stmt2->execute()) {
die('Announcement INSERT execute() failed: ' . htmlspecialchars($stmt2->error));
}
//echo "Announcement was added successfully!";
else
{
echo "Announcement Failed!";
}
You're selecting all of the users:
SELECT `id` FROM users
So when you get one record from that result, it's probably going to coincidentally be the latest record in the table.
You're trying to bind a parameter to i:
$user_stmt->bind_result($user_id);
so maybe you meant to have a WHERE clause?
SELECT `id` FROM users WHERE `id` = ?
Though, that seems... unnecessary. Since you already have the ID. You seem to be posting the ID from client-side, and keeping it in session state, and getting it from the database. So it's not entirely clear what you're even trying to do here. But one thing that is clear is that query is going to return every record from that table.

Categories

Resources