codeigniter and ajax cannot access the post - php

On my website I am using ajax post request to show content around my site, this is done using this code,
$("a.contentlink").click(function(ev) {
ev.preventDefault();
$('#main_menu').hide();
var url = $(this).attr("href");
var data = "calltype=full&url="+url;
$.ajax({
url:url,
type: "POST",
data: data,
success : function (html) {
$('#left-content-holder').html(html);
}
})
});
as you can see I am passing the url into the `$_POST' and I can access this in the method the javascript calls, this method is called get_content_abstract and looks like this,
public function get_content_abstract() {
$this->load->model('content_model');
if($this->input->post('calltype') == "abstract"){
if($query = $this->content_model->get_content_by_id($this->uri->segment(3))) {
$data['abstract'] = $query;
}
$this->load->view('template/abstract', $data);
}
elseif($this->input->post('calltype') == "full") {
if($query = $this->content_model->get_content_by_id($this->uri->segment(3))) {
$data['full'] = $query;
}
$this->load->view('template/full-content', $data);
}
}
How ever I have no added a new function that will allow the user to save the content to 'bookmarking system', however in my method I cannot access the post using codeigniters $this->input-post('url') (where URL is the one of peices of data passed in the javascript), it says that the post is empty when I var dump it, this is done using this method,
public function love_this() {
die(var_dump($this->post->input('url')));
}
can anyone help as to why the post is empty in this love_this method?

Shouldn't:
public function love_this() {
die(var_dump($this->post->input('url')));
}
Actually be
public function love_this() {
die(var_dump($this->input->post('url')));
}
See:
http://codeigniter.com/user_guide/libraries/input.html

Related

Ajax POST, check PHP $_GET and then $_POST

Using the following Ajax POST function on form submit (simplified here):
$form.on("submit", function (i) {
i.preventDefault();
var sendEmail = 1;
ValidateForm(sendEmail, "goSignup");
});
function ValidateForm(sendEmail, action) {
$.ajax({
type: "POST",
url: window.location.pathname,
dataType: "json",
data: {
ajaxRequest: 1,
sendEmail: sendEmail,
}
}
After I post this I want to use a conditional GET parameter that equals 1 (i.e https://www.example.com?test-parameter=1) and then if it's present in the URL use one or another function from there if the ajaxRequest is received from $_POST in my PHP:
public function __construct() {
$testingParameter = $_GET["test-parameter"] ?? '';
if (trim($testingParameter) == '1') { // if has get parameter equal
if (!empty($_POST['ajaxRequest'])) { // if JS postRequest has been posted
$this->handlePostRequests();
}
echo 'has get parameter';
} else { // else use old logic
if (!empty($_POST['ajaxRequest'])) {
$this->handleOtherRequests();
}
echo 'no get parameter';
}
}
Issue:
I get the correct echo from PHP but when I submit the form with Ajax its still using the handleOtherRequests(); instead of the handlePostRequests(); function if I'm using the url www.example.com?test-parameter=1.
Likely getting some basic PHP logic wrong here, would appreciate if anyone could guide me in the right direction with this.
url: window.location.pathname,
Your Ajax is never going to POST the data to a URL with a query string because you explicitly took only the path name.
Maybe you want location.href instead.

Use codeiginiter and ajax following the rules codeigniter

I'm struggeling to use codeigniter the way it was created. I'm opening an edit page (order). I want to change data on the page which will be dynamically saved after leaving a field. But when I'm not succeeding in the way codeigniter works or with other words on a "nice way". I don't want to be depending on the uri structure and get the data with uri segment, like the code is now. I want to improve the code beneath but i'm not succeeding...
This is the code to open my view
public function edit($id = NULL) {
// Fetch a page or set a new one
$this->load->model('shop_m');
$this->load->model('details_m');
$this->data['subtitle'] = 'incoming';
if ($id) {
if($this->transfer_m->get_permission($id) > 0){
$this->data['transfer'] = $this->transfer_m->get_rec($id);
// $this->data['transfer'] = $this->transfer_m->get($id,true);
count($this->data['transfer']) || $this->data['errors'][] = 'page could not be found';
$this->data['details'] = $this->details_m->get_by(array('doc_no' => $id),FALSE);
}
else{
redirect('admin/Dashboard', 'refresh');
}
} else {
$this->data['transfer'] = $this->transfer_m->get_new();
}
$this->data['shop_from'] = $this->shop_m->get($this->data['transfer']->from_customer,TRUE);
$this->data['shop_to'] = $this->shop_m->get($this->data['transfer']->to_customer,TRUE);
// Load the view
$this->data['subview'] = 'pages/details/transfer_edit';
$this->load->view('pages/main', $this->data);
}
My ajax call
function add_shop(shop){
var id = $('#doc_no').text();
$.ajax({
url: base_url+"/admin/transfer/add_shop/"+id+"/"+shop,
async: false,
type: "POST",
data: "",
dataType: "html",
success: function(data) {
$('#ajax-content-container').hide();
}
})
}
my controller function to add a shop
public function add_shop($id){
$data = array('to_customer' => $this->uri->segment(5));
$this->transfer_m->save($data,$id);
}
Any help will be appreciated!!
You can use post. Modify your ajax call and pass the data like below. See the document here https://api.jquery.com/jquery.post/
data: { id: id, shop: shop }
This data can be accessed $this->input->post('id'); $this->input->post('shop');

Ajax Auto-complete search with Code-igniter

Ajax Auto-complete search with Code-igniter from my database. I am trying to search my database and Ajax completes the search from items saved on my database. I believe I am missing a simple trick. Maybe I am writing my controller or maybe everything all wrong... Code below
// View Page
Location path: application/views/template/header
<form class="navbar-form" >
<input type="text" id="mysearch" placeholder="search" onkeyup="doSearch();">
<br />
<script>
// This is the jQuery Ajax call
function doSearch()
{
$.ajax({
type: "GET",
url:"localhost/codeigniter/index.php/ajax/getdata/" + $("#mysearch").val(),
success:function(result){
$("#searchresults").html(result);
}});
}
//class example
</script>
Note: My form or search box is inside my header... So my view page is located in template/header
// Controller Page
Location path: codeigniter/application/controller/ajax.php
class Ajax extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->model('ajax_model');
//$this->load->helper('url_helper');
}
public function form ()
{
$data['title'] = 'Ajax search';
$this->load->view('template/header');
}
// function ends
public function getdata($param = '')
{
// Get data from db
$data['ajaxdata'] = $this->ajax_model->search($param);
// Pass data to view
$this->load->view('template/header', $data);
}
}
?>
// My Model
Location path: application/model/Ajax_model.php
<?php if (! defined('BASEPATH')) exit('No direct script access');
class Ajax_model extends CI_Model
{
public function __construct()
{
$this->load->database();
}
public function search ($title){
$this->db->select('title');
$this->db->select('text');
$this->db->like('title', $title, 'both');
return $this->db->get('news');
}
}
?>
Please be aware I am new to CodeIgniter. It explains my rather obvious ignorance
$data['ajaxdata'] = $this->ajax_model->search($param);
$data['ajaxdata'] = json_encode($data['ajaxdata']);
echo $data['ajaxdata'];
Ajax method expects data in form of (JSON) string. So you don't need to load header again. Instead, just pass needed data from DB and jQuery will put it in designated place. In this case into element with id of searchresults.
Try changing this
$this->load->view('template/header', $data);
to
$content = $this->load->view('template/header', $data,TRUE);
// load view to a variable.
echo $content;
if i am clear what you need try:
first define ajax request type:
function doSearch()
{
$.ajax({
type: "GET",
dataType:"html",
url:"localhost/codeigniter/index.php/ajax/getdata/" + $("#mysearch").val(),
success:function(result){
$("#searchresults").html(result);
}});
}
Then in controller :
just echo your view:
$auto_complete_html = $this->load->view('template/header', $data,TRUE);
echo $auto_complete_html;
//good practice always die(); after ajax called
die();
Try using POST in AJAX instead of GET:
<script>
// This is the jQuery Ajax call
function doSearch()
{
var search = $("#mysearch").val()
$.ajax({
type: "POST",
url:"localhost/codeigniter/ajax/getdata/",
data:'search=' + search,
success:function(data){
$("#searchresults").html(data);
}});
}
//class example
</script>
Then in your controller Get THE POSTED data from AJAX
public function getdata()
{
$param= $this->input->post('search');
// Get data from db
$result = $this->ajax_model->search($param);
// Pass data to view
echo $result;
}

codeigniter function load two pages of same function calls in different ways

I am using two ways for user login in codeigniter:
One is by typing url like this localhost/mySite/login
Other is popup dialog appear when I click a link from localhost/mySite
When I'm following step 2 then calling a function using ajax request.
both time I am calling same function. but when call to the function using Ajax load an additional header.
I used following code for the calling function.
if ($this->input->is_ajax_request()){
echo json_encode(array('status'=>'success','url'=>'auth/enable_account'));
exit();
}
else {
redirect ( "auth/enable_account",'refresh');
}
My jquery code
jQuery('#signin_form').submit(function(event) {
var email = jQuery('#email').val();
var password = jQuery('#password').val();
var remember = jQuery('.dev_signin_remember').is(':checked');
jQuery.ajax({
url:baseurl+'auth/login',
type:'POST',
data:{'email':email,'password':password,'remember':remember},
dataType:'json',
success:function(data){
if(data.status == 'success') {
if(data.url != '') {
window.location.replace(baseurl+data.url);
}
else {
window.location.replace(baseurl+"auth/login");
}
}
else {
jQuery('.dev_signin_error').html('Invalid Username or password');
}
}
});
setTimeout(jQuery.unblockUI);
});

Zend Json render data into views

Hi i have an Zend Framework apps, the following code are popularAction controller
public function popularAction()
{
$type = $this->_getParam('ref',1);
if($type == 'reviews'){
$businessReviewMapper = new Application_Model_Mapper_BusinessReviewsMapper();
$result = $businessReviewMapper->getTotalVote();
$rotd = $businessReviewMapper->getROTD($result['review_id']);
$rotd[0]['u_img'] = $this->view->getLoginUserImage($rotd[0]['social_id'],$rotd[0]['login_type'],null,null,square);
$rotd[0]['rating'] = $this->view->getRatingImg($rotd[0]['rating']);
$rotd[0]['business_name_url'] = preg_replace("![^a-z0-9]+!i","-", $rotd[0]['business_name']);
$this->render('reviews');
$this->_helper->json($rotd);
} elseif($type == 'openings') {
$this->view->text = "New Openings";
} else {
$this->_helper->redirector('index', 'index', 'default');
}
}
When a user browse to http://localhost/business/popular?ref=reviews the above controller code would render reviews.phtml template. Now inside the template itself there is ajax request for a data as follow:
function getPopular()
{
var count=1;
$.ajax({
url:"<?=$this->baseUrl('business/popular?ref=reviews')?>",
data:{'count':count},
dataType:"json"
type:"POST",
success:function(data){
alert('ok')
}
});
unfortunately the $this->_helper->json($rotd); doesn't pass data to the reviews.phtml,but display json data which is returned by zend db model, where i might be wrong?Thanks
If your Goal is to, to send JSON instead of the .phtml File on an Ajax Request, try to implement this:
if ($this->getRequest()->isXmlHttpRequest()) {
if ($this->getRequest()-isPost()) {
$this->_helper->json($rotd);
}
}
This part checks if the request is, lets call it: ajax based..

Categories