in one of my front end PHP files im doing this in my Jquery :
var name = $('#core_name').val();
var param = {};
param['name'] = name;
$.ajax({
url:'../back_end/user.php/verify_name',
data:param,
type:'POST',
success:function(result){
alert(result);
}
});
In my back_end/user.php im doing this :
<?php
class User{
function index(){
//for now do nothing
}
function verify_name(){
echo "here";
}
}
?>
Why cant i alert "here", what is it that iam doing wrong ?
Firebug detects no error , so the file user.php has correct path (no 404 error) why cant i reach the function verify_name ?
You need to instantiate the User class and call verify_name() on back_end/user.php.
You can do this adding the following to back_end/user.php:
$user = new User;
$user->verify_name();
Related
I'm having an issue with getting data from Controller, I have tried all the solutions here but it's the same..
when I click on the button it says 404 not found, if I change the URL to completed URL included the controller class name + function name, it says 403
Here is my view code :
<h2>Quiz</h2>
<script type="text/javascript">
$(document).ready(function(){
var BASE_URL = '<?php echo base_url(); ?>';
$('#show').click(function(e){
console.log(BASE_URL);
$.ajax({
url: BASE_URL + "Quiz/get_item",
dataType:'text',
type:"POST",
success: function(result){
var obj = $.parseJSON(result);
console.log(obj);
}
})
})
});
</script>
<button id="show">Show Cutomers</button>
<div id="customers-list"></div>
<p>Our first multi-page CodeIgniter application! Each page has its own controller and view!</p>
Here is my Controller code :
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Quiz extends CI_Controller {
var $TPL;
public function __construct()
{
parent::__construct();
$this->load->model('Quiz_data');
// Your own constructor code
}
function show_customers()
{
$query = $this->db-> query("SELECT * FROM quiz ORDER BY id;");
$this->TPL['listing'] = $query->result_array();
$this->template->show('quiz', $this->TPL);
}
public function index()
{
$this->template->show('quiz', $this->TPL);
}
public function get_item(){
$data = $this ->Quiz_data->get_data();
echo json_encode($data);
}
}
Here is my Model code :
<?php
class Quiz_data extends CI_Model {
public function get_data()
{
$query = $this->db->get('quiz');
return $query -> result_array();
}
}
What is the output of
console.log(BASE_URL);
Didnt mess with CI for quite a while, but it used to need /index.php/ in the URL. Try:
url: BASE_URL + "/index.php/quiz/get_item",
Although the controller-name needs to start with a capital, it doesnt need to be called that way in the URL.
Make sure url: BASE_URL + "Quiz/get_item" provides the correct URL.
var BASE_URL = '<?php echo base_url(); ?>'; May not provide trailing slash and you won't get correct url.
Try updating your call with following:
url: BASE_URL + "/Quiz/get_item",
Am apology for my bad english. Am new to prestashop. Please anybody help. How to send AJAX request to custom php file in prestashop
//My js file
$.ajax({
url : baseUrl + "modules/<myModule>/ajaxfunc.php",
type: "POST",
cache: false,
data : {form_data: 1 , action:'imageuploadAction'},
beforeSend: function() {
$('body').append('<div class="loading_popup">Loading...</div>');},
success: function(data){
console.log(data);
}
});
// php file
// modules/<myModule>/ajaxfanc.php
<?php
include_once('../../config/config.inc.php');
include_once('../../init.php');
class ajaxfuncAjaxModuleFrontController extends ModuleFrontController
{
public function imageuploadAction() {
die('here');
}
}
?>
I didn't know its be correct or not. please guide me.
You can use an ajax front controller in your module and generate the URL you need for the Ajax request in the module itself with a hook.
See Make an ajax request from a Prestashop module
I have found the solution to get the proper Ajax request in prestashop 1.7
//In tpl file
<script>
var url= {url entity='module' name='<myModuleName>' controller='<MyControllerName>' params = ['var1' => 1,'var2' => 2,action => 'MyControllerAction']}
</script>
//In Js file
$.ajax({
url : url,
type: "POST",
data : 'var3='3,
success : function(response){
console.log(response);
}
});
//In Controller Php file
<?php
require_once(dirname(__FILE__).'../../../../config/config.inc.php');
require_once(dirname(__FILE__).'../../../../init.php');
class <MyModule><MyController>ModuleFrontController extends ModuleFrontController
{
public function initContent()
{
$this->ajax = true;
parent::initContent();
}
// displayAjax for FrontEnd Invoke the ajax action
// ajaxProcess for BackEnd Invoke the ajax action
public function displayAjaxMyControllerAction()
{
$var1 = Tools::getValue('var1');
$var2 = Tools::getValue('var2');
$var3 = Tools::getValue('var3');
header('Content-Type: application/json');
die(Tools::jsonEncode(['var1'=> $var3]);
}
}
I am working on a project using PHP Codeigniter. I want to know how can I sent a variable with JQuery to the controller. Below is my code
<script>
function Reset_User_Password(id){
$.post("<?=base_url();?>WebAdmin/Reset_User_Password/id", {id: id}, function(page_response)
{
$(".modal-body").html(page_response);
});
}
</script>
Here I'm first getting the variable 'id' from function parameter. But when I run this code, it return the string 'id' instead of the actual user id from database. I want to view the user id. Below is my function from the controller..
public function Reset_User_Password()
{
$data['admin_id'] = $this->uri->segment(3);
$this->load->view('admin/user/reset_user_password', $data);
}
Send data by POST method is not append in url as GET method. So you can't get is using $this->uri->segment().
Instead use
$data['admin_id']=$this->input->post('id');
Use
$this->input->post('id');
Don't use $this->uri->segment(3); because you are posting id by post method if you want to use $this->uri->segment(3); then do a minior miodification in your function
$.post("<?=base_url();?>WebAdmin/Reset_User_Password/"+id, function(page_response)
{
$(".modal-body").html(page_response);
});
You can take help with this code. It is working perfectly at my end
function Reset_User_Password(){
var currentpwd= document.getElementById("currentpwd").value;
var newpwd = document.getElementById("newpwd").value;
var cnfrmnewpwd = document.getElementById("cnfrmnewpwd").value;
var url = "<?php echo base_url('user/changepwd'); ?>"
$.ajax({
type:"POST",
data:{currentpwd:currentpwd,newpwd:newpwd,cnfrmnewpwd:cnfrmnewpwd},
url:url,
success:function(data){
if(data){
$('#newsleter').html(data);
}
}
});
}
try below code
you should get that id variable from GET method on the controller.
function Reset_User_Password(id){
$.post("<?=base_url();?>WebAdmin/Reset_User_Password/id="+id
$(".modal-body").html(page_response);
});
I've made an ajax call with this:
$('.start-rate-fixed').on('click', function(e){
e.preventDefault();
var videoRate = $('.start-rate input[name="rating"]:checked').val(),
productId = parseInt($('.popover-content').prop('id'));
$.ajax({
url : ROOT + 'products/rate_video',
type : 'POST',
data : {
'data[Product][id]' : productId,
'data[Product][success_rate]' : videoRate
}
}).done(function(res){
var data = $.parseJSON(res);
alert(data);
});
});
Where I defined ROOT as the webroot of my cakephp project in my default.ctp with this:
<script type="text/javascript">
var ROOT = '<?php echo $this->Html->url('/');?>';
</script>
and trying to retrieve data from a function "rate_video" defined in my products controller but I get this error. Also I've tried a simple ajax for a test function but it showed me the same issue.
Controller Code
public function rate_video(){
$this->autoRender = false;
if($this->request->is('post') && $this->request->is('ajax')){
$success_rate = $this->request->data['Product']['success_rate'];
$this->Product->id = $this->request->data['Product']['id'];
if($this->Product->saveField('success_rate', $success_rate)){
echo json_encode('Successfully Rated');
} else {
echo json_encode('Error!!');
}
}
}
Please add dataType and a forward slash (/) at the end of your request URL
$.ajax({
url : ROOT + 'products/rate_video/',
type : 'POST',
data : {
'data[Product][id]' : productId,
'data[Product][success_rate]' : videoRate
},
dataType: 'json',
}).done(function(res){
I just had the same problem and solved it by putting the URL within AJAX call to a URL that I know works. Then try accessing the URL that you are trying to invoke via AJAX directly within the web browser - most likely you are accessing a controller that does not have a view file created. To fix this you have to ensure that the controller method being accessed does not have a view to be rendered - set $this->render(null)
If you have incorrect url then
url: '<?php echo Router::url(array('controller' => 'Controllername', 'action' => 'actionname')); ?>'
this above url provide ajax to url from root to your action.
And other cause for 403 is your auth function, if your using auth in your controller then make your ajax function allow like
$this->Auth->allow('Your ajax function name here');
Your script placed at localhost/dev.popover/products/rate_video but ajax ROOT is / - that mean localhost/ and ajax sent request to
'localhost/products/rate_video'
Right solution is
<script type="text/javascript">
var ROOT = '<?php echo $this->Html->url('/dev.popover/');?>';
</script>
I have 2 files(call.php and post.php) and using ajax pass value from call to post,and i want to get return value from post ,but this doesn't work. when i change post ,modify "return" to "echo",it works,but i don't know why.can anybody give me a help?
Examples would be most appreciated.
call.php
<script type="text/JavaScript">
$(document).ready(function(){
$('#submitbt').click(function(){
//var name = $('#name').val();
//var dataString = "name="+name;
var dataPass = {
'name': $("#name").val()
};
$.ajax({
type: "POST",
url: "post.php",
//data: dataString,
data: dataPass,//json
success: function (data) {
alert(data);
var re = $.parseJSON(data || "null");
console.log(re);
}
});
});
});
</script>
post.php:
<?php
$name = $_POST['name'];
return json_encode(array('name'=>$name));
?>
update:
by contrast
when i use MVC "return" will fire.
public function delete() {
$this->disableHeaderAndFooter();
$id = $_POST['id'];
$token = $_POST['token'];
if(!isset($id) || !isset($token)){
return json_encode(array('status'=>'error','error_msg'=>'Invalid params.'));
}
if(!$this->checkCSRFToken($token)){
return json_encode(array('status'=>'error','error_msg'=>'Session timeout,please refresh the page.'));
}
$theme = new Theme($id);
$theme->delete();
return json_encode(array('status'=>'success'));
}
$.post('/home/test/update',data,function(data){
var retObj = $.parseJSON(data);
//wangdongxu added 2013-08-02
console.log(retObj);
//if(retObj.status == 'success'){
if(retObj['status'] == 'success'){
window.location.href = "/home/ThemePage";
}
else{
$('#error_msg').text(retObj['error_msg']);
$('#error_msg').show();
}
});
This is the expected behaviour, Ajax will get everything outputted to the browser.
return only works if you are using the returned value with another php variable or function.
In short, php and javascript can't communicate directly, they only communicate through what php echoed or printed. When using Ajax or php with javascript you should use echo/print instead of return.
In Fact, as far as I know, return in php is not even used in the global scope very often (on the script itself) it's more likely used in functions, so this function holds a value (but not necessarily outputs it) so you can use that value within php.
function hello(){
return "hello";
}
$a = hello();
echo $a; // <--- this will finally output "hello", without this, the browser won't see "hello", that hello could only be used from another php function or asigned to a variable or similar.
It's working on the MVC framework because that has several layers, probably the delete() method is a method from the model, which returns its value to the controller, and the controller echo this value into the view.
Use dataType option in $.ajax()
dataType: "json"
In post.php try this,
<?php
$name = $_POST['name'];
echo json_encode(array('name'=>$name));// echo your json
return;// then return
?>