Executing PHP function on click of a link - php

I want to trigger a PHP function on click of a link or button. How can I do it? I have used javascript onclick functionality but is there any way to do so ?

Better go for jquery, ajax for sending data in json format.! Like
code.js
$(document).ready(function(){
$("#submit").click(function(e){
var status = $('form')[0].checkValidity();
if(status){
var formData = new FormData($('form')[0]);
$.ajax({
url: "code.php",
type: "POST",
data: formData,
processData: false,
contentType: false,
async: false,
dataType: "JSON",
success: function(json){
if(json.error){
alert(json.error_msg);
e.preventDefault();
}else{
alert("Data stored successfully!");
}
},
error: function(jqXHR, textStatus, errorThrown){
alert(errorThrown);
}
});
}
});
});
code.php
<?php
define('HOST','localhost');
define('USER','***');
define('PASS','***');
define('DB','***');
$response = array();
$con = mysqli_connect(HOST,USER,PASS,DB) or die('Unable to Connect');
if(!mysqli_connect_errno()){
$error_flag = false;
/*foreach($_POST as $value){
if(empty($value)){
$error_flag = true;
break;
}
}*/
if(!$error_flag){
//receiving post parameters
$sdn =$_POST['sdn'];
// create a new user profile
$sql = "INSERT INTO safety(sdn, created_at) VALUES ('$sdn',NOW())";
if(mysqli_query($con,$sql)){
$response["error"] = false;
echo json_encode($response);
}else{
$response["error"] = true;
$response["error_msg"] = "INSERT operation failed";
echo json_encode($response);
}
}else{
$response["error"] = true;
$response["error_msg"] = "Few fields are missing";
echo json_encode($response);
}
}else{
$response["error"] = true;
$response["error_msg"] = "Database connection failed";
echo json_encode($response);
}
?>
And lastly use jquery link inside
code.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript" src = "code.js"></script>
</head>
<body>
<form id="form" name ="form" method = "POST" action="Next_page.html" class="wizard-big" autocomplete = "off">
<div class="col-sm-3 form-group">
<input type="text" placeholder="sdn" class="form-control" id="sdn" name="sdn">
<div class="col-sm-12 form-group">
<input style="width:100%" type="submit" name = "submit" id = "submit" value = "Save and continue" class="btn btn-success">
</div>
</div>
</form>
</body>
</html>

Related

How to insert multiple row from textarea to multiple column?

I have this code from index.php :
<?php
require("../inc/config.php");
$url = $_GET['url'];
?>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
</head>
<body>
<form method="" action="">
<textarea type="text" class="form-control" id="ketqua" name="ketqua" value="" required="" placeholder="Name|Url" rows="6"></textarea>
<input type="text" class="form-control" id="link" name="link" required="" value="<?php echo $url ?>">
<button type="button" class="btn btn-success" name="insert-data" id="insert-data" onclick="ThemTap()">Add</button>
</form>
<script type="text/javascript">
function ThemTap() {
var ketqua = $("#ketqua").val();
var link = $("#link").val();
$.ajax({
type: "POST",
url: "api.php",
data: {
action: 'ThemTap',
ketqua: ketqua,
link: link
},
dataType: "JSON",
success: function(data) {
$("#message").html(data);
$("p").addClass("alert alert-success");
},
error: function(err) {
alert(err);
}
});
}
</script>
This is my api.php .I think my code is missing or missing in this section and I don't know how to solve it:
<?php
include('../inc/config.php');
if($_POST['action'] == 'ThemTap') {
$ketqua=$_POST['ketqua'];
$string = $ketqua;
$HuuNhan = explode('|',$string);
$link=$_POST['link'];
$stmt = $DBcon->prepare("INSERT INTO tap(tap,link,player) VALUES(N'".$HuuNhan[0]."', N'$link',N'".$HuuNhan[1]."')");
mysqli_query($conn,"UPDATE phim SET updatephim = updatephim + 1 WHERE link = '$link'");
if($stmt->execute())
{
if (mysqli_query($conn, $sql)) {
}
$res="<div class='alert alert-success'>Đã thêm tập <b>".$HuuNhan[0]."</b> thành công !</div>";
echo json_encode($res);
}
else {
$error="<div class='alert alert-danger'>Thêm không thành công</div>";
echo json_encode($error);
}
}
?>
I tried running it as follows:
From text area
EP1|Link1
EP2|Link2
EP3|Link3
But it only inserts a row:
EP1|Link
And not insert EP2|Link2 and EP3|Link3
Please correct my source code so I can add many different rows, thank you very much!

