PHP (Codeigniter) and ajax help - php

I am trying to create a twitter like application in which the user enters some data into a form and through using ajax (jquery library) the users see theirs submission in realtime go to the top of the all the other data.
The way it works is the user submits the form and the data gets submitted to the database, I also want to add teh data to the list of data using ajax.
My problem is I can only access the data the PHP method creates from the ajax request if I echo $var; in my php method, this doesn't look correct to me can some tell me what I am doing wrong please?
public function feed() {
$this->load->library('form_validation');
$this->load->helper('dates');
$data['feed'] = $this->f->get_feed_by_employer($this->session->userdata('employer_id'));
$this->form_validation->set_error_delimiters('<div class="error">', '</div>');
$this->form_validation->set_rules('content', 'content', 'required|trim|max_length[140]');
$this->form_validation->set_rules('retrain', 'retrain position', 'trim|max_length[1]');
if ($this->form_validation->run() == FALSE)
{
echo validation_errors('<div class="error">', '</div>');
$this->template->build('employer/feed', $data);
}
else
{
$insert = array(
'content' => $this->input->post('content'),
'retrain' => $this->input->post('retrain'),
'created_at' => time(),
'employers_id' => $this->session->userdata('employer_id')
);
if($this->f->insert($insert)) {
echo $insert['content'];
}
}
}
and the jquery
$('#employer_feed').submit(function(){
$.ajax({
url: '/employer/feed',
data: $('#employer_feed').serialize(),
type: 'POST',
success:function(html) {
$('#feed').append('<div class="feed_item">'+html+'</div>');
}
});
return false;
});

