Why I'm getting the error in my jquery even though my record inserting in database? I add some changes in this code, I convert it into mysqli function. But the problem is the error message comes out? Why is that?
The error message is came from below on my script
Here's my code
Script
$(document).ready(function(){
$("#save").click(function(){
ajax("save");
});
$("#add_new").click(function(){
$(".entry-form").fadeIn("fast");
});
$("#close").click(function(){
$(".entry-form").fadeOut("fast");
});
$("#cancel").click(function(){
$(".entry-form").fadeOut("fast");
});
$(".del").live("click",function(){
if(confirm("Do you really want to delete this record ?")){
ajax("delete",$(this).attr("id"));
}
});
function ajax(action,id){
if(action =="save")
data = $("#userinfo").serialize()+"&action="+action;
else if(action == "delete"){
data = "action="+action+"&item_id="+id;
}
$.ajax({
type: "POST",
url: "ajax.php",
data : data,
dataType: "json",
success: function(response){
if(response.success == "1"){
if(action == "save"){
$(".entry-form").fadeOut("fast",function(){
$(".table-list").append("<tr><td>"+response.cat_name+"</td><td>"+response.cat_code+"</td><td>"+response.letter+"</td><td><a href='#' id='"+response.row_id+"' class='del'>Delete</a></td></tr>");
$(".table-list tr:last").effect("highlight", {
color: '#4BADF5'
}, 0000);
});
$(".entry-form input[type='text']").each(function(){
$(this).val("");
});
}else if(action == "delete"){
var row_id = response.item_id;
$("a[id='"+row_id+"']").closest("tr").effect("highlight", {
color: '#4BADF5'
}, 0000);
$("a[id='"+row_id+"']").closest("tr").fadeOut();
}
}else{
alert("unexpected error occured, Please check your database connection");
}
},
error: function(res){
alert("Unexpected error! Try again.");
}
});
}
});
AJAX
<?php
error_reporting(0);
$mysqli = new mysqli("localhost", "root", "", "2015");
if(isset($_POST) && count($_POST)){
$cat_name = $mysqli->real_escape_string($_POST["cat_name"]);
$cat_code = $mysqli->real_escape_string($_POST["cat_code"]);
$letter = $mysqli->real_escape_string($_POST["letter"]);
//$phone = mysql_real_escape_string($_POST['phone']);
$item_id = $_POST['item_id'];
$action = $_POST['action'];
if($action == "save"){
$result = $mysqli->query("insert into category values('','".$cat_name."','".$cat_code."','".$letter."')");
$lid = mysqli_insert_id();
if($lid){
echo json_encode(
array(
"success" => "1",
"row_id" => $lid,
"cat_name" => htmlentities($cat_name),
"cat_code" => htmlentities($cat_code),
"letter" => htmlentities($letter),
//"phone"=>$unique_id,
)
);
}else{
echo json_encode(array("success" => "0"));
}
}
else if($action == "delete"){
//echo "delete from info where id = '".$item_id."'";
$res = $mysqli->query("delete from category where id = '".$item_id."'");
if($res){
echo json_encode(array( "success" => "1","item_id" => $item_id));
}else{
echo json_encode(array("success" => "0"));
}
}
}else{
echo json_encode(array("success" => "0"));
}
?>
The Reponse returned in success block was zero because this statement here $lid = mysqli_insert_id(); returned nothing.
Replace $lid = mysqli_insert_id(); with $mysqli->insert_id , as this is the right syntax to get the id of the recently added/inserted row.
Happy Coding:)
I got it. mysqli_insert_id() needs the connection of the database.
It should be like this
mysqli_insert_id($mysqli);
Related
Hello I am new at coding and I have a question I hope some of you guys with some experience can help me with.
I have a page with some text and a button "Confirm". When this button is clicked by me, I first want to redirect to "loading.php" and in the mysql database I want to recieve "confirmed" or "ok" anything like that. Then in my dashboard I want to manually press "Next" on the unique-userid to redirect to "page3.php"
I would need some help with this and a simple "template" on how the button would be programmed in my php.
Script in my PHP where I have the button.
$(document).ready(function() {
var allInputs = $(":input");
$('#SubmitConfirm').submit(function(e) {
e.preventDefault();
var confirm = $('#confirm').val();
if (confirm == null) {
return false;
} else {
}
$.ajax({
type: 'POST',
url: 'files/action.php?type=confirm',
data: $('#confirm').serialize(),
success: function(data) {
console.log(data);
var parsed_data = JSON.parse(data);
if (parsed_data.status == 'ok') {
//console.log(parsed_data);
location.href = "Loading.php"
} else {
return false;
}
//console.log(parsed_data.status);
}
})
});
});
And here is "confirm" in action.php
if($_GET['type'] == 'confirm'){
if($_POST['confirm'] == true){
$submit = $_POST['confirm'];
$uniqueid = $_POST['userid']; // unique userid
$query = mysqli_query($conn, "UPDATE customers SET confirm='$confirm', status=1, buzzed=0 WHERE uniqueid=$uniqueid");
if($query){
echo json_encode(array(
'status' => 'ok'
));
}else{
echo json_encode(array(
'status' => 'notok'
));
}
}
}
}
I have tried but I only got 404 error when I pressed the button
from dashboard.
$query = mysqli_query($conn, "SELECT * from customers");
if($query){
if(mysqli_num_rows($query) >= 1){
$array = mysqli_fetch_all($query,MYSQLI_ASSOC);
//print_r($array);
}
}
foreach($array as $value){
$user = $value['user'];
$confirm = $value['submit'];
$info = "
uniqueID : $user
Confirm: $confirm
echo "
I am doing a custom script to restrict a private website, user need access-code and their last name to access the website. The Webiste made with WordPress while the restrict credentials was from an external php application.
I have two files one is home.php and another is autho.php. The login form is in home.php where the form and Ajax code written their. The autho.php is the server-side script and creating the session to restrict WordPress site.
The session validation happening at /wp-content/themes/twentynineteen/header.php file. At the area of wordpress site I cannot able to find the session data which was created at autho.php. Please suggest.
home.php (login form)
<script type='text/javascript'>
$(document).ready(function(){
$('#login_error').hide();
$('#accessform').on('submit', function(event){
event.preventDefault();
$.ajax({
url:"doctor_autho.php?action=login&type=login",
method:"POST",
data:$(this).serialize(),
dataType:"json",
beforeSend:function(){
$('#submit').attr('disabled', 'disabled');
},
success:function(data)
{
if(data.result = 'false')
{
$('#login_error').show();
$('#login_error').html("<strong> Doctors last name or code is invalid </strong>");
$('#submit').prop('disabled', false);
}
if(data.result = 'true')
{
$('#login_error').show();
$('#login_error').html("<strong> Access Granted !!! </strong>");
window.location.href = "/index.php");
}
$('#submit').attr('disabled', false);
},
error: function (response) {
$('#login_error').show();
$('#login_error').html("<strong> Doctors last name or code is invalid </strong>");
$('#submit').prop('disabled', false);
}
})
});
});
</script>
autho.php PHP file
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error){
die("Connection failed: " . $conn->connect_error);
}
$type = isset($_GET['type'])?$_GET['type']:"";
$action = isset($_GET['action'])?$_GET['action']:"";
if(isset($_POST) && $action == "login" && $type=="login"){
$doctor_invitation_code= isset($_POST['doctor_invitation_code'])?$_POST['doctor_invitation_code']:"";
$doctor_last_name= isset($_POST['doctor_last_name'])?$_POST['doctor_last_name']:"";
if($doctor_invitation_code =="" OR $doctor_last_name ==""){
$data = array("result" => "false", "msg" => "Parameter is required");
die(json_encode($data));
}else{
check_login($doctor_invitation_code,$doctor_last_name);
}
}else{
$data = array("result" => "false", "msg" => "Parameter wrong used!");
die(json_encode($data));
}
function check_login($doctor_invitation_code,$doctor_last_name){
Global $conn;
$doct_auto_query ="SELECT * FROM `tbl_user_master` WHERE patient_invition_code='".$doctor_invitation_code."' AND user_lname='".$doctor_last_name."' AND user_type='2' and is_deleted=0 limit 1";
//echo $doct_auto_query;
$result = $conn->query($doct_auto_query);
if($result->num_rows > 0){
$data = array("result" => "true", "msg" => "Access Granted !!!");
session_start();
$_SESSION['invitation_code'] = $doctor_invitation_code;
$_SESSION['last_name'] = $doctor_last_name;
die(json_encode($data));
}else{
$data = array("result" => "false", "msg" => "The Invitation code or Last Name is wrong used!");
header ("Location: home.php");
die(json_encode($data));
}
}
Session validation on theme's header.php file
session_start();
if (!isset($_SESSION['invitation_code']) && !isset($_SESSION['last_name']) ) {
header("Location: https://www.website.com/home.php");
}
At WordPress site under the theme header file I cannot able to access $_SESSION['invitation_code'] and $_SESSION['last_name'] there, please suggest how to fix this.
At First Put the session_start(); at wp-config.php file.
define( 'WP_SESSION_USE_OPTIONS', true );
session_start();
Your JQuery something like this
<script type='text/javascript'>
$(document).ready(function(){
$('#login_error').hide();
$('#accessform').on('submit', function(event){
event.preventDefault();
$.ajax({
url:"autho.php?action=login&type=login",
method:"POST",
data:$(this).serialize(),
dataType:"json",
beforeSend:function(){
$('#submit').attr('disabled', 'disabled');
},
success:function(data)
{ console.log(data);
if(data.result =="true") {
$('#login_error').show();
$('#login_error').html("<strong> "+data.msg+" </strong>");
window.location.href = "index.php";
return false;
}
if(data.result == "false") {
$('#login_error').show();
$('#login_error').html("<strong> "+data.msg+" </strong>");
$('#submit').prop('disabled', false);
return false;
}
$('#submit').attr('disabled', false);
},
error: function (response) {
$('#login_error').show();
$('#login_error').html("<strong> There is an error! </strong>");
$('#submit').prop('disabled', false);
}
})
});
});
</script>
Your PHP code something like this
<?php
$con = mysqli_connect("127.0.0.1","dbuser","dbpassword","dbname");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
exit();
}
$doctor_last_name = mysqli_real_escape_string($con, $_POST['doctor_last_name']);
$password = mysqli_real_escape_string($con, $_POST['doctor_invitation_code']);
if($doctor_last_name !="" && $password !=""){
$query ="SELECT * FROM `tbl_user_master` WHERE is_deleted=0 AND user_type='2' ";
if($doctor_last_name !=""){
$query .=" AND user_lname='".$doctor_last_name."' ";
$data=mysqli_query($con, $query);
if ($data){
if (mysqli_num_rows($data) == 0){
$data = array("result" => "false", "msg" => "The Last Name is invalid.");
}
}
}
//end
//validation for invitation code
if($password !=""){
$query .=" AND patient_invition_code='".$password."' ";
$data=mysqli_query($con, $query);
if ($data){
if (mysqli_num_rows($data) == 0){
$data = array("result" => "false", "msg" => "The Invitation Code is invalid.");
}
}
}
$data=mysqli_query($con, $query);
if ($data){
if (mysqli_num_rows($data) > 0){
session_start();
$_SESSION['invitation_code'] = $password;
$_SESSION['last_name'] = $doctor_last_name;
$data = array("result" => "true", "msg" => "Access Granted !!!");
echo json_encode($data);
exit();
}else {
//validation of code and lastname only
$data = array("result" => "false", "msg" => "The Last name & Invitation Code is invalid.");
echo json_encode($data);
exit();
}
}
}else{
$data = array("result" => "false", "msg" => "Parameter is required.");
echo json_encode($data);
exit;
}
reset($doctor_last_name);
reset($password);
mysqli_close($con);
exit;
?>
And Lastly you can put session validation in any header file of your WordPress theme.
session_start();
if(!isset($_SESSION['invitation_code']) || $_SESSION['invitation_code'] == '') {
header('location:home.php');
}
So I have these codes wherein I want a notification to appear in every event. I want to check if the record exists, then a notification will appear, saying the college already exists. But that doesn't happen tho. I keep on inputting duplicate input, but the notification still says it's successful. Is there a mistake in my code?
add-college.php
<?php
function findDuplicate($code) {
try {
include($_SERVER['DOCUMENT_ROOT']."/config/db-config.php");
$sql = "SELECT * FROM colleges WHERE collegecode = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("s", $code);
$stmt->execute();
$stmt->store_result();
if ($stmt->num_rows > 0) {
return true;
}
else {
return false;
}
}
catch (Exception $e) {
return false;
}
}
try {
include($_SERVER['DOCUMENT_ROOT']."/config/db-config.php");
$code = $_POST['code'];
$name = $_POST['name'];
$result = array();
if (findDuplicate($code)) {
$result['message'] = 'duplicate';
}
else {
$sql = "INSERT INTO colleges(collegecode, collegename) VALUES(?, ?)";
$stmt = $conn->prepare($sql);
$stmt->bind_param("ss", $code, $name);
if ($stmt->execute()) {
$result['message'] = 'success';
}
else {
$result['message'] = 'error';
}
}
echo json_encode($result);
}
catch (Exception $e) {
echo json_encode($result);
}
?>
script.js
$("#save-new").click(function() {
var form = $("#add-college");
var code = $("#code").val();
var name = $("#name").val();
$.ajax({
type: "POST",
data: {
code: code,
name: name
},
url: "../ajax/add-college.php",
dataType: "html",
success: function(data) {
if (data.message = "success") {
$.notify({
// options
message: 'College has been added.'
},{
// settings
type: 'success'
});
}
else if (data.message = "duplicate") {
$.notify({
// options
message: 'College already exists.'
},{
// settings
type: 'warning'
});
}
else {
$.notify({
// options
message: 'College cannot be added.'
},{
// settings
type: 'error'
});
}
$("#code").val("");
$("#name").val("");
$("#add-new").modal('hide');
showColleges();
}
});
});
data.message = "success" this is assignment operation, if you want to compare two string use == operator.
So, the correct statement would be for the if condition would be if(data.message == "success")
Similarly, if(data.message == "duplicate"). I am sure you are aware of all this!
I'm new using ajax and I have a code to display from wordpress some information from database columns.
I have this PHP code to connect with the database and create the JSON file:
<?php
$username = $_REQUEST['username'];
$password = $_REQUEST['password'];
if (isset($username) && isset($password)) {
//CONEXION
$host="localhost";
$user="DB_Username";
$pass="DB_Password";
$dbname="DB_Name";
//Conexion
$conexion = mysqli_connect($host, $user, $pass,$dbname)
or die("unexpected error");
//gWe made the search
$sql = "SELECT * FROM Column WHERE A_Login='$username'";
mysqli_set_charset($conexion, "utf8");
if(!$result = mysqli_query($conexion, $sql)) die();
$clients = array();
$num_result = mysqli_num_rows($result);
if ($num_result == 0) {
$clients = array("error" => "true", "msg" => "We can't found this user", "data" => $username);
} else {
while($row = mysqli_fetch_array($result))
{
$id=$row['ID'];
$Name=$row['Name'];
if ($row['A_Login'] == $username && $row['A_Password'] == $password){
$clients[] = array('id'=> $id, 'Name'=> $Name);
} else {
$clients[] = array('error'=> "true", "msg" => "Incorrect data");
}
}
}
$close = mysqli_close($conexion)
or die("Unespected error with DB");
}
else {
$clients = array("error" => "true", "msg" => "You must fill all fields", "username" => $username);
}
//We build the JSON
$json_string = json_encode($clients);
echo $json_string;
?>
In a wordpress page I have this code, I build a form where if the user click the submit button call doLogin()
<script type="text/javascript"> function doLogin(){
data = {username: jQuery("#user").val(), password: jQuery("#pass").val()}
console.log(data);
jQuery.ajax({
type: "POST",
url: "Mywebsiteurl.php",
data: data,
beforeSend: function(){
},
success: function(data){
console.log(data);
//var arr = JSON.parse(data);
//$('#forma').html(data);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Error");
console.log(textStatus);
console.log(errorThrown);
}
});
} </script>
I need to show in <div id="forma"> a kind of list usign html, for example:
Id: VALUE ID
Name: VALUE NAME
and more information...
When i try to print in my website the required information using $('#forma').html(data); I obtain error or just an empty space.
How can I fix it? thanks.
In WordPress we need to hook the ajax hook to your check_user function here.
add_action('wp_ajax_your_action_from_js', 'your_function');
//Using ajax for non-logged users as well (PUBLIC)
add_action('wp_ajax_nopriv_your_action_from_js', 'your_function');
Check below code for how it is done regarding your context.
In functions.php
function check_user() {
$username = $_REQUEST['username'];
$password = $_REQUEST['password'];
if (isset($username) && isset($password)) {
//CONEXION
$host="localhost";
$user="DB_Username";
$pass="DB_Password";
$dbname="DB_Name";
//Conexion
$conexion = mysqli_connect($host, $user, $pass,$dbname)
or die("unexpected error");
//gWe made the search
$sql = "SELECT * FROM Column WHERE A_Login='$username'";
mysqli_set_charset($conexion, "utf8");
if(!$result = mysqli_query($conexion, $sql)) die();
$clients = array();
$num_result = mysqli_num_rows($result);
if ($num_result == 0) {
$clients = array("error" => "true", "msg" => "We can't found this user", "data" => $username);
} else {
while($row = mysqli_fetch_array($result))
{
$id=$row['ID'];
$Name=$row['Name'];
if ($row['A_Login'] == $username && $row['A_Password'] == $password){
$clients[] = array('id'=> $id, 'Name'=> $Name);
} else {
$clients[] = array('error'=> "true", "msg" => "Incorrect data");
}
}
}
$close = mysqli_close($conexion)
or die("Unespected error with DB");
}
else {
$clients = array("error" => "true", "msg" => "You must fill all fields", "username" => $username);
}
//We build the JSON
$json_string = json_encode($clients);
echo $json_string;
}
add_action('wp_ajax_check_user', 'check_user');
//Using ajax for non-logged users as well (PUBLIC)
add_action('wp_ajax_nopriv_check_user', 'check_user');
In your JS called file.
In the script the action is related to your _your_action_from_js. So action is needed for knowing where the ajax has to hit. In our case it executes our check_user and returns the appropriate values.
<script type="text/javascript">
function doLogin(){
data = {action: 'check_user', username: jQuery("#user").val(), password: jQuery("#pass").val()}
console.log(data);
jQuery.ajax({
type: "POST",
url: ajax_url,
data: data,
beforeSend: function(){
},
success: function(data){
console.log(data);
//var arr = JSON.parse(data);
//$('#forma').html(data);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Error");
console.log(textStatus);
console.log(errorThrown);
}
});
}
</script>
Reference Simple AJAX Form: http://wptheming.com/2013/07/simple-ajax-example/
CODEX Reference: https://codex.wordpress.org/AJAX_in_Plugins
WordPress has specific methods to enable ajax requests.
// registering ajax request for Logged users
add_action( 'wp_ajax_my_action', 'my_action_callback' );
// registering ajax request also for public area
add_action( 'wp_ajax_nopriv_my_action', 'my_action_callback' );
function my_action_callback()
{
// Your code here
wp_die(); // this is required to terminate immediately and return a proper response
}
To call it:
jQuery(document).ready(function($) {
var data = {action: "my_action", username: jQuery("#user").val(), password: jQuery("#pass").val()}
jQuery.ajax({
url: '/wp-admin/admin-ajax.php',
data: data,
method: 'POST',
success: function(response) {
console.log(response);
},
error: function(a,b,c) {
}
});
});
Source: https://codex.wordpress.org/AJAX_in_Plugins
i am facing an problem in sending data from ajax to php i would need some help
$.ajax({
type: "post",
url: "/raffle.php",
dataType: "json",
data: {
"postraffle": "true",
"title": $("#rtitle").val(),
"message": $("#mess").val(),
"maxentry": $("#maxentry").val(),
"duration": $("#durr").val(),
"filter": $("#reffil").val(),
"split": $("input[name=split]:checked").val(),
"pub": $("input[name=rafflepub]:checked").val(),
"stype": $("input[name=stype]:checked").val(),
"invo": $("input[name=invo]:checked").val(),
"items[]": itms,
"games[]": gmes,
},
success: function(data){
if(data.status == "fail")
{
alert(data.message);
$("#rafBut").removeAttr("disabled");
$("#rafBut").attr("value", "Raffle it!");
}
else if(data.status == "ok")
{
alert(data.message);
}
}
});
and the php script is here
<?php
// getting data from AJAX
$raffle_title = $_POST['title'];
$raffle_message = $_POST['message'];
$raffle_maxentry = $_POST['maxentry'];
$raffle_duration = $_POST['duration'];
$raffle_filter = $_POST['filter'];
$raffle_split = $_POST['split'];
$raffle_pub = $_POST['pub'];
$raffle_stype = $_POST['stype'];
$done = false;
$data = array(
'status' => 'ok',
'message' => 'saved! redirecting you!',
'datakey' => 'HALLEYO!',
);
$host ="localhost"; // enter your host.
$pass =""; // enter your password.
$db = "test"; // Enter your database..
$user ="4"; // enter your username.
# MYSQL Connection
$con=mysqli_connect($host,$user,$pass,$db);
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
foreach($_POST['items'] as $item){
$query = "INSERT INTO table (heading,content,items) VALUES ('".$_POST['title']."', '".$_POST['message']."','".$item."')";
// this should also be done for each item
if (!mysqli_query($con, $query)) {
printf("Error: %s\n", mysqli_error($con));
}
}
echo $data;
?>
Now the function of the above script is to get the data from ajax and upload it to mysql database and send an response to the ajax script back which currently doesnt work.
i think there may be problem with my mysql query (php mysqli parameterized queries)
Some help would be really appreciated.
Thanks!
Try replacing
echo $data;
with
echo json_encode($data);
echoing data will give just "Array" string, not anything JSON encoded
You can not print arrays!
You must chenge it echo $data; to echo json_encode($data);.