I have select box with menu(id,name) and I have another select box category(cid, cname) and it must show only category based on the menu selected by setting the menuid to "url".
Here is my code:
http://jsfiddle.net/L8su2/738/
echo $this->Form->create('Subcategorynew');
echo $this->Form->input('menu_id', array('empty'=>'--Select--','label'=>'Menu','type'=>'select','options'=>$menunew, 'div' => false, 'id' => 'prodid', 'onchange' => 'test()', 'class' => 'form-control'));
echo "</br>";
echo $this->Form->input('category_id', array('type'=>'select','label'=>'Category', 'div' => false, 'id' => 'total','options'=>$catnew, 'class' => 'form-control'));
echo "</br>";
First, you should add an error trigger to see what happens. AJAX is based on JSON and you are sending HTML code. Then you HAVE to change the data type. Finally, to do it easier, you can use $.get() and $.post() to be sure the way data is coming.
error: console.log,
dataType : 'html',
It should be something like this to test. Results are in your developpement console like in Chrome or Firefox
$.post({
url: "<?=$this->webroot?>admin/subcategorynew/add/"+prodid,
data: data,
error: console.log,
success: console.log,
dataType: 'html'
});
or
$.get({
url: "<?=$this->webroot?>admin/subcategorynew/add/"+prodid,
data: data,
error: console.log,
success: console.log,
dataType: 'html'
});
To display data where we want, via JQuery
Set the callback
success: dataToProcess,
Create the callback
function dataToProcess(data, status){
// select your submenu via the ID
// $.html() will replace the current HTML data INTO the actual tag to the data you sended
$("#idSubMenu").html(data);
}
Related
Exact Problem and the Solution
Upon activating the CakePHP (3) Security Component, when loading a form, you generate three hidden fields in the form. These are '_Token[fields]', '_Token[unlocked]' and '_Token[debug]'. What exactly happens is the Form->end() method calls the secure() method (see FormHelper) when the request data contains a ['Token'] parameter.
The forms that were not working for me were all forms rendered as an Element. For these forms, the '$this->request->params' did not contain the parameter normally generated by the Security Component.
Solution was in manually adding the parameter to the request data..
$this->request->params['_Token'] = ['unlockedFields' => []];
This than runs through the secure() method of FormHelper, as it should, and token parameters are correctly added.
Original Question
I have an issue using the SecurityComponent of CakePHP 3.8.
Everything was working fine, until I loaded Component in my AppController.
$this->loadComponent('Security');
Upon clicking a button I make an ajax call.
var csrf_token = <?php echo json_encode($this->request->getParam('_csrfToken')) ?>;
var checkouturl = "<?php echo $this->Url->build('/orders/checkout', true) ?>";
var test = "test";
$("#checkout").click(function() {
$.ajax({
type: 'post',
url: checkouturl,
headers: {'X-CSRF-Token': csrf_token},
data: {data : test},
success: function(result){
console.log(result);
},
error: function (xhr, ajaxOptions, thrownError) {
console.log(xhr);
console.log(thrownError);
}
});
});
This call was working fine, now I get the following error message (400 bad request). Apparently using the Security Component checks for an additional token apart from the csrf-token.
'_Token' was not found in request data.
Can anyone explain what I can do about this? I only find information related to forms, but this is an ajax call. I would like to keep the Security Component enabled.
Example of a non-working form..
echo $this->Form->create($athlete, ['url' => ['controller' => 'Athletesux', 'action' => $action]]);
echo $this->Form->control('user_id', ['type' => 'hidden', 'value' => $userid]);
echo $this->Form->control('first_name');
echo $this->Form->control('last_name');
echo $this->Form->control('threek_time', ['value' => $athlete['3K_time']]);
echo $this->Form->control('fivek_time', ['value' => $athlete['5K_time']]);
echo $this->Form->control('tenk_time', ['value' => $athlete['10K_time']]);
echo $this->Form->select('country', $countryoptions);
echo $this->Form->select('gender', $gender);
echo $this->Form->button('Add Athlete');
echo $this->Form->end();
Thanks!
HTML Generated..
I have an input field that I'm turning into a jqueryUI autocomplete:
$( "#autocomplete" ).autocomplete({
autoFocus: true,
source: mylist
});
The mylist variable is just a string in the array format ['Value1','Value2,'Blah'] which i originally just hardcoded into the script.
Now I want the mylist variable to be the result of an ajax call to a function in my cakephp app. The function is basically as follows, it just grabs all the data as a list, and json encodes it.
public function source() {
$this->layout = 'ajax';
$countries=$this->Country->find('list',array('fields'=>'Country.country'));
ChromePhp::log($countries);
echo json_encode($countries);
}
This outputs:
{"1":"Afghanistan","2":"Albania ","3":"Algeria ","5..
My issue is getting the output of this function, (which ends up in the ajax success callback as 'data') into the correct format to place into the options array of the autocomplete.
I can get as far as console logging each value, but I'm stumped. Basically clutching at straws at the correct syntax.
$.ajax({
type: "GET",
dataType: "json",
url: "/source/",
success: function(data){
/*
magic array string creation code would go here instead of my code below...
*/
$.each(data, function(i, item) {
console.log(item);
});
console.log('data',data);
}
})
The autocomplete plugin can do a lot of the work for you if you give it things in the right format.
I would start by re-indexing the $countries variable to start from 0. You can use the array_values() function for that:
echo json_encode(array_values($countries));
This should give you the JSON in the format of:
['Afghanistan','Albania','Algeria',...]
Then you can change the source property in the autocomplete code to be a url for your source action.
$( "#autocomplete" ).autocomplete({
autoFocus: true,
source: "/your_controller/source"
});
The autocomplete plugin won't filter the results for you, instead a query string is added to the url with a term field (e.g. /your_controller/source?term=foo) so you need to modify your find() method to use this.
$countries = $this->Country->find('list', array(
'fields' => 'Country.country',
'conditions' => array(
'Country.country LIKE' => $this->request->query['term'] . '%'
)
));
You can read more about the different types the source option can accept in the autocomplete on the API Documentation.
I have a form, and when users submit this form, it should pass the data along to a function using AJAX. Then, the result of that is displayed to the user in a dialog box. I'm using CakePHP (1.3) and jQuery to try and accomplish this but I feel like I'm running into the ground.
The form will eventually be used for uploading images with tags, but for now I just want to see a message pop up in the box..
The form:
<?php
echo $this->Form->create('Image', array('type' => 'file', 'controller' => 'images',
'action' => 'upload', 'method' => 'post'));
echo $this->Form->input('Wallpaper', array('type' => 'file'));
echo $this->Form->input('Tags');
echo $this->Form->end('Upload!');
?>
The AJAX:
$(document).ready(function() {
$("#ImageUploadForm").submit(function() {
$.ajax({
type: "POST", url: "/images/upload/",
data: $(this).serialize(),
async: false,
success: function(html){
$("#dialog-modal").dialog({
$("#dialog-modal").append("<p>"+html+"</p>");
height: 140,
modal: true,
buttons: {
Ok: function() {
$(this).dialog('close');
}
}
})
}
});
return false;
});
});
NOTE: if I put $("#dialog-modal").dialog({ height: 140, modal: true }); OUTSIDE of the $.ajax but inside the $("#ImageUploadForm").submit(function() { and comment out the $.ajax stuff, I WILL see a dialog box pop up and then I have to click it for it to go away. After this, it will not forward to the location /images/upload/
The method that AJAX calls:
public function upload()
{
$this->autoRender = false;
if ($this->RequestHandler->isAjax())
{
echo 'Hi!';
exit();
}
}
$this->RequestHandler->isAjax() seems to do either absolutely nothing, or it is always returning false. I have never entered an if statement with that as the condition.
Thanks for all the help, if you need more information let me know.
Try this:
$(document).ready(function(){
$.ajax({
type: "POST", url: "/images/upload/",
data: $(this).serialize(),
async: false,
success: function(html){
//First you must append to div:
$("#dialog-modal").append("<p>"+html+"</p>");
$("#dialog-modal").dialog({
height: 140,
modal: true,
buttons: {
Ok: function() {
$(this).dialog('close');
}
}
}); //dialog
}//success
});//ajax
Note the first sentence:
$("#dialog-modal").append("<p>"+html+"</p>");
it can not be a propertie. You must pass an object as a parameter to dialog() function so properties or member of an object looks like:
{
height:140,
buttons:{},
anotherPropertie: 'value'
}
If you call to dialog() function after ajax(), the dialog will be empty because will execute before success() function declared inside ajax().
how i call javascript function in ajax callback function and how i can pass arguments to this javascript function like field name or something
'#ajax' => array(
'callback' => 'ajax_javascript_function',
'wrapper' => 'd-div-autocomplete-textfield-div',
'method' => 'replace',
'event' => 'blur',
'effect' => 'fade',
'progress' => array('type' => 'throbber', 'message' => ''),
),
You need to pass those variables to a server with javascript ajax JSONP. There are many ways, but here are 2 examples:
With plain querystring:
$.ajax({
type: "GET",
dataType: "jsonp",
url: "some.php?callback=mycallback",
data: "name=John&location=Boston",
success: function(response){
alert( "Data received: " + received);
},
error: function(e){
alert(e);
}
});
with object for querystring parameters
$.ajax({
type: "GET",
dataType: "jsonp",
url: "some.php?callback=mycallback",
data: {
"name" : "John",
"location" : "Boston"
}
success: function(response){
alert( "Data received: " + response );
},
error: function(e){
alert(e);
}
});
Your PHP code must output its response with the callback you asked for in this javascript (I used 'mycallback'). If you are not writing the PHP(or some kind of server side code) then that server must be agreeing to return responses wrapped with the callback function you asked for it to use. This way, the response gets into your javascript because you told it what function would be callable. This is called JSONP architecture. It works because the one thing that you can request Cross-Domain is a script.
PHP
echo "mycallback('" + $data + "');";
Good luck, read more here: http://api.jquery.com/jQuery.ajax/
I am trying to receive a json object back from php after sending data to the php file from the js file.
All I get is undefined.
Here are the contents of the php and js file.
data.php
<?php
$action = $_GET['user'];
$data = array( "first_name" => "Anthony",
"last_name" => "Garand",
"email" => "anthonygarand#gmail.com",
"password" => "changeme");
switch ($action) {
case 'anthonygarand#gmail.com':
echo $_GET['callback'] . '('. json_encode($data) . ');';
break;
}
?>
core.js
$(document).ready(function(){
$.ajax({ url: "data.php",
data: {"user":"anthonygarand#gmail.com"},
context: document.body,
data: "jsonp",
success: function(data){renderData(data);}
});
});
function renderData(data) {
document.write(data.first_name);
}
It looks like you have two data options set in the Ajax function. Instead of the line
data: "jsonp",
You need
dataType: "jsonp"
As you're not actually passing the PHP file any information.
Another couple of things, make sure you're getting valid JSON (jsonlint.com), we had a similar issue and it turned out we had the wrong kind of quotes.
Lastly: You MAY need to JSON.parse(data) to see convert it to an object at Javascript's end.