ajax login error, can't check

I have problem, I can't check username and password, can you help me?
login.php:
<form class="login-form" method="post" name="loginform" action="">
<div class="title-section">
<h1><span>Login</span></h1>
</div>
<p>Welcome! Login in to your account</p>
<label for="user_login">Username or email address<span>*</span>
</label>
<input type="text" name="log" id="user_login">
<label for="user_pass">Password<span>*</span>
</label>
<input name="pwd" id="user_pass" type="password">
<div id="error"></div>
<button type="submit" name="submit-login" id="submit-login"> <i class="fa fa-arrow-circle-right"></i> Login </button>
</form>
model.php;
<?php
ob_start();
session_start();
error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED);
?>
<?php
global $pdo;
session_start();
if(isset($_POST['submit-login'])) {
$user_email = trim($_POST['log']);
$user_password = trim($_POST['pwd']);
try {
global $pdo;
$stmt = $pdo->prepare("SELECT * FROM user WHERE username=:email");
$stmt->execute(array(":email"=>$user_email));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$count = $stmt->rowCount();
if($row['user_password']==$password){
echo "ok"; // log in
echo $_SESSION['user_session'] = $row['id_user'];
}
else {
echo "email or password does not exist."; // wrong details
}
}
catch(PDOException $e){
echo $e->getMessage();
}
}
?>
ajax.js
$(document).ready(function(){
$("#submit-login").click(function(){
username=$("#user_login").val();
password=$("#user_pass").val();
$.ajax({
type: "POST",
url: "admin/module/admin/model/acc_model.php",
data: "name="+username+"&pwd="+password,
success: function(html){
if(html=='ok') {
window.location="profile.php";
}
else {
alert('Please, Error');
}
},
beforeSend:function() {
$("#error").html("<img src='http://www.chinesecio.com/templates/base/images/loading.gif' /> Loading...")
}
});
return false;
});
});
You should pass the data like this
$(document).ready(function(){
$("#submit-login").click(function(){
username=$("#user_login").val();
password=$("#user_pass").val();
$.ajax({
type: "POST",
url: "admin/module/admin/model/acc_model.php",
data: {
name : username,
pwd : password
},
success: function(html){
if(html=='ok') {
window.location="profile.php";
}
else {
alert('Please, Error');
}
},
beforeSend:function()
{
$("#error").html("<img src='http://www.chinesecio.com/templates/base/images/loading.gif' /> Loading...")
}
});
return false;
});
});
Also use parameter like below :
$user_email = trim($_POST['name']);
$user_password = trim($_POST['pwd']);
I think that when you are sending data from your ajax request you are using different variable names and in your model.php you are using your form elements name. Please check into that
data : {"name":username, "password ":password}

I am enable to get the success message..!

