I try that: when clicking on an image a function is executed, this function collects a value and sends it via POST to the controller, this controller collects this data and displays the view. The problem is that everything works but it doesn't get to show me the view, I stay where I was.
Image that calls the function when clicking:
<img onclick="getSubjectPublication(<?php echo $inf->codiAsignaturaDesti; ?>)" id="click" src="/EEmobi/resources/images/click.png"/>
Function:
function getSubjectPublication(data){
console.log("EntroFuncion");
console.log(data);
$.ajax({
type: "POST",
url: "perfil.php/" + "subjectPublications",
data: {"data":data},
success: function(response) {
console.log(response);
},
error: function(t, e) {
window.alert("Error al intentar visualitzar les publicacions");
}
})}
The function calls this general controller (lib), it collects the sent data and passes it to the specific controller:
case 'subjectPublications':
$controllerName = "SubjectPublicationsController";
$actionName = "showSubjectPublications";
$data = $_POST['data'];
array_push($parameters, $data);
break;
Specific Controller:
<?php class SubjectPublicationsController{
function __construct(){
$this->view = new View();
}
public function showSubjectPublications($parameters){
require 'models/PublicationsSubjectModel.php';
$publicationsSubjectModel = new PublicationsSubjectModel();
$data = $parameters[0];
echo "<script>console.log('ENTROFINAL');</script>";
echo "<script>console.log('. json_encode( $data ) .');</script>";
$subjectPublications = $publicationsSubjectModel->getPublicationOfSubject($data);
$route = $this->view->show("PublicationsSubject.php");
$publicationsSubjectModel->disconnect();
include ($route);
}}?>
The case is that in the console browser it shows me the console.log that I do in the function and the response returns the entire web including the view that I include in the controller (the view that i wanted to show in the browser), but it doesn't show it on the screen, i continue with the same screen and not the one that I included in the controller. What am I doing wrong?
Browser Screenshot
When you complete a ajax request you generally want to send back a json object. In this case maybe about the image that you clicked. So then you do something with that in your success function e.g alert - or show a popup or something. Look at json_encode to send your data back from your php page php.net/manual/en/function.json-encode.php
Related
In my view , let's call it View-A, I get an input from user in a prompt and assign it to a variable, and then I need to load in browser another view, say View B, while passing it that variable.
Say, in my viewA.blade.php, I have taken user's input and assigned it to variable usersInput. Now I need to send it to view B, whose route in web.php is defined at Route::get('editRecord', 'MyController#displayEditRecordView')->name('editRecordFormView');.
Question is how do I load route(editRecordFormView) in browser and pass usersInput variable to it, from javascript written in my blade view?
#Tushar In in my ViewA.blade.php:
$.ajax({
url: url_editRecordView.url,
data: {
usersInput: dataToSend.usersInput,
},
method: "get",
cache: false,
success: function (dataReturned, stringStatus, jqXHR) {
console.log("dataReturned from mYController.displayEditRecordFormView:-");
console.log(dataReturned);//check
console.log("Type of dataReturned:-" + typeof dataReturned); //SAME DATA COMES BACK, AS THE DATA I SENT
},
error: function (jqXHR, stringStatus, stringExceptionThrown) {
alert("Error! status: " + stringStatus + " ExceptionThrown: " + stringExceptionThrown);//check
}
});
In my MyController:
public function displayEditRecordFormView (Request $request) {
error_log("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");//check
error_log("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");//check
$title= $request->input('usersInput');
error_log("In displayEditRecordFormView: title: ".$title);//check
$allPaintingsArray = $this->getAllPaintingsArraySanitized();
$data = [
"allPaintingsArray"=>$allPaintingsArray ,
"title"=>$title
];
return view("paintings.editRecordForm")->with("allGoodData", $data);
}
Instead of AJAX call why don't use something like this:
var url = "/editRecord?usersInput=dataToSend.usersInput;
window.location.href = url;
catch variable In controller:
$title= request()->filled('usersInput');// or find a way according to Laravel version
You can make use of AJAX. Just set an event handler for when the user gives an input, and send a request containing the user input to a method in your View-A controller via AJAX and from there you can redirect to View-B along with the value that you got from the request.
EDITED
Instead of using view() method try using redirect() method like this:
return redirect()->route('editRecordFormView', ['input' => 'userInput']);
To know more about redirects please refer to this
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;
}
I have the following php codeigniter function code which is being called by a jquery ajax function:
$this->load->library('session');
$this->load->helper('url');
$ids = $_POST['i'];
$message = $_POST['m'];
var_dump($message);
var_dump($ids);
$sql = 'update replies set `response` = "'.$message.'" where id IN ('.implode( ',', $ids).')';
echo $sql;
R::exec($sql); // works normally to here
redirect($this->uri->uri_string());
I want to refresh the page after the db insertion of 'message'. however nothing seems to happen. everything works normally including the db insertion. What am I doing wrong?
You can not redirect via AJAX url. Redirect is possible using callback function in
three ways done, fail and always.
Example:
$.ajax({
url: '/path/to/file',
type: 'default GET (Other values: POST)',
dataType: 'default: Intelligent Guess (Other values: xml, json, script, or html)',
data: {param1: 'value1'},
})
.done(function(url) { // echo url in "/path/to/file" url
// redirecting here if done
location.href = url;
})
.fail(function(url) { // echo url in "/path/to/file" url
// redirecting here if failed
location.href = url;
})
.always(function(url) { // echo url in "/path/to/file" url
// redirecting here always
location.href = url;
});
On your ajax success use this after showing success message
window.location="path_to redirect";
like for example i am redirecting to member controller
window.location="member";
Hope this helps.
I have a loader in user panel which is waiting for a response from user's mobile device. Unfortunately i'm compeletly blank on how to get the request from mobile device, and update the page content real time.
right now the problem i have is i am sending data from view page to my Controller function through ajax .... then in Controller function i am sending some data which i get from the ajax function to the other function which is in utility class and then returning the result to the ajax function.... and whenever the i receive the response from the controller function then i am starting the loader/preloader/ajax spinner ... now after the i am sending a variable from android ... so after the android response comes i want to stop the loader ... so i dont know how to i call the ajax function specifically and the response from controller
there can be two ways to acheive this
1st either i call directly the javascript function from android and then grab the value .
2nd or i call the javascript function from controller and send the value in ajax function ..dont know if it is possible ...
my js function
function openPrompt()
{
var cancelled = true;
var lock='lock';
$.modal.prompt('Enter message :', function(value)
{
$.ajax({
type:"POST",
data:{value:value,lock:lock},
url:"/allsecure/api/lock/",
success : function(data) {
//start spinner
},
error : function() {
alert("error");
}
});
}, function()
{
});
};
Controller function
public function lock(){
if( $this->request->is('ajax') ) {
$message = $this->request->data('value');
$lock = $this->request->data('lock');
$this->loadModel('Userinfo');
$userid = $this->Auth->User('idUser');
$key = $this->Userinfo->getKey($userid);
$apiKey = "1234567890";
$resp = AllSecure::sendNotification($apiKey, array($key), array('message' => $lock, 'tickerText' =>$message));
echo $resp; //after this response i am starting the loader
}
}
function android(){
// here i am getting the variable from android
$json = $this->request->data('json');
$data = json_decode($json, TRUE);
openPrompt()//here i want to call the javascript function and want to send the value of android to the javascript
}
or there is any better approach to do this ???
If you want to execute client javascript from the server you can do similar thing as JSONP does. Where the response is JSON data wrap in javascript function that is executed in client.
I am using Codeigniter with Zurb Foundation framewrk. i am tryin to load data in reveal box(fancy popup) using AJAX.. The trick is, i am not loading just the inner html content, but the HTML itself..I mean, i want the function in controller to return the php file to ajax calling function whose contents will be displayed in popup.. My code is
Ajax function call
function ajaxfunct() {
$.ajax({
type: "POST",
url: "welcome/test",
data: { name: "Jigar", location: "jain" }
}).done(function( html ) {
$("#tagUser").append(html);
});
}
My Controller Code is
public function test() {
$data['name'] = $_POST['name'];
$data['location'] = $_POST['location'];
$this->load->view('index', $data);
echo 'WHAT SHUD I ECHO HERE ?'
}
I know the last 2 lines of my Controller code is wrong..I just dont know how to fetch a php file from views folder, process it and pass it to ajax as a pre-processed html(string).
I am not looking for entire code..just a reference to some function or online tutorials will be great..
thanx
You already do fetch a PHP file from your views folder in your Controller.
The line
$this->load->view('index', $data);
Loads the /application/views/index.php file and processes it with data from the $data array.
So for Your AJAX call you could make a different view file than index.php like test.php that contain the proper HTML for the AJAX and call it with the line
$this->load->view('test', $data);
And skip the ECHO part...