I have a form that submits an ajax call to the controller file below which has a function defined in another file "processes.php" [that I've included]. The challenge is receiving the json response; the browser expects to find it in the controller yet it's generated within the function. How can I retrieve the response from the function and make it readable from the controller [outside its functions] so that the response can be read by the browser?
controller.php
<?php
session_start();
$_SESSION['postdata'] = $_POST;
require "constants.php";
$file = $_SESSION["Form"].".php";
require $file;
if( isset($_POST["Save"]) ){
save_record($connection);
}
process.php
<?php
$_POST = $_SESSION['postdata'];
function save_record($connection){
$errors = array(); // array to hold validation errors
$data = array(); // array to pass back data
$name = mysqli_real_escape_string($connection, $_POST["name"]);
$strQuery = "INSERT INTO names (name) VALUES ('$name')";
$result = mysqli_query($connection, $strQuery); //or exit("Error in query execution attempt!");
if($result){
$data['success'] = true;
$data['message'] = 'Success!';
}
else{
$errors['errorinexecute'] = "Error in query execution attempt!";
}
mysqli_close($connection);
unset($_SESSION["postdata"]);
if ( ! empty($errors)) {
// if there are items in our errors array, return those errors
$data['success'] = false;
$data['errors'] = $errors;
}
else{
$data['success'] = true;
$data['errors'] = $errors;
}
// return all our data to an AJAX call
echo json_encode($data);
}
?>
You can't use:
if( isset($_POST["Save"]) ){
save_record($connection);
}
when doing AJAX, so what I did is pass the button id into the JavaScript function like so:
onclick="saveInfo(this.id)"
The button id shows whether it's a "Delete", "Save", "Edit" request and so on and then from there the PHP file can read like this:
if( $buttonId == "Save" ){
save_record($connection);
}
Related
I am trying to get pre set session variables through ajax and display in my modal. its like a cart. But when i try to get them there is no result at all when i read the ajax result from chrome inspect network or the modal. below is my code. what am i doing wrong here?
<script>
$("#cart-button").click(function(){
$.ajax({
url: "includes/cart-read.php",
success: function(data){
console.log(data);
alert(data);
$('#modal-body').empty().append(''+data+'');
}
});
});
</script>
and in cart-read.php
if(isset($_SESSION['dices'])){
foreach ($_SESSION['dices'] as $dice){
$msg = $dice;
echo json_encode($msg);
}
}
session dices is an array with simple numbers. such as 4, 5, 6.
Make sure you have the following things in your code
Check if you have added session_start(); below after
Try putting an else case to your session check,
Try using an array to store and display the results.
<?php
session_start();
$result = array();
$msg = array();
if(isset($_SESSION['dices'])){
foreach ($_SESSION['dices'] as $dice){
array_push($msg,$dice);
}
if(sizeof($msg) > 0)
{
$result['status'] = true;
$result['message'] = $msg;
}
else
{
$result['status'] = false;
$result['message'] = 'No values';
}
}
else
{
$result['status'] = false;
$result['message'] = 'Session not set';
}
echo json_encode($result);
?>
I came across weird problem with my site only after uploaded it to the live server. In localhost I've no issue with these.
The problem is for login and register function. Let me talk about login first.
I keyed in the credentials and found that the page is called in the f12 network tab.However that page doesn't retrieve any data! So I put aside this jquery/ajax for a while and manually checked the php pages if they return any data but still they don't.
Now the flow like this:
login form filled up by user-> ajax request from php script-> php request from class file and return to ajax -> ajax give access to admin dashboard.
Now as I told you, I excluded ajax request and only checked with php and class file. Again it doesn't return anything from the class file to the php script though I only echoed "something"! Its not even go through any function!
Then I omitted, class file, checked the php script with ajax file.I only echo "wexckdsewndxw" and changed tha datatype in ajax to 'text'..still it doesn't get any value!
So in conclusion, data between pages are not passed at all! SO I suspect its something to do with crossDomain issue as mentioned here:
How does Access-Control-Allow-Origin header work?
But not sure how this works and how I should alter my code.
My code for reference:
login-user.js
/*login user*/
<!--login form submission starts-->
$("document").ready(function(){
$("#login-user").submit(function(){
var data = {
"action": "test"
};
data = $(this).serialize() + "&" + $.param(data);
$.ajax({
type: "POST",
dataType: "json",
url: "login-this-user.php",
data: data,
success: function(data) {
alert(data);
console.log(data);
var i;
for (i = 0; i < data.length; i++)
{
console.log(data[i].email);
console.log(data[i].activate);
console.log(data[i].status);
if($.trim(data[i].status)=='0')
{
//alert("not verified");
$('.invalid-popup-link').trigger('click');
}else
{
//alert("verified");
location.replace("admin/dashboard.php");
}
}//end for
},
error: function( jqXhr, textStatus, errorThrown ){
console.log( errorThrown );
}
});
return false;
});
});
<!--login form submission ends-->
login-this-user.php
<?php
session_start();
include('config.php');
include('class.login.php');
$return = $_POST;
//$return ='{"email":"admin#gmail.com","pass":"admin","action":"test"}';
//$return['json']= json_encode($return);
//
//below code to store in database
$data = json_decode($return, true);
$login = new checkLogin();
$status = $login->checkLogin2($data["email"],$data["pass"]);
$_SESSION['user_id']=$status;
$login = new checkLogin();
$profile = $login->check_profile($data["email"]);
$activated_id=array();
foreach($profile as $k=>$v){
array_push($activated_id,array("email"=>$v['email'],"activate"=>$v['activate'],"status"=>'0'));
$_SESSION['email'] = $v['email'];
$_SESSION['activated_id'] = $v['activate'];
}
//header('Content-Type: application/json');
echo json_encode($activated_id);
?>
class
<?php
session_start();
?>
<?php
class checkLogin
{
public $email;
public $password;
public $userId;
public $salt;
public $hpass;
public function __construct()
{
}
public function checkLogin2($param1, $param2)
{
$this->email=$param1;
$this->password=$param2;
$sql = "SELECT * FROM authsessions WHERE email='{$this->email}'";
$statement = connection::$pdo->prepare($sql);
$statement->execute();
while( $row = $statement->fetch()) {
$salt=$row['salt'];
$hashAndSalt=$row['hashpword'];
$user_id=$row['UUID'];
}
if (password_verify($this->password, $hashAndSalt)==true) {
$status = "verified";
$_SESSION['user_id'] =$user_id;
$_SESSION['logged_in']=1;
}else
{
$status = "not verified";
$_SESSION['user_id'] =0;
$_SESSION['logged_in']=0;
}
return $_SESSION['user_id'] = 1;
}
public function check_profile($param)
{
$this->email = $param;
$sql="SELECT * FROM authsessions WHERE email = '{$this->email}'";
$stmt =connection::$pdo->prepare($sql);
$stmt->execute();
$profile=array();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$profile[] = $row;
}
return $profile;
}
}
?>
I had developed a event management system using javascript php and mysql. It works perfectly in plain php but now I need to migrate it into codeigniter and need some advice on how to pass the data from js to php while in codeigniter.
My front end java script function is like this
// event creating
dp.onTimeRangeSelected = function (args) {
var name = prompt("New event name:", "Event");
dp.clearSelection();
if (!name) return;
var e = new DayPilot.Event({
start: args.start,
end: args.end,
id: DayPilot.guid(),
resource: args.resource, //Change to classroom name
text: name //Change to event name
});
dp.events.add(e);
args.text = name;
DayPilot.request(
"backend_create.php",
function(req) { // success
var response = eval("(" + req.responseText + ")");
if (response && response.result) {
dp.message("Created: " + response.message);
}
},
args,
function(req) { // error
dp.message("Saving failed");
}
);
};
The php file handling the create function is like this
<?php
require_once '_db.php';
$insert = "INSERT INTO events (name, start, end, resource) VALUES (:name, :start, :end, :resource)";
$stmt = $db->prepare($insert);
$stmt->bindParam(':start', $start);
$stmt->bindParam(':end', $end);
$stmt->bindParam(':name', $name);
$stmt->bindParam(':resource', $resource);
$received = json_decode(file_get_contents('php://input'));
$start = $received->start;
$end = $received->end;
$resource = $received->resource;
$name = $received->text;
$stmt->execute();
class Result {}
$response = new Result();
$response->result = 'OK';
$response->message = 'Created with id: '.$db->lastInsertId();
echo json_encode($response);
?>
Now on migrating to codeignitor I moved to segregated the backend_create.php file into model and controller and it looks like this.
The controller part
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class TimecalCon extends CI_Controller {
function __construct()
{
parent::__construct();
$this->load->model("Timecal_model");
}
public function insert()
{
$received = json_decode(file_get_contents('php://input'));
$start = $received->start;
$end = $received->end;
$resource = $received->resource;
$name = $received->text;
$this->Timecal_model->InsertDetails($name, $start, $end, $resource);
}
The Model
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Timecal_model extends CI_Model {
function __construct()
{
// Call the Model constructor
parent::__construct();
}
function InsertDetails($name, $start, $end, $resource)
{
$insert = "INSERT INTO events (name, start, end, resource) VALUES (:name, :start, :end, :resource) ";
$query = $db->prepare($insert);
$stmt->bindParam(':start', $start);
$stmt->bindParam(':end', $end);
$stmt->bindParam(':name', $name);
$stmt->bindParam(':resource', $resource);
$stmt->execute();
class Result {}
$response = new Result();
$response->result = 'OK';
$response->message = 'Created with id: '.$db->lastInsertId();
return json_encode($response);
}
The issue is when I change the javascript in the view page and use it like this
.....
DayPilot.request(
"TimecalCon/insert", .......
The functionality breaks and I am unable to insert events into the db. How should I be passing the data from js to the controller in this condition?
We can send the value from javascript to controller using Ajax. I have some code of mine which may help you.
function deleteEmp(empid){
var base_url = '<?php echo site_url(); ?>';
var r=confirm("Do You Really Want to Delete? ")
if (r==true)
{
objPost= new Object();
objPost.empid = empid;
$.ajax({
url:"employee_registration/deleteEmp?empid="+empid,
type:"POST",
data:objPost,
beforeSend:function(data){
},
error:function(data){
},
success:function(data){
alert(data);
result=JSON.parse(data);
alert(result);
if(result.status == 'success'){
alert('Deleted Successfully ');
window.location.reload();
return false;
}
}
});
}else{
return false;
}
}
As you can see I have pass the empid from my view to controller using ajax which gives me result back in variable. Which in this case is json.
Try this
DayPilot.request("<?php echo base_url().'TimecalCon/insert';?>",...)
You'll have to add "url" in "autoload.php" under config folder, then check if the url being loaded is the right one if not. Try modifying base_url() a bit like adding or removing the "index.php" part in the url.
Hope This helps
Hi I am developing an app in phonegap, where I am getting a particular value from server by connecting php file the value I need to pass is a string value 'pmnno'suppose whose value is '2' I need to get the value of '2' in column name 'personalnumber'.. So I am giving my code below
var jsonData;
$.ajax({
type: 'GET',
url: 'http://xxxx.com/app/get_pday1_number.php',
data: { pmnno: '2' },
dataType: 'html',
success: function (response) {
jsonData = response;
alert(jsonData);
}
});
php code
<?php
// array for JSON response
$response = array();
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
// check for post data
if (isset($_GET["pone"]))
{
$pone = $_GET['pone'];
// get a product from products table
$result = mysql_query("SELECT *FROM pdaynew WHERE pone = $pone");
if (!empty($result)) {
// check for empty result
if (mysql_num_rows($result) > 0) {
$result = mysql_fetch_array($result);
$product = array();
$product["pid"] = $result["pid"];
$product["pone"] = $result["pone"];
$product["personaldayone"] = $result["personaldayone"];
$product["created_at"] = $result["created_at"];
$product["updated_at"] = $result["updated_at"];
// success
$response["success"] = 1;
// user node
$response["product"] = array();
array_push($response["product"], $product);
// echoing JSON response
echo json_encode($response);
} else {
// no product found
$response["success"] = 0;
$response["message"] = "No product found";
// echo no users JSON
echo json_encode($response);
}
} else {
// no product found
$response["success"] = 0;
$response["message"] = "No product found";
// echo no users JSON
echo json_encode($response);
}
} else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
// echoing JSON response
echo json_encode($response);
}
?>
I am getting a success mesage that means connection is succesful but ineed the value of '2' in column 'personalnumber' for that where I need to add that code..If anyone knows pls help me...
Instead of using * use personaldayone:
$result = mysql_query("SELECT personaldayone FROM pdaynew WHERE pone = $pone");
I am trying to pass user's info from mysql to the webpage, if the user has logged in but can't get it to work. If I put a wrong email or password it will show the error message but if the credentials are ok it would do anything...
on php file:
$sql = "SELECT * FROM users WHERE email='$l_email' AND password='$l_password'";
$query = mysql_query($sql) or die ('Error: ' . mysql_error());
$num_rows = mysql_num_rows($query);
if($num_rows < 1)
{
echo "You have entered a wrong email or password!";
}
else {
$memberInfo = array();
while( $row = mysql_fetch_array( $query ) )
{
$memberInfo[] = $row;
}
return $memberInfo;
echo json_encode( $memberInfo );
//echo "1";
}
on js file:
$.post("./includes/checkOut.php",{ l_email1: l_email, l_password1: l_password },
function(data) {
if(data=='1')
$("#checkOut_form")[0].reset();
$("#login_returnmessage").html("");
$("#memberInfo").hide("");
var memberInfo = jQuery.parseJSON(memberInfo);
for( var i in memberInfo )
{
var f_name = memberInfo[i].f_name;
var l_name = memberInfo[i].l_name;
var phone = memberInfo[i].phone;
}
$("#loggedinInfo").show("");
$('#_f_name').val(f_name);
$('#_l_name').val(l_name);
$('#_email').val(l_email);
$('#_phone').val(phone);
}
$("#login_returnmessage").html(data);
});
If you use return outside a function then it terminates the script at that point. This is exactly what you're doing here:
return $memberInfo;
echo json_encode( $memberInfo );
//echo "1";
You need to remove the return statement.
You should also add a Content-type: header to the response to tell the browser to expect JSON:
header('Content-type:application/json');
echo json_encode( $memberInfo );
Your Javascript code is checking the response for the value 1, which you're not sending, so the code that updates the display won't execute.
Lastly:
don't store passwords unencrypted - use password_hash()
don't use mysql as it's deprecated - use mysqli or PDO
ensure you escape your inputs before passing them to the database (or better, use prepared statements (not supported by mysql_*()).