Database not updating using php and jquery - php

Basically, I want the status to change based on the id. There's no error but it is not updating.
index.php
$(document).ready(function() {
$('.seatCharts-seat').click(function(){
var id = jQuery(this).attr("id");
$seatid = id;
$.post("class/booking.php",
{
seatid:$seatid
},
function(data, status){
console.log('data',data);
console.log('status',status);
console.log($seatid);
});
});
});
booking.php
<?php
require_once 'config.php';
class booking extends config{
public $id;
public function __construct($id){
$this->id = $id;
}
public function editTask(){
$con = $this->con();
$sql = "UPDATE `tbl_booking` SET `status`= 'unavailable' WHERE `id` = $this->id";
$data = $con->prepare($sql);
if($data->execute()){
return true;
}else{
return false;
}
}
}
?>

Option 1 is to create a common file to handle all ajax related activities for the project. Say I would call it as myAjaxHandler.php
Then I would include the required class files are creates its instances to get the required methods called. Keep in mind when your projects get bigger it would be a bit difficult to maintain.
myAjaxHandler.php
<?php
require_once 'booking.php';
if(!empty($_POST) && isset($_POST['seatid'])) {
$booking = new booking($_POST['seatid']);
$result = $booking->editTask();
echo $result; // Would get 1 for true & 0 for false
}
Changes to ajax
$.post("path/to/myAjaxHandler.php",
{
seatid: $seatid
},
function(data, status){
console.log('data',data);
console.log('status',status);
});
Option 2 is to have the above if block inside the booking.php file itself.
<?php
require_once 'config.php';
if(!empty($_POST) && isset($_POST['seatid'])) {
$booking = new booking($_POST['seatid']);
$result = $booking->editTask();
echo $result; // Would get 1 for true & 0 for false
}
class booking extends config { ... }
//Ajax
$.post("path/to/booking.php",
{
seatid: $seatid
},
function(data, status){
console.log('data',data);
console.log('status',status);
});

Related

php function returning value for some pages, but fails to return values for other pages with same document structure

So here I want to get an ID for the specific user, using a php page, and then perform database insert using a function defined in a file named 'functions.php'. So basically, I am capturing values from a page using jQuery ajax() method and sending the data to a php page named 'follow_school.php'. The rest of what's happening would be clear from the code, I provide below:
jQuery code:
jQuery(document).ready(function() {
var school_name = jQuery('#school-name').text();
var session_var = jQuery('#session').text();
// console.log(session_var);
var button_text_onload =
localStorage.getItem("btnText_"+school_name+"_for_"+session_var);
console.log(button_text_onload);
if (button_text_onload !== null) {
jQuery('#follow-button').html(button_text_onload);
} else {
jQuery('#follow-button').html('Follow');
}
jQuery('#follow-button').click(function() {
// alert (session_var);
// console.log(session_var);
var button_text = jQuery('#follow-button').text();
// alert(button_text);
if (button_text === 'Follow') {
jQuery.ajax({
type: 'POST',
url:
'https://mim-insider.com/wp-content/themes/Divi/follow_school.php',
data: {name : school_name,
email : session_var
},
success: function(result) {
console.log(result);
var key = "btnText_" + school_name +"_for_" +
session_var;
console.log(key);
localStorage.setItem(key, "Unfollow");
jQuery('#follow-button').html('Unfollow');
}});
} else {
jQuery.ajax({
type: 'POST',
url:
'https://mim-insider.com/wp-content/themes/Divi/unfollow_school.php',
data: {name : school_name,
email : session_var,
},
success: function(result) {
console.log(result);
var key = "btnText_" + school_name +"_for_" +
session_var;
console.log(key);
localStorage.setItem(key, "Follow");
jQuery('#follow-button').html("Follow");
}});
}
});
});
follow_school.php
<?php
include_once "includes/db.php";
include_once "includes/functions.php";
$name = $_POST['name'];
$email = $_POST['email'];
$id = get_id($email);
/* for debugging purpose */
if ($id == null) {
var_dump($id);
} else {
echo $id;
}
echo $email;
/* insert operation */
insert_school($id, $name);
?>
functions.php
function get_id($email) {
global $conn;
$sql = "SELECT id FROM member WHERE email = '$email'";
$result = $conn->query($sql);
$row = $result->fetch_assoc();
return $row["id"];
}
function insert_school($id, $name) {
global $conn;
$sql = "INSERT INTO user_schools (user_id, school_name)
VALUES ('$id', '$name')";
$conn->query($sql);
}
NOTE: Here the database connection is perfectly fine, and these codes worked for some pages earlier. But apparently, other pages don't seem to run the code, or to be precise, returns "null" as id. Also, I would like to mention that, the table entries and fields are not null, or unspecified. They are perfectly fine, as I said, it worked for some pages.
Please can anyone guide me, as to what's going wrong here, because after dedicating so much of my time on this, i still am not able to understand the issue.
Thank you.

