Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I am using codeigniter for my site. Now I am working to get captcha. For refreshing captcha image, I use Jquery Ajax. When Jquery is calling my captcha_refresh function in controller, I get Internal server error.
Here is my controller:
class Register extends CI_Controller {
function __construct(){
parent::__construct();
//start session
session_start();
$this->load->model('model_users');
$this->load->helper('captcha');
}
function index() { ...}
//here goes some code
// For new image on click refresh button.
function captcha_refresh(){
header('Content-type: application/json');
$values = array(
'word' => '',
'word_length' => 8,
'img_path' => './images/images/',
'img_url' => base_url() .'images/images/',
'font_path' => base_url() . 'system/fonts/texb.ttf',
'img_width' => '150',
'img_height' => 50,
'expiration' => 3600
);
$data= create_captcha($values);
$_SESSION['captchaWord'] = $data['word'];
echo json_encode($data);
exit;
}
}
And here is my js function:
function refresh_captcha() {
new Ajax.Request(baseURL + 'Register/captcha_refresh', {
method: 'get',
evalJSON: true,
parameters: {},
onSuccess: function (transport) {
var answer = JSON.parse(transport.responseText);
},
onError: function () {
alert('Error');
},
onComplete: function () {
}
});
}
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 days ago.
This post was edited and submitted for review 3 days ago.
Improve this question
I got so problems to use the Uipath api with php.
I want to create a php api which put value in queue(I already sucess in typescript with the same value), i can’t/don’t want to do it with cURL.
But when I call it, there is an error : failed to open stream: HTTP request failed! HTTP/1.1 401 Unauthorized.
And on My IIS there is this error : Abp.Authorization.AbpAuthorizationException: Current user did not login to the application!.
this is my php call :
$app->post('/test', function (Request $request) use ($app) {
$postdata2 = json_encode(
array(
'itemData'=> array('Name'=>'testeur',
'Priority'=> 'High',
'DeferDate'=> '2023-02-15T09:33:19.667Z',
'DueDate'=> '2023-02-15T09:33:19.667Z',
'RiskSlaDate'=> '2023-02-15T09:33:19.667Z'
)
)
);
// var_dump($token);
$test=56;
$opts2 = array(‘http’ =>
array(
'method' => 'POST',
'header' => 'Content-Type: application/json\r\n'.
'accept : application/json\r\n'.
'X-UiPath-OrganizationUnitId:'.$test.'\r\n'.
'Authorization:Bearer '.$token.'\n',
'content' => $postdata2
)
);
$context2 = stream_context_create($opts2);
$result = file_get_contents('xxxxxxxxx/odata/Queues/UiPathODataSvc.AddQueueItem', false, $context2,-1, 40000);
return $result ;
}
$app->after(function (Request $request, Response $response) {
$response->headers->set('Access-Control-Allow-Origin', $request->headers->get('Origin'));
$response->headers->set('Access-Control-Allow-Methods', 'HEAD, OPTIONS, GET, POST, PUT, PATCH, DELETE');
$response->headers->set('Access-Control-Allow-Credentials', 'true');
$response->headers->set("Access-Control-Allow-Headers", "Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With,X-UIPATH-OrganizationUnitId,accept");
});
there is my call in typescript :
headers: new HttpHeaders({
'Content-Type': 'application/x-www-form-urlencoded'
}),
responseType: 'text' as 'text'
};
public test() {
return this.http.post(`${environment.variables.urlApiSite}/test`, this.httpOptions)
.toPromise()
.then((response) => {
//console.log(response);
return response;
})
.catch(err => this.handleError(err));
}```
I succesfully make the other api post in php to have the token. And the same function in Typescript work.
I know it's a commun question and I red nearly all the subject about it, but i can't find an answer who fit my case.
I wrote a plugin to add country and languages related (USA->English|Sapnish for example) I am using Class and constructor for the plugin's functions. It is fully working expect the following function :
I get a select in front with all the country, and on change of this select action another function with ajax, the data passed are ok but the response is always returning 0, connected as admin or not.
Here is my ajax :
$('#sel-country-back').change(function(){
var post_id = $(this).val();
change_status(post_id);
})
function change_status(id) {
$.ajax({
url: window.location.origin + '/wp-admin/admin-ajax.php',
data: {
action: 'wmu-display-lang-select',
post_id: id,
},
type: 'post',
success:function(data){
$('#lang-back').html(data);
},
error: function(errorThrown){
$('#lang-back').html('<select name="langBack" id="sel-lang-back"><option value="default" class="no-lang-option">Aucune langue associée</option></select>');
}
});
}
and my function
public function wmu_display_lang_select()
{
if ($_POST['post_id']) {
$id = sanitize_text_field($_POST['post_id']);
$lang = self::getLang($id);
if ($lang !== false) {
$response = array(
'status' => 200,
'content' => $lang
);
}
else {
$response = array(
'status' => 201,
'message' => __('Le fichier demandé n\'existe pas', 'cadwork')
);
}
die(json_encode($response));
}
}
with the action added to the constructor
public function __construct()
{
add_action('admin_menu', array($this, 'wmu_add_menu'));
add_action('wp_ajax_wmu_display_lang_select', 'wmu_display_lang_select');
add_action('wp_ajax_nopriv_wmu_display_lang_select', 'wmu_display_lang_select');
}
I tried to place the add_action outside the class after the class instantiation
$wmu = new WB_MultiLang_URL();
add_action('wp_ajax_wmu_display_lang_select', 'wmu_display_lang_select');
add_action('wp_ajax_nopriv_wmu_display_lang_select', 'wmu_display_lang_select');
but it doesn't seem to work,
Do you have any ideas why ? I think it's a dumb error or mistake somewhere but I can't find it...
Change action: 'wmu-display-lang-select', in your JS request to action: 'wmu_display_lang_select', and it should work.
this is my view code working on auto complete , but its showing me 500 internal server error
I am not sure what is going wrong if i'm not using the right url or some other problem.
public function search(){
$this->loadComponent('RequestHandler');
if ($this->request->is('ajax'))
{
$name = $this->request->query['term'];
$resultArr = $this->Invoices
->find()
->where(
['Invoices.name LIKE' => ($name . '%')],
['Invoices.name' => 'string']);
$resultsArr = [];
foreach ($resultArr as $result)
{
$resultsArr[] = ($result['name']);
}
$this->set('resultsArr', $resultsArr);
// This line is what handles converting your array into json
// To get this to work you must load the request handler
$this->set('_serialize', ['resultsArr']);
}
}
this is my view code:
<?php echo $this->Form->input('name', ['type' => 'text']); ?>
$.ajax({
type: "POST",
url: "<?php echo Router::url(array('controller' => 'Clinics','action' => 'search')); ?>",
success: function(response) {
$("#name").autocomplete({ source: response });
}
});
According to the error message in your comments, the loadComponent method isn't defined.
I would suggest loading the RequestHandler component near the top of your controller, for example:
class ClinicController extends AppController {
public $components = array('Request');
There is also another syntax for loading components on the fly:
$this->Request = $this->Components->load('Request');
Reference: https://book.cakephp.org/2.0/en/controllers/components.html
This question already has answers here:
How do I pass JavaScript variables to PHP?
(16 answers)
Closed 5 years ago.
I want to send data from JS file to PHP file where a function receives this data and performs further actions on it. But the problem is that the data isn't receiving from JS to controller function.
JS code:
$("#mybtn").click(function(){
$.post(<?= base_url()?>+"upload",{a1: $('#a1').val(), a2:
$('#a2').val(), a3: $('#a3').val(), a4: $('#a4').val(),a5:
$('#a5').val()},function(data) {
});
});
Controller function:
function upload() {
echo "this is upload";
$data = array(
'name' => $this->input->post('a1'),
'email' => $this->input->post('a2'),
'pass' => $this->input->post('a3'),
'amnt' => $this->input->post('a4'),
'pcode' => $this->input->post('a5')
);
$result = $this->pages_m->upload($data);
var_dump($data);
}
first you declare this on header, after this you dont need to use base_url() function again in ajax.
<script>
var url = <?php echo base_url(); ?>
</script>
$("#mybtn").click(function(){
$.ajax({
url: url+'upload',
type: 'post', // performing a POST request
data : {
a1: $('#a1').val(),
a2: $('#a2').val(),
a3: $('#a3').val(),
a4: $('#a4').val(),
a5: $('#a5').val()
},
dataType: 'json',
success: function(data)
{
console.log(data)
}
});
});
In controller
function upload()
{
if($_POST){
$data = array(
'name' => $this->input->post('a1'),
'email' => $this->input->post('a2'),
'pass' => $this->input->post('a3'),
'amnt' => $this->input->post('a4'),
'pcode' => $this->input->post('a5')
);
$result = $this->pages_m->upload($data);
if($result == true){
echo "Successfully Save";
}else{
echo "Error";
}
}
}
I am working with Js helper to help me replace the contents of a "div" in my index.ctp with contents of another file changeto.ctp .
This application has a few check boxes with corresponding images. When I select a checkbox, the setting is stored in the database and the corresponding image is to be displayed. Similarly when unchecked, it is to be removed from the database and the image should disappear.
I am using the Js helper for this :
my changeto.ctp is subset of my index.ctp and has access to same variables and loads without any problems (except that any click/change events are just not responded to. The names of the Ids of the checkboxes are exactly same).
My index file contains the following Js code at the bottom of all Html:
$this->Js->get($change_checkbox1 )->event('click',
$this->Js->request(array(
'controller'=>'testing',
'action'=>'changeto'
), array(
'update'=>'#changeDiv',
'async' => true,
'method' => 'post',
'dataExpression'=>true,
'data'=> $this->Js->serializeForm(array(
'isForm' => false,
'inline' => true
))
))
);
This is generating the following Jquery/javascript
$(document).ready(function () {$("#ck0_1_8").bind("click", function (event) {$.ajax({async:true, data:$("#ck0_1_8").closest("form").serialize(), dataType:"html", success:function (data, textStatus) {$("#changeDiv").html(data);}, type:"post", url:"\/mytest-site\/options\/testing"});
return false;});
}
My controller has a function called
changeto()
{
$this->layout = 'ajax';
}
the first time I click on this the checkbox this works without any problem. However any subsequent clicks don't work. The javascript is not even being called.
My questions are :
Any ideas ?
Will it help if I somehow ask cakephp to use on() / live() insead of bind() .If yes how ?
Thanks!!
Solved this by editing a cakephp core file:
lib/Cake/View/Helper/JqueryEngineHelper.php
line 184:
change
return sprintf('%s.bind("%s", %s);', $this->selection, $type, $callback);
to
return sprintf('%s.live("%s", %s);', $this->selection, $type, $callback);
cake version 2.2.2
You have to use on instead of bind as they suggest in this question .live() vs .bind()
That's what I did was create my own Helper on View/Helper add the following method:
public function onEvent($selector, $type, $callback, $options = array()) {
$defaults = array('wrap' => true, 'stop' => true);
$options = array_merge($defaults, $options);
$function = 'function (event) {%s}';
if ($options['wrap'] && $options['stop']) {
$callback .= "\nreturn false;";
}
if ($options['wrap']) {
$callback = sprintf($function, $callback);
}
return sprintf('$(document).on("%s", "%s", %s);', $type, $selector, $callback);
}
And use that method from my views:
echo $this->MyJs->onEvent('#creditcards', 'change', $eventCode, array('stop' => false));