i am trying to get the user details into database and data is stored..i want a success message to fade in i have tried out some code but sadly its not working...plzz help me out of this..beg u pardon if am wrong..
here gose my register.php code
<?php
require_once 'DB_Functions.php';
$db = new DB_Functions();
// json response array
$response = array("error" => false);
if (!empty($_POST['fname']) && !empty($_POST['lname']) && !empty($_POST['email']) && !empty($_POST['password']) && !empty($_POST['mobile'])){
// receiving the post params
$fname = trim($_POST['fname']);
$lname = trim($_POST['lname']);
$email = trim($_POST['email']);
$password = $_POST['password'];
$mobile = trim($_POST['mobile']);
// validate your email address
if(filter_var($email, FILTER_VALIDATE_EMAIL)) {
// valid email address
if ($db->isUserExisted($email)) {
// user already existed
$response["error"] = true;
$response["error_msg"] = "User already existed with " . $email;
echo json_encode($response);
} else {
// create a new user
$user = $db->storeUser($fname, $lname, $email, $password, $mobile);
if ($user) {
// user stored successfully
$response["error"] = false;
$response["uid"] = $user["id"];
$response["user"]["fname"] = $user["fname"];
$response["user"]["lname"] = $user["lname"];
$response["user"]["email"] = $user["email"];
$response["user"]["created_at"] = $user["created_at"];
$response["user"]["updated_at"] = $user["updated_at"];
echo json_encode($response);
} else {
// user failed to store
$response["error"] = true;
$response["error_msg"] = "Unknown error occurred in registration!";
echo json_encode($response);
}
}
} else {
// invalid email address
$response["error"] = true;
$response["error_msg"] = "invalid email address";
echo json_encode($response);
}
} else {
$response["error"] = true;
$response["error_msg"] = "Required parameters are missing!";
echo json_encode($response);
}
?>
and here gose the .html file with jquery..
<html>
<head>
<title>jQuery Test</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript" src = "register.js"></script>
</head>
<body>
<!--html body-->
<form name = "register" id = "register" method = "POST">
<label>First name:</label>
<input type = text name = "fname" id = "fname" required>
<label>Last name:</label>
<input type = "text" name = "lname" id = "lname" required>
<label>E-mail:</label>
<input type = "email" name = "email" id = "email" required>
<label>Password</label>
<input type = "password" name = "password" id = "password" required>
<label>Mobile no:</label>
<input type = "number" name = "mobile" id = "mobile" required>
<input type="submit" value="Insert" name="submit" id = "submit">
</form>
<div id = "result" align = "right"></div>
</body>
</html>
here gose me /.js/ file
$(document).ready(function(){
$("#submit").click(function(e){
e.preventDefault();
$.ajax({
url: "register.php",
type: "POST",
data: {
fname: $("#fname").val(),
lname: $("#lname").val(),
email: $("#email").val(),
password: $("#password").val(),
mobile: $("#mobile").val()
},
dataType: "JSON",
success: function (json) {
$("#result").html(json.user.email); // like that you can display anything inside #result div
$("#result").fadeOut(1500);
},
error: function(jqXHR, textStatus, errorThrown){
alert(errorThrown);
}
});
});
});
There's no need to use JSON.stringify(jsonStr) because jQuery has already parsed the response object for you. jQuery will look at the Content-Type of the response and, if it's application/json, it will parse it, and provide the parsed result to your success handler.
Your jQuery should be like this:
$(document).ready(function(){
$("#submit").click(function(e){
e.preventDefault();
$.ajax({
url: "register.php",
type: "POST",
data: {
fname: $("#fname").val(),
lname: $("#lname").val(),
email: $("#email").val(),
password: $("#password").val(),
mobile: $("#mobile").val()
},
dataType: "JSON",
success: function (json){
if(json.error){
$("#result").html(json.error_msg); // display error message
}else{
$("#result").html(json.user.email); // like that you can display anything inside #result div
}
$("#result").fadeOut(1500);
},
error: function(jqXHR, textStatus, errorThrown){
alert(errorThrown);
}
});
});
});

how to put the form content into database and give back a php response?