Codeigniter Ajax Post not working

Hello guys im trying to create a simple voting for comments like and dislike but i want to do that with jquery Ajax so i don't want to refresh the page when someone like it.
And this is my jquery code
$(document).ready(function(){
$(".vote-btn").click(function() {
var voteId = this.id;
var upOrDown = voteId.split('_');
// alert(upOrDown); = provides --> id,name
// var all = 'voteId:'+upOrDown[0]+ ',upOrDown:' +upOrDown[1];
// alert(all);
$.ajax({
type: "POST",
url: "http://localhost/Dropbox/cipr/index.php/demo",
cache: false,
dataType:'json',
data:{'voteId='+upOrDown[0] + '&upOrDown=' +upOrDown[1],
success: function(response){
try{
if(response=='true'){
var newValue = parseInt($("#"+voteId+'_result').text()) + 1;
$("#"+voteId+'_result').html(newValue);
}else{
alert('Sorry Unable to update..');
}
}catch(e) {
alert('Exception while request..');
}
},
error: function(){
alert('Error while request..');
}
});
});
});
this is my Controller code Demo.php
<?php
class Demo extends CI_Controller {
function Demo(){
parent::Controller();
$this->load->model('sygjerimet');
}
public function index(){
$voteId= $this->input->post('voteId');
$upOrDown= $this->input->post('upOrDown');
$status ="false";
$updateRecords = 0;
if($upOrDown=='voteup' || true){
$updateRecords = $this->sygjerimet->updateUpVote($voteId);
}else{
$updateRecords = $this->sygjerimet->updateDownVote($voteId);
}
if($updateRecords>0){
$status = "true";
}
echo $status;
}
And this is my model code sygjerimet.php
<?php
Class Sygjerimet extends CI_Model
{
function shtoSygjerimin()
{
$permbajtja = $this->input->post('idea');
$data = array(
'permbajtja' => $permbajtja
);
$this->db->insert('pr_sygjerimet', $data);
}
function updateDownVote($voteId){
$sql = "UPDATE pr_sygjerimet set vote_down = vote_down+1 WHERE ID =?";
$this->db->query($sql, array($voteId));
return $this->db->affected_rows();
}
function updateUpVote($voteId){
$sql = "UPDATE pr_sygjerimet set vote_up = vote_up+1 WHERE ID =?";
$this->db->query($sql, array($voteId));
return $this->db->affected_rows();
}
}
And this is my view Code
<?php
$query = $this->db->query('SELECT * FROM pr_sygjerimet');
foreach ($query->result() as $row)
{
echo "<div class='sygjerimi'>";
echo htmlspecialchars($row->permbajtja);
if(!$log_in):
echo '<br>';
echo ' <button id="'.$row->ID.'_votedown" class="vote-btn"><i class="fa fa-thumbs-down">'.htmlentities($row->vote_down).'</i></button> ';
echo ' <button id="'.$row->ID.'_voteup" class="vote-btn"><i class="fa fa-thumbs-up">'.htmlentities($row->vote_up).'</i></button> ';
endif;
echo "</div>";
}
?>
That's it guys when i cilck vote it executes this code
alert('Error while request..');
If anyone can help that would be Great :) Thanks
Most likely this is the CI CSRF protection; if you use POST, CI automatically checks the CSRF hidden field and since you are building the ajax post yourself, it's not sending the hidden field so it bags on you.
Check the several $config['csrf_*'] lines in your config/config.php file. You can disable (but I don't recommend this). You can also serialize the form in jQuery and send that, and it should work for you, and keep you a bit more protected from CSRF attacks.
Just to rule this in or out, you can disable the 'csrf_protection' and if it works then, you can enable it again and then change your javascript to serialize the form and use that as your data with your ajax post.
try this
$.ajax({
//pull the toke csrf like this
data:{'<?php echo $this->security->get_csrf_token_name();?>':'<?php echo $this->security->get_csrf_hash();?>'},
});

AJAX request and PHP class functions

How to call a PHP class function from an ajax call
animal.php file
class animal
{
function getName()
{
return "lion";
}
}
Then in my ajax.php file I have an ajax request, need to get values from getName function
How to do that getName() function can I do like this?
<script type=text/javascript>
$.ajax({
type: "POST",
data: {
invoiceno:jobid
},
url: "animal/getName",
beforeSend: function() {
},
dataType: "html",
async: false,
success: function(data) {
result=data;
}
});
</script>
My answer is the same as Surreal Dreams answer, but with the code.
First. Class animal is OK. Leave it like that:
animal.php
<?php
class animal
{
function getName()
{
return "lion";
}
}
Next. Create a new animalHandler.php file.
<?php
require_once 'animal.php';
if(isset( $_POST['invoiceno'] )) {
$myAnimal = new animal();
$result = $myAnimal->getName();
echo $result;
}
Finally. Change your Javascript.
<script type=text/javascript>
$.ajax({
type: "POST",
data: {
invoiceno:jobid
},
url: "animalHandler.php",
dataType: "html",
async: false,
success: function(data) {
result=data;
}
});
</script>
That's is.
You need one additional script, because your animal class can't do anything on its own.
First, in another script file, include animal.php. Then make an object of the animal class - let's call it myAnimal. Then call myAnimal->getName() and echo the results. That will provide the response to your Ajax script.
Use this new script as the target of your Ajax request instead of targeting animal.php.
OOP Currently with php:
ajax.html program(client tier) -> program.php (middle tier) -> class.php (middle tier) -> SQL call or SP (db tier)
OOP Currently with DotNet:
ajax.html program(client tier) -> program.aspx.vb (middle tier) -> class.cls (middle tier) -> SQL call or SP (db tier)
My real-life solution:
Do OOA, do not OOP.
So, I have one file per table -as a class- with their proper ajax calls, and select the respective ajax call with a POST parameter (i.e. mode).
/* mytable.php */
<?
session_start();
header("Content-Type: text/html; charset=iso-8859-1");
$cn=mysql_connect ($_server, $_user, $_pass) or die (mysql_error());
mysql_select_db ($_bd);
mysql_set_charset('utf8');
//add
if($_POST["mode"]=="add") {
$cadena="insert into mytable values(NULL,'".$_POST['txtmytablename']."')";
$rs=mysql_query($cadena,$cn) or die(mysql_error().' : '.$cadena);
};
//modify
if($_POST["mode"]=="modify") {
$cadena="update mytable set name='".$_POST['txtmytablename']."' where code='".$_POST['txtmytablecode']."'";
$rs=mysql_query($cadena,$cn) or die(mysql_error().' : '.$cadena);
};
//erase
if($_POST["mode"]=="erase") {
$cadena="delete from mytable where code='".$_POST['txtmytablecode']."'";
$rs=mysql_query($cadena,$cn) or die(mysql_error().' : '.$cadena);
};
// comma delimited file
if($_POST["mode"]=="get") {
$rpta="";
$cadena="select * from mytable where name like '%".$_POST['txtmytablename']."%'";
$rs=mysql_query($cadena,$cn) or die(mysql_error().' : '.$cadena);
while($row = mysql_fetch_array($rs)) {
$rowCount = mysql_num_fields($rs);
for ($columna = 0; $columna < $rowCount; $columna++) {
$rpta.=str_replace($row[$columna],",","").",";
}
$rpta.=$row[$columna]."\r\n";
}
echo $rpta;
};
//report
if($_POST["mode"]=="report_a") {
$cadena="select * from mytable where name like '%".$_POST['txtmytablename']."%'";
$rs=mysql_query($cadena,$cn) or die(mysql_error().' : '.$cadena);
while ($row=mysql_fetch_array($rs)) {
echo $row['code']." ".$row['name']."<br/>"; // colud be a json, html
};
};
//json
if($_POST["mode"]=="json_a") {
$cadena="select * from mytable where name like '%".$_POST['txtmytablename']."%'";
$rs=mysql_query($cadena,$cn) or die(mysql_error().' : '.$cadena);
$result = array();
while ($row=mysql_fetch_array($rs)) {
array_push($result, array("id"=>$row['code'],"value" => $row['name']));
};
echo json_encode($result);
};
?>
Can you please mention which are you using any Framework?
You method is correct but I want to mention two things over here. First try your URL from the browser and check if its working correctly. Secondly don't use return, in *success: function(data) * data will contain only the output. so use Echo rather then return
For what it is worth, I have used a PHP proxy file that accepts an object as a post -- I will post it here. It works by providing class name, method name, parameters (as an array) and the return type. This is limited as well to only execute classes specified and a limited set of content types to return.
<?php
// =======================================================================
$allowedClasses = array("lnk","objects"); // allowed classes here
// =======================================================================
$raw = file_get_contents("php://input"); // get the complete POST
if($raw) {
$data = json_decode($raw);
if(is_object($data)) {
$class = $data->class; // class: String - the name of the class (filename must = classname) and file must be in the include path
$method = $data->method; // method: String - the name of the function within the class (method)
#$params = $data->params; // params: Array - optional - an array of parameter values in the order the function expects them
#$type = $data->returntype; // returntype: String - optional - return data type, default: json || values can be: json, text, html
// set type to json if not specified
if(!$type) {
$type = "json";
}
// set params to empty array if not specified
if(!$params) {
$params = array();
}
// check that the specified class is in the allowed classes array
if(!in_array($class,$allowedClasses)) {
die("Class " . $class . " is unavailable.");
}
$classFile = $class . ".php";
// check that the classfile exists
if(stream_resolve_include_path($classFile)) {
include $class . ".php";
} else {
die("Class file " . $classFile . " not found.");
}
$v = new $class;
// check that the function exists within the class
if(!method_exists($v, $method)) {
die("Method " . $method . " not found on class " . $class . ".");
}
// execute the function with the provided parameters
$cl = call_user_func_array(array($v,$method), $params );
// return the results with the content type based on the $type parameter
if($type == "json") {
header("Content-Type:application/json");
echo json_encode($cl);
exit();
}
if($type == "html") {
header("Content-Type:text/html");
echo $cl;
exit();
}
if($type == "text") {
header("Content-Type:text/plain");
echo $cl;
exit();
}
}
else {
die("Invalid request.");
exit();
}
} else {
die("Nothing posted");
exit();
}
?>
To call this from jQuery you would then do:
var req = {};
var params = [];
params.push("param1");
params.push("param2");
req.class="MyClassName";
req.method = "MyMethodName";
req.params = params;
var request = $.ajax({
url: "proxy.php",
type: "POST",
data: JSON.stringify(req),
processData: false,
dataType: "json"
});
Try this:
Updated Ajax:
$("#submit").on('click', (function(e){
var postURL = "../Controller/Controller.php?action=create";
$.ajax({
type: "POST",
url: postURL,
data: $('form#data-form').serialize(),
success: function(data){
//
}
});
e.preventDefault();
});
Update Contoller:
<?php
require_once "../Model/Model.php";
require_once "../View/CRUD.php";
class Controller
{
function create(){
$nama = $_POST["nama"];
$msisdn = $_POST["msisdn"];
$sms = $_POST["sms"];
insertData($nama, $msisdn, $sms);
}
}
if(!empty($_POST) && isset($_GET['action']) && $_GET['action'] == ''create) {
$object = new Controller();
$object->create();
}
?>
For every ajax request add two data, one is class name and other is function name
create php page as follows
<?php
require_once 'siteController.php';
if(isset($_POST['class']))
{
$function = $_POST['function'];
$className = $_POST['class'];
// echo $function;
$class = new $className();
$result = $class->$function();
if(is_array($result))
{
print_r($result);
}
elseif(is_string($result ) && is_array(json_decode($result , true)))
{
print_r(json_decode($string, true));
}
else
{
echo $result;
}
}
?>
Ajax request is follows
$.ajax({
url: './controller/phpProcess.php',
type: 'POST',
data: {class: 'siteController',function:'clientLogin'},
success:function(data){
alert(data);
}
});
Class is follows
class siteController
{
function clientLogin()
{
return "lion";
}
}
I think that woud be a sleek workaround to call a static PHP method via AJAX which will also work in larger applications:
ajax_handler.php
<?php
// Include the class you want to call a method from
echo (new ReflectionMethod($_POST["className"], $_POST["methodName"]))->invoke(null, $_POST["parameters"] ? $_POST["parameters"] : null);
some.js
function callPhpMethod(className, methodName, successCallback, parameters = [ ]) {
$.ajax({
type: 'POST',
url: 'ajax_handler.php',
data: {
className: className,
methodName: methodName,
parameters: parameters
},
success: successCallback,
error: xhr => console.error(xhr.responseText)
});
}
Greetings ^^

Zend Ajax can't delete

I have a table named state with columns state_id, state_name. Currently I can add new states and edit them, but I can't delete states. What might be wrong with my code?
{title:"Actions",template:'<a class="left" onclick="javascript:openEditStatePopup(this);">Edit</a>' +
'<a class="right" onclick="javascript:deleteState(this);">Delete</a>'
,width:120,sortable:false}
This snippet is the view code, and when I click the link, it executes the following JavaScript:
function deleteState(element)
{
var countryDetail = {};
var GriddataItem = $("#state_grid").data("kendoGrid").dataItem($(element).closest("tr"));
countryDetail.state_id =GriddataItem.state_id;
countryDetail.state_name = GriddataItem.state_name;
// alert(countryDetail.state_id);
$.ajax({
url:"<?= $this->baseUrl('admin/state/delete')?>",
data: {state_id : countryDetail.state_id},
dataType: "json",
type: "POST",
success: function(){
alert('success');
},
failure:function(){
alert('not working');
}
});
}
When I echo alert(countryDetail.state_id) before the $.ajax call, I can get the correct state id.
My delete controller is:
public function deleteAction()
{
$state = $this->_request->_getPost('state_id');
$stateMapper = new Application_Model_Mapper_StateMapper();
$stateMapper->delete($state);
}
and the model mapper for deleting is:
public function delete(Application_Model_State $state)
{
$data = $state->toArray();
$adapter = $this->getDbTable()->getAdapter()->delete(array('state_id=?'=>$data['state_id']));
}
Hi you need to write deleteAction as following
public function deleteAction()
{
$state = $this->_getParam('state_id');
$stateMapper = new Application_Model_Mapper_StateMapper();
$stateId = $stateMapper->delete($state);
$this->_helper->json(array('success'=>1));
}
in your controller action deleteAction() you are getting POST param 'state_id'
$state = $this->_request->_getPost('state_id');
$stateMapper = new Application_Model_Mapper_StateMapper();
$stateMapper->delete($state);
and you are passing that $state in the $stateMapper->delete($state); function
in your model class function public function delete(Application_Model_State $state) definition you are passing State model object not and state id, so you should change this to
public function delete($state_id)
{
$adapter = $this->getDbTable()->getAdapter()->delete(array('state_id=?'=>$state_id));
}
Then it should work...
Another thing I have not seen
failure:function(){
alert('not working');
}
Rather it is
error:function(){
alert('not working');
}

PHP Function can't read jquery POST data?

Alright so I have this function
<?php
/**
* #author Mitchell A. Murphy
* #copyright 2011
*/
include ('func_lib.php');
connect();
echo (check($_POST['input']) ? 'true' : 'false');
function check($args)
{
$args = strtolower($args);
$checkemail = "/^[a-z0-9]+([_\\.-][a-z0-9]+)*#([a-z0-9]+([\.-][a-z0-9]+)*)+\\.[a-z]{2,}$/i";
if (preg_match($checkemail, $args))
{
//logic for email argument
$sql = "SELECT * FROM `users` WHERE `email`='" . $args . "'";
$res = mysql_query($sql) or die(mysql_error());
echo "type=email:";
if (mysql_num_rows($res) > 0)
{
return true;
} else
{
return false;
}
} else
{
//logic for username argument
$sql = "SELECT * FROM `users` WHERE `username`='" . $args . "'";
$res = mysql_query($sql) or die(mysql_error());
echo "type=username:";
if (mysql_num_rows($res) > 0)
{
return true;
} else
{
return false;
}
}
}
?>
The function should be accessed by this jquery script:
$('form.register .submit').click(validateRegister);
function validateRegister() {
//Variables
var emailExists = false;
var userExists = false;
var $error = "";
//Executes functions
email();
function email() {
var $error = $('#email .error');
var input = $('#email input').val();
var emailRE = /^.*#.+\..{2,5}$/;
if (input.match(emailRE)) {
$error
.html('<div>Proper Email Format: <span>Hello#Yoursite.com</span></div>')
.animate({
'left': '-130px',
'opacity': '0'
});
//Checks for Existing Email
function checkExisting_email() {
$.ajax({
type: 'POST',
url: 'includes/checkExist.php',
data: input,
statusCode: {
404: function () {
alert('page not found');
}
},
success: function (data) {
alert(data);
},
error: function () {
alert("error bro");
}
});
}
emailExists = checkExisting_email();
//If it exists
if (emailExists) {
alert("This email already exists!");
} else if (emailExists == false) {
alert("Email doesnt exist!");
}
} else {
//Email doesn't match
$error
.html('<div>Proper Email Format: <span>Hello#Yoursite.com</span></div>')
.animate({
'left': '-150px',
'opacity': '1'
});
}
}
return false;
}
But for some reason the script (js) isn't sending any data? if so, how do i reference it. I am the backend developer but the designer who did the javascript left me to fix this. I know the php works because I made a test form to send the data with this html markup:
<form action="includes/checkExist.php" method="post">
<input type="text" name="input" />
<input type="submit" name="submit" />
</form>
And that works...so why is the input from jquery returning as NULL?
See that checkExisting_email() don't return anything, so emailExists = checkExisting_email(); will not set emailExists. This data will only be provided on the callback function, which today only display the result on an alert().
To make things easier, use jQuery ajax validation field remote. Check the documentation and sample.
You need to pass in a key/value pair for the "data", not just the value.
As is, your form is going to be posted with a querystring looking like this:
target.php?asdf#hotmail.com
it should be:
data: { input: input },
This will set the querystring to look like:
target.php?input=asdf#hotmail.com
Also, since you are getting the value out of an element by ID, you dont need to specify the input tag.
var input = $('#email').val();

Categories