There's no problem of using echo when dealing with ajax request, actually it's the way to go. Also you may use echo json_encode($output); depending on your ajax request type.
Check this article, using is_ajax to know when to echo and when to load your views is a clean way!
so create a file is-ajax_helper.php in application/helpers/ folder:
<?php
function is_ajax(){
return (isset($_SERVER['HTTP_X_REQUESTED_WITH'])
&& strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest');
}
And in your config/autoload.php:
$autoload['helper'] = array('is-ajax');
And just check if it's an ajax call or not!
EDIT:
Since Codeigniter 2.0 is officially out and plugins are now replaced with helpers, I have updated my Answer.

Nowadays, you can just use $this->input->is_ajax_request(), available in the input class, to achieve the same results as with the hand-made helper by #ifaour.

Related

PHP calling function with parameters by clicking on HTML div

I am trying to make a delete button which I'll be able to delete some user from my database but main thing how to call PHP function with clicking on some div etc..
<div class="cross" onclick='<?php deleteUser("Nickname")?>'>X</div>
<?php
function deleteUser($username) {
//... code
}
?>
Html can't directly call php, it can do a separate call to load the same page, with the action.
<?php
function deleteUser($username){}
if($_GET['action'] == "delete")
{
deleteUser($_GET['username']);
}
?>
<a class="cross" href='?action=delete&username=NickName'>X</a>
The reason for this is because PHP runs on the server, BEFORE anything is sent to the browser. So it requires another page load to run the function by clicking something. It is possible to use javascript and AJAX calls to send a call to a php script without reloading the main page. Just look into Jquery's post or ajax features.
You cannot call a PHP function that resides on the server by just clicking on a div that exists on the client browser.
You need to trigger a Javascript event (using e.g. jQuery), that will call a function on the server (e.g. through AJAX), that after checking the parameters are correct and the user has the right of calling it will do what you seek.
There are ready-made frameworks that would allow you to do that.
Otherwise (after including jQuery in your HTML page) you can do something like,
<div class="cross" id="deleteUserButton" data-user="nickname">X</div>
<script type="text/javascript">
$('#deleteUserButton').on('click', function() {
let nick = $(this).attr('data-user');
$.post('/services/delete.php',
{
cmd: 'delete',
user: nick
}).then( reply => {
if (reply.status === 'OK') {
alert("User deleted");
}
});
<?php
$cmd = $_POST['cmd'];
switch($cmd) {
case 'delete':
$user = $_POST['user'];
if (deleteUser($user)) {
$reply = [ 'status' => 'OK' ];
} else {
$reply = [ 'status' => 'failure', 'message' => 'Doh!' ];
}
break;
...
header('Content-Type: application/json;charset=UTF-8');
print json_encode($reply);
exit();

Calling php function with ajax and passing return value to div

I have a function that adds social buttons to my blog posts , but once i load more posts using ajax I cant figure out how can I call add_social_buttons() and pass the data to div.
I'm not really familiar with ajax , i tried this method :
$.ajax({
type:"POST",
url:"functions.php",
data: "social_sharing_buttons()",
success: function(data){
$('.pp').html(data);
}
but it seems that it tries to invoke some totally other function Fatal error: Call to undefined function add_action().
As far as I am aware, you can't. What you can do is have a handler file for your classes, so for example say we have this PHP class,
<?php
class Car {
function getCarType() {
return "Super Car";
}
}
?>
Then in your handler file,
<?php
require_once 'Car.php';
if(isset($_POST['getCarType'])) {
$car = new Car();
$result = $car->getCarType();
echo $result;
}
?>
You'd post your AJAX request to the handler, you could make specific handlers for each request or you could have a generic AJAX handler, however that file could get quite big and hard to maintain.
In your case you'd have in that data,
"getSocialButtons" : true
Then in your AJAX handler file,
if (isset($_POST['getSocialButtons'])) {
// Echo your function here.
}
Then you'd echo out the function within that if statement and using the success callback in your AJAX request do something like this.
document.getElementById("yourDivId").innerHTML = data
That is assuming you're using an ID. Adjust the JS function to suit you.
Try to call that function social_sharing_buttons() like this in function.php:
$.ajax({
type:"POST",
url:"functions.php",
data: {action: 'add'},
success: function(data){
$('.pp').html(data);
}
in functions.php
if(isset($_POST['action']) && !empty($_POST['action'])) {
if($_POST['action'] == 'add') {
echo social_sharing_buttons();
}
}

Posting to CakePHP controller using jquery ajax

I want to post data to a controller in CakePHP, but posting with JQuery always results in"POST http//localhost/SA/myController/editUserData/1 400 (Bad Request)" error and I can't figure out why.
In my view I have the following method, that posts the data to the controller page
$scope.saveUser = function() {
$.ajax({
type: 'POST',
url: '<?php echo Router::url(array(
'controller' => 'myController',
'action' => 'editUserData',
0 => $userInfo['user']['id'],));?>',
data: { email: 'cabraham#delhi.k12'},//"my edited data for example"
success: function (data) {
alert(data);
}
});
My controller method looks like this:
public function editUserData($id) {
if($this->request->is('post') || $this->request->is('put')) {
$this->AcsaUser->save($this->request->data('email'));//edit and save the new data
echo 'ok';
}
}
Any ideas??
Two things that may be throwing it.
(1) Cake's built-in security - so exempt the method from it:
In AppController.php
public function beforeFilter() {
$this->Security->unlockedActions = array('editUserData')
}
(2) Decide how you want your editUserData method to render the view, if you're echo'ing out an 'ok' it will still pull in the default layout and look for an editUserData.ctp in the view (and cause an error if it doesn't find the file), so
To not render anything, ie a .ctp view file and the default layout.. in the editUserData($id), add
$this->autoRender = false;
To only render the view file and not the layout:
$this->autoLayout = false;
......Then lastly I wound just add this parameter in the ajax call :
dataType : 'html' // (or JSON?)

Sending data with AJAX to a PHP file and using that data to run a PHP script

I'm currently trying to make live form validation with PHP and AJAX. So basically - I need to send the value of a field through AJAX to a PHP script(I can do that) and then I need to run a function inside that PHP file with the data I sent. How can I do that?
JQuery:
$.ajax({
type: 'POST',
url: 'validate.php',
data: 'user=' + t.value, //(t.value = this.value),
cache: false,
success: function(data) {
someId.html(data);
}
});
Validate.php:
// Now I need to use the "user" value I sent in this function, how can I do this?
function check_user($user) {
//process the data
}
If I don't use functions and just raw php in validate.php the data gets sent and the code inside it executed and everything works as I like, but if I add every feature I want things get very messy so I prefer using separate functions.
I removed a lot of code that was not relevant to make it short.
1) This doesn't look nice
data: 'user=' + t.value, //(t.value = this.value),
This is nice
data: {user: t.value},
2) Use $_POST
function check_user($user) {
//process the data
}
check_user($_POST['user'])
You just have to call the function inside your file.
if(isset($_REQUEST['user'])){
check_user($_REQUEST['user']);
}
In your validate.php you will receive classic POST request. You can easily call the function depending on which variable you are testing, like this:
<?php
if (isset($_POST['user'])) {
$result = check_user($_POST['user']);
}
elseif (isset($_POST['email'])) {
$result = check_email($_POST['email']);
}
elseif (...) {
// ...
}
// returning validation result as JSON
echo json_encode(array("result" => $result));
exit();
function check_user($user) {
//process the data
return true; // or flase
}
function check_email($email) {
//process the data
return true; // or false
}
// ...
?>
The data is send in the $_POST global variable. You can access it when calling the check_user function:
check_user($_POST['user']);
If you do this however remember to check the field value, whether no mallicious content has been sent inside it.
Here's how I do it
Jquery Request
$.ajax({
type: 'POST',
url: "ajax/transferstation-lookup.php",
data: {
'supplier': $("select#usedsupplier").val(),
'csl': $("#csl").val()
},
success: function(data){
if (data["queryresult"]==true) {
//add returned html to page
$("#destinationtd").html(data["returnedhtml"]);
} else {
jAlert('No waste destinations found for this supplier please select a different supplier', 'NO WASTE DESTINATIONS FOR SUPPLIER', function(result){ return false; });
}
},
dataType: 'json'
});
PHP Page
Just takes the 2 input
$supplier = mysqli_real_escape_string($db->mysqli,$_POST["supplier"]);
$clientservicelevel = mysqli_real_escape_string($db->mysqli,$_POST["csl"]);
Runs them through a query. Now in my case I just return raw html stored inside a json array with a check flag saying query has been successful or failed like this
$messages = array("queryresult"=>true,"returnedhtml"=>$html);
echo json_encode($messages); //encode and send message back to javascript
If you look back at my initial javascript you'll see I have conditionals on queryresult and then just spit out the raw html back into a div you can do whatever you need with it though.

How to implement jquery and CodeIgniter validation library together?

I want to create a registration form where I want to use jquery and also the CI validation library.
How can I do this? Upon submitting the form, I want the control to go to the validation library using jquery and return the response. Then, if all is well, I want the "form is submitted" message to be displayed on that page itself.
Edit:
here are my codes.
VIEW
<?php $this->load->view('template/header'); ?>
<div id="add_form">
<h2>Add New Category</h2>
<?php echo form_open('abc/abc_category_controller/add_new_category'); ?>
<?php
$category_data = array(
'name' => 'category_name',
'id' => 'category_name',
'value' => set_value('category_name'),
'maxlength' => '15'
);
$unit_data = array(
'name' => 'unit',
'id' => 'unit',
'value' => set_value('unit'),
'maxlength' => '10'
);
?>
<p><label for="name">Name: </label><?php echo form_input($category_data); ?></p>
<p><label for="unit">Unit: </label><?php echo form_input($unit_data); ?></p>
<p><?php echo form_submit('submit', 'Submit','id="submit"'); ?></p>
<?php echo form_close(); ?>
<?php echo validation_errors('<p class="error">'); ?>
</div><!--end add new category-form-->
<div id="success_msg">
</div>
<?php $this->load->view('template/footer') ?>
Controller- add_new_category
<?php
class Stocks_category_controller extends CI_Controller{
function add_new_category()
{
//$this->load->helper('form');
$this->load->library('form_validation');
$data['title'] = 'Add a new category';
$this->form_validation->set_rules('category_name', 'Category Name', 'required');
$this->form_validation->set_rules('unit', 'Unit', 'required');
if ($this->form_validation->run() === FALSE)
{
$this->load->view('abc/add_new_category');
}
else
{
$category_name = $this->input->post('category_name');
$unit = $this->input->post('unit');
$this->load->model('abc/abc_category_model');
$insert_id=$this->abc_category_model->add_new_category($category_name
,$unit);
if($insert_id!=NULL)
{
$this->load->view('template/success',$data);
}
else{
$data['error_msg']='Error Occurred';
$this->load->view('template/template',$data);
}
}
}
function success(){
$data['success_msg']='New Category Successfully Created';
$this->load->view('template/success',$data);
}
}
And finally the model.
function add_new_category($category_name,$unit){
$data = array(
'abc_category_name' => $category_name ,
'unit' => $unit
);
$this->db->insert('abc_category', $data);
$insert_id=$this->db->insert_id();
return $insert_id;
}
}
What I want is that when I submit the form, jquery validation should take place. And if, all is well then the SUccessful message be displayed using ajax only and page should not reload.
Also, please tell me is it possible to use jquery validation and CI validation library both and maintaining ajax at the same time?
To implement both client side and server side validations you need to use the jquery validation plugin.
So, you need to include:
jQuery javascript library
jQuery validation plugin
Load the javascript with
<script type="text/javascript" src="<?php echo base_url();?>js/jquery-1.6.1.min.js"></script>
<script type="text/javascript" src="<?php echo base_url();?>js/jquery.validate.js"></script>
<script type="text/javascript" src="<?php echo base_url();?>js/jquery.validate-rules.js"></script>
then setup your form:
$attr = array('id' => 'demo_form');
echo form_open('demo/validation_example', $attributes);
and validate your form like:
$(document).ready(function() {
$("#demo_form").validate({
rules: {
name: {
required: true
},
...
},
messages: {
name: {
required: "Name required",
},
},
errorElement: "span",
errorPlacement: function(error, element) {
error.appendTo(element.parent());
}
});
});
And use the server side validation too, because it is not a good practice to use only client side validation.
For more help, you can find a good tutorial about
how to implement the jquery validation with codeigniter
and working demo
Where you can check jquery validation, and by disabling the javascript of your browser, you can check codeigniter server side validations done with php.
I think you have to use jquery ajax for this.
First you need to post your data. Set your submit button to fire jquery ajax like this.
$.ajax({
type: "GET",
url: "/controller/validate", //your controller action handler
dataType: "json",
data: {name:value, name: value}, //set your post data here
cache:false,
success: function(data){
//handle the callback response
if(data.success)
alert("Success");
else
alert(data.errors);
}
});
Next in your controller action, validate your post data using codeigniter validator.
If it fails the validation, you need to send the errors back to your js callback function using json_encode in your view. Set the data error like this,
In your view (the view you will set for /controller/validate), do something like this
$data['errors'] = validation_errors();
echo json_encode($data);
You will have the errors back to you without refreshing the page.
When the validation is success, just set a $data['success'] and use echo json_encode using if statement so that only success data will be retrieved. I have set the ajax script callback.

Categories