I have created a html form which sends certain variables to a php file, the file is saved in the database and returns the success through json back to the javascript. But the problem is am not able to save the data and get the response back to the javascript file. I donno what is the reason. So can some help me with this. Thank you
my form is
<!doctype html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"> </script>
<script src="scriptj.js"></script>
</head>
<body>
<form action="http://localhost/donotdel/process.php" method="POST">
<div id="name-group" class="form-group">
<label for="name">Name</label>
<input type="text" class="form-control" name="name" placeholder="name">
</div>
<div id="email-group" class="form-group">
<label for="email">Email</label>
<input type="text" class="form-control" name="email" placeholder="email">
</div>
<button type="submit" class="btn btn-success">Submit <span class="fa fa-arrow-right"></span></button>
</form>
</body>
</html>
my javascript file is
$(document).ready(function () {
$('form').submit(function (event) {
$('.form-group').removeClass('has-error');
$('.help-block').remove();
var formData = {
'name': $('input[name=name]').val(),
'email': $('input[name=email]').val(),
};
$.ajax({
type: 'POST',
url: 'http://localhost/donotdel/process.php',
data: formData,
dataType: 'json',
encode: true
}).done(function (data) {
console.log(data);
if (!data.success) {
if (data.errors.name) {
$('#name-group').addClass('has-error');
$('#name-group').append('<div class="help-block">' + data.errors.name + '</div>');
}
if (data.errors.email) {
$('#email-group').addClass('has-error');
$('#email-group').append('<div class="help-block">' + data.errors.email + '</div>');
}
}
else {
$('form').append('<div class="alert alert-success">' + data.message + '</div>');
}
}).fail(function (data) {
console.log(data);
});
event.preventDefault();
});
});
and my php file is
<?php
$errors = array();
$data = array();
if (empty($_POST['name']))
$errors['name'] = 'Name is required.';
if (empty($_POST['email']))
$errors['email'] = 'Email is required.';
if ( ! empty($errors)) {
$data['success'] = false;
$data['errors'] = $errors;
} else {
$data['success'] = true;
$data['message'] = 'Success!';
}
header ('Content-Type: application/json');
header("Access-Control-Allow-Origin: *");
echo json_encode($data);
?>
now from the above php file i want to enter the name and email into the database. but i donno how to do it. So can someone help me out with the code. and after entering i want to send the above json response back to the javascript
thank you
What you need to do is establish a database connection and use that database connection to insert a new row in the users table. If the sql errors out return the error, if it works return the json data. Make sure to close the connection to the database when you are done.
Start by building a dbconfig.php file
This is used to establish the connection to your database.
This is what a simple one looks like.
<?php
$servername = "localhost";
$username = "root";
$password = "temppass";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
?>
Include the dbcong.php in your file
include ('dbconfig.php');
// Check connection
if (mysqli_connect_error()) {
die("Database connection failed: " . mysqli_connect_error());
}else{
//if it make a connection insert code here!
$qry = "INSERT ..."; //build your insert string here!
$conn->query($qry); // run your insert here!
//Don't forget to CLOSE YOUR CONNECTION!
$conn->close();
}

Getting all the content of table and append it using ajax with jquery

I made a simple sample on how to insert using AJAX and retrieving it then append it in a <div> after getting it. But I am having trouble on getting all the content of the table, it's returning a null values.
<div id="wrap-body">
<form action method="post">
<input type="text" name="username" id="username">
<input type="text" name="msg" id="msg">
<input type="button" id="submit" value="Send">
</form>
<div id="info">
</div>
</div>
jQuery:
<script>
$(document).ready(function (){
$('#submit').click(function (){
var username = $('#username').val();
var msg = $('#msg').val();
$.ajax({
type: 'POST',
url: 'get.php',
dataType: 'json',
data:'username='+username+'&msg='+msg,
success: function (data){
$('#info').append("<p> you are:"+data.username+"</p> <p> your message is:"+data.mesg);
}
});
});
});
</script>
PHP:
<?php
$host='localhost';
$username='root';
$password='12345';
$db = 'feeds';
$connect = mysql_connect($host,$username,$password) or die("cant connect");
mysql_select_db($db) or die("cant select the".$db);
$username = $_POST['username'];
$msg = $_POST['msg'];
$insert = "INSERT INTO info(user_name,message) VALUES('$username','$msg')";
if(#!mysql_query($insert)){
die('error insertion'.mysql_error());
}
$get = "SELECT * FROM info ";
$result=mysql_query($get)or die(mysql_error());
while ($row = mysql_fetch_array($result))
{
$return = $row['user_name'];
$return = $row['message'];
}
echo json_encode($return);
?>
Your while should create array and then do json_encode
Try below code
$data=array();
while ($row = mysql_fetch_array($result))
{
$data[] = array(
'username'=>$row['user_name'],
'mesg'=>$row['message']
);
}
echo json_encode($data);
exit
Now write your javascript success handler as below
$.ajax({
type: 'POST',
url: 'get.php',
dataType: 'json',
data:'username='+username+'&msg='+msg,
success: function (data){
$.each(data, function(i, item) {
$('#info').append("<p> you are:"+data[i].username+"</p> <p> your message is:"+data[i].mesg);
});​
}
});
There are several issues you have to fix, but you have to start with returning the same type as expected by the ajax call:
$return = array()
if ($row = mysql_fetch_array($result))
{
$return['username'] = $row['user_name'];
$return['mesg'] = $row['message'];
}
echo json_encode($return);

Categories