I've been stuck with the retrieving of my sent variable trough an ajax POST function. Could you help me out?
My Jquery code:
$.ajaxSetup ({
cache: false
});
var selected = new Array();
$(document).ready(function() {
$('.value').click(function () {
if($(this).hasClass('strong'))
{
selected.splice(selected.indexOf(this.innerHTML), 1);
submitData(selected);
$(this).removeClass('strong');
}
else
{
selected.push(this.innerHTML);
submitData(selected);
$(this).addClass('strong')
}
});
});
function submitData(arDat) {
var arrayData = {"param1" : JSON.stringify(arDat)};
$.ajax({
type: 'POST',
url: 'http://localhost.local/coconut/trunk/challenges/values',
data: arrayData,
dataType: 'json',
success: function(data){
console.log(arrayData);
},
error: function(message){
alert(message);
}
});
}
My CakePHP Controller function:
function values() {
if ($this->RequestHandler->isAjax()) {
$this->autoRender = false;
Configure::write('debug', 0);
$params = json_decode($_POST['param1']);
//$result = json_encode($params);
$this->set('submitValue', $params);
} else {
$this->redirect(array('controller' => 'challenges', 'action' => 'index'));
}
}
And in a view.ctp file:
<?php debug($submitValue); ?>
But I get the following error:
Notice (8): Undefined variable: submitValue
In firebug I see this:
Parametersapplication/x-www-form-urlencoded
param1 ["Business","Life","Health"]
Source
param1=%5B%22Business%22%2C%22Life%22%2C%22Health%22%5D
Does anyone know what I'm doing wrong?
Thanks!
Edit:
A bit more clarification about what I want.. I want to use $this->set('submitValue', $params); (so $submitValue) elsewhere in another view.
The CakePHP function 'isAjax()' checks to see if a request is a Prototype Ajax request.
You aren't using Prototype, you're using jQuery - so presumably it's always returning false, and so submitValue is never set.
Related
I have seen many topics like mine but I can't resolve my problem who seems so simple.
I have this function in JS :
function displayFullDesignation(id, select) {
var fullDesignation = $('option:selected', select).data('idacc');
var myId = parseInt(fullDesignation);
$.ajax({
url: '<?php echo $this->url(array('controller' => 'catalog', 'action' => 'fullname'));?>',
type: 'POST',
datatype: 'json',
data: {'id': myId},
success: function(data) {
if(data.success){
console.log(data.success);
}
}
});
return fullDesignation;
}
And in my controller :
/**
* AJAX Action
*/
public function fullnameAction($params) {
$ajaxContext = $this->_helper->getHelper('AjaxContext');
$ajaxContext->addActionContext('fullname', 'json')->initContext();
$response = array();
$params = $this->getAllParams();
$listModels = Application_Model_Catalog_Accessory_List::getDesignationComplet($params['id']);
$response['success'] = true;
$response['aaData'] = $listModels;
$this->getHelper('json')->sendJson($response);
}
I don't know why I can't get anything from this ajax call. If I try to do a var_dump inside my function, it does nothing at all so I think that my call isn't good, but I have other calls who work like this.
What am I doing wrong please ?
And if I do a console.log of 'data', it gives me HTML. data.success gives me undefined.
Thanks !!
I'm using Yii 2.0 basic version and I need some help.
I created one ajax function like this:
function eliminarColaborador(id) {
$.ajax({
type: "GET",
async: false,
url: "<?= urldecode(Url::toRoute(['colaborador/ajaxEliminarColaborador'])) ?>",
dataType: 'json',
data: {
'id': id
},
complete: function ()
{
},
success: function (data) {
if (data !== null)
{
// SUCCESS
}
else
{
// ERROR
}
}
});
}
My action in controller:
public function actionAjaxEliminarColaborador($id) {
if (Yii::$app->request->isAjax) {
$continuar = false;
if(isset($id) && $id > 0) {
var_dump($model); die;
$continuar = true;
}
echo CJSON::encode(array('continuar'=>$continuar));
Yii::$app->end();
}
}
I'm getting this erro in firebug: Not Found (#404): Page not found.
I tried everything, but i can't figure out what's the problem.
If I change ajax url to urldecode(Url::toRoute(['colaborador/delete'])) the error is gone and all works just fine.
Maybe I need to declare in ColaboradorController my new action ajaxEliminarColaborador, but I don't know how.
What is wrong?
controller
public function actionAjaxEliminarColaborador(){}
ajax
urldecode(Url::toRoute(['colaborador/ajax-eliminar-colaborador']))
It should be <?= urldecode(Url::toRoute(['colaborador/ajax-eliminar-colaborador'])) ?>. Here you can learn why.
Change the ajax response with:
url: '/colaborador/ajaxEliminarColaborador/$id',
data: {id: $id,_csrf: yii.getCsrfToken()},
Try to remove the word 'ajax' on your url.
I'm new to cs cart. I need to pass the ajax results to blocks template file.
I have the following code in my controller :-
if($mode=='drill')
{
$id=166;
Registry::get('view')->assign('pid', $id);
$all_subcategory=fn_get_subcategories($id);
foreach($all_subcategory as $value){
$sub_cat[$value['category_id']]=$value['category'];
}
Registry::get('view')->assign('all_year', $sub_cat);
Registry::get('view')->display('templates/blocks/product_filters/components/drillsearch.tpl');
Registry::get('view')->assign('all_year', $sub_cat);
return $sub_cat;
}
I have the following code in drillsearch.tpl :-
function fun(){
var sBase = location.href.substr(0, location.href.lastIndexOf("/") + 1);
$.ajax({
url: sBase+"index.php?dispatch=drill.drill",
data: 123 ,
type: "POST",
success: function(data) {
alert("sfd");
alert(data);
},
error: function(xhr, status, error) {
alert('failed');
alert(xhr.responseText);
}
});
}
Here the ajax results does not assign templates/blocks/product_filters/components/drillsearch.tpl .How to solve it .Please help me
When sending a request from a view to a controller, you can "reply" to the view by simply using this:
Registry::get('ajax')->assign('all_year', $sub_cat);
I believe this shall work just fine, as the variable you need will be available to your AJAX response.
Please try
PHP
if($mode=='drill'){
$id=166;
$all_subcategory=fn_get_subcategories($id);
foreach($all_subcategory as $value){
$sub_cat[$value['category_id']]=$value['category'];
}
header('Content-Type: application/json');
echo json_encode($sub_cat);
exit;
}
TPL
function fun(){
$.ajax({
url: Tygh.index_script+"?dispatch=drill.drill",
data: { variable: '123' },
type: "GET",
success: function(categories) {
for(var category_id in categories){
console.log(category_id+' > '+categories[category_id]);
}
}
});
}
Results
I hope that helps,
I have checked around, but can't seem to figure out how this is done.
I would like to send form data to PHP to have it processed and inserted into a database (this is working).
Then I would like to send a variable ($selected_moid) back from PHP to a JavaScript function (the same one if possible) so that it can be used again.
function submit_data() {
"use strict";
$.post('insert.php', $('#formName').formSerialize());
$.get('add_host.cgi?moid='.$selected_moid.');
}
Here is my latest attempt, but still getting errors:
PHP:
$get_moid = "
SELECT ID FROM nagios.view_all_monitored_objects
WHERE CoID='$company'
AND MoTypeID='$type'
AND MoName='$name'
AND DNS='$name.$selected_shortname.mon'
AND IP='$ip'
";
while($MonitoredObjectID = mysql_fetch_row($get_moid)){
//Sets MonitoredObjectID for added/edited device.
$Response = $MonitoredObjectID;
if ($logon_choice = '1') {
$Response = $Response'&'$logon_id;
$Response = $Response'&'$logon_pwd;
}
}
echo json_encode($response);
JS:
function submit_data(action, formName) {
"use strict";
$.ajax({
cache: false,
type: 'POST',
url: 'library/plugins/' + action + '.php',
data: $('#' + formName).serialize(),
success: function (response) {
// PROCESS DATA HERE
var resp = $.parseJSON(response);
$.get('/nagios/cgi-bin/add_host.cgi', {moid: resp });
alert('success!');
},
error: function (response) {
//PROCESS HERE FOR FAILURE
alert('failure 'response);
}
});
}
I am going out on a limb on this since your question is not 100% clear. First of all, Javascript AJAX calls are asynchronous, meaning both the $.get and $.post will be call almost simultaneously.
If you are trying to get the response from one and using it in a second call, then you need to nest them in the success function. Since you are using jQuery, take a look at their API to see the arguments your AJAX call can handle (http://api.jquery.com/jQuery.post/)
$.post('insert.php', $('#formName').formSerialize(),function(data){
$.get('add_host.cgi?moid='+data);
});
In your PHP script, after you have updated the database and everything, just echo the data want. Javascript will take the text and put it in the data variable in the success function.
You need to use a callback function to get the returned value.
function submit_data(action, formName) {
"use strict";
$.post('insert.php', $('#' + formName).formSerialize(), function (selected_moid) {
$.get('add_host.cgi', {moid: selected_moid });
});
}
$("ID OF THE SUBMIT BUTTON").click(function() {
$.ajax({
cache: false,
type: 'POST',
url: 'FILE IN HERE FOR PROCESSING',
data: $("ID HERE OF THE FORM").serialize(),
success: function(data) {
// PROCESS DATA HERE
},
error: function(data) {
//PROCESS HERE FOR FAILURE
}
});
return false; //This stops the Button from Actually Preforming
});
Now for the Php
<?php
start_session(); <-- This will make it share the same Session Princables
//error check and soforth use $_POST[] to get everything
$Response = array('success'=>true, 'VAR'=>'DATA'); <--- Success
$Response = array('success'=>false, 'VAR'=>'DATA'); <--- fails
echo json_encode($Response);
?>
I forgot to Mention, this is using JavaScript/jQuery, and ajax to do this.
Example of this as a Function
Var Form_Data = THIS IS THE DATA OF THE FORM;
function YOUR FUNCTION HERE(VARS HERE) {
$.ajax({
cache: false,
type: 'POST',
url: 'FILE IN HERE FOR PROCESSING',
data:Form_Data.serialize(),
success: function(data) {
// PROCESS DATA HERE
},
error: function(data) {
//PROCESS HERE FOR FAILURE
}
});
}
Now you could use this as the Button Click which would also function :3
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 10 years ago.
Trying to run a script, (test.al();) and inside test.al, its called getcrypt.php();, the php script is on a webserver, and it is working. Currently, these are my scripts
JS
var getcrypt = {
php: function () {
$.ajax({
url: "server.com/return.php",
type: "POST",
async: true,
data: "id=getit",
success: function (msg) {
var v = msg.match(/^.*$/m)[0];
return v;
}
});
}
}
var test = {
al: function () {
a = getcrypt.php();
alert(a);
}
}
PHP
<?php
$id = $_POST['id'];
if ('getit' == $id){
$value = 'VALUE';
echo $value;
}else{
echo 0;
}
?>
In this way, it will show an alert with 'unidefined', and if i add a alert(v); right before return v, it will show me 'VALUE', but not able to use it outside the variable...
var getcrypt = {
php: function () {
$.ajax({
url: "server.com/return.php",
type: "POST",
async: true,
data: "id=getit",
success: function (msg) {
var v = msg.match(/^.*$/m)[0];
alert(v);
return v;
}
});
}
}
This will give me an alert with the correct value (AFTER THE 'undefined')
This is because of the asynchronous call you're making. The return is only for the success function and not for the php function.
To get the value out you would need to write:
var value;
var getcrypt = {
php: function (callback) {
$.ajax({
url: "",
type: "POST",
async: true,
data: "id=getit",
success: function (msg) {
var v = msg.match(/^.*$/m)[0];
alert(v);
callback(v);
}
});
}
}
getcrypt.php(function(v) {
alert(v);
// This happens later than the below
value = v;
});
// The below will still not work since execution has already passed this place
// alert will still return undefined
alert(value);
The problem is jQuery ajax works with callbacks and does not work with return value's so you need to add an callback to your getcrypt function so say
var getcrypt = {
php: function (callback) {
$.ajax({
url: "server.com/return.php",
type: "POST",
async: true,
data: "id=getit",
success: function (msg) {
var v = msg.match(/^.*$/m)[0];
callback(v);
}
});
}
}
so now if you call
getcrypt.php(function(returnVar){
alert(returnVar)
});
you will get an alert with VALUE
$.ajax returns immidiately (well, almost :)) upon calling, before the response is received. You should rewrite your code to accomodate to this fact, something like this;
var getcrypt = {
php: function(){
$.ajax({
//..other params ..//
success: function(msg){
var v = msg.match(/^.*$/m)[0];
alertResponse(v);
}
});
},
alertResponse: function(processedResponse) {
alert(v);
}
}
var test = {
al: function(){
getcrypt.php();
}
}
If you need your response in test object, you move alertResponse to that object and call it from success method. I think this tutorial might be useful for you to learn javascript event-driven programming model.
$.ajax calls are async. So what you get is the return value of $.ajax (when the request is sent, before a response is received). It is only when the browser receives a response to the ajax call that the success callback is run, as a seerate process from the $.ajax call. In other words the return value of $.ajax will always be null. I'm not sure it's possible to do anythging with the return value of the success callback, you need to put your logic (or a call to another function with the logic) in the success callback itself, in the same way you did with the alert in your final example