I've just started writing code with this framework. I have a big problem after adding this code to my View file (to add AJAX support for the form):
echo $this->Js->submit('Send',array(
'before'=> $this->Js->get('#success')->effect('fadeOut'),
'success'=>$this->Js->get('#success')->effect('fadeIn'),
'update'=>'#success'
));
Every time I refresh the page, Cakephp creates a file named {hash}.js like 987276be3fa726db322142ee6dfee435.js What's more, every refresh takes around 5s.
So after a few hours of work I had over 200 files in /webroot/js.
Every file contains code like this:
$(document).ready(function () {$("#submit-1856995147").bind("click", function (event) {$.ajax({beforeSend:function (XMLHttpRequest) {$("#success").fadeOut();}, data:$("#submit-1856995147").closest("form").serialize(), dataType:"html", success:function (data, textStatus) {$("#success").fadeIn();$("#success").html(data);}, type:"post", url:"\/newapp\/Sender"});
return false;});});
Do you know how to solve this?
try
core.php(inside /app/config/) has lot of features that help us improve our web application.
Configure::write(‘Asset.timestamp’, ‘force’);
This will helpful for you.
Related
In my project I have rows of modules loaded from Partial views.
So imagine a grid of small squares with information.
There is a popup dialog for all of them, that displays the data of the clicked module.
Currently when I submit a change in the dialog, the javascript reloads the entire page. BUT, this takes a long time, and I need to be able to refresh only the one dialog.
I can imagine to make a separate js function for each type of module, and then pass some data in, so jquery can find the specific module, and then make an ajax get, for the data. But this requires me to do all the data insertion from js always. instead of using razor and MVC's built in awesomeness.
Does anyone know of a way, to call a partial view inside a div?
Also in the future I will need to reload "some" but not all the modules in an interval refresh. So for future proofing purposes:
What im looking for is something like:
function reloadElement(row, column, id){
var target = $("#div1");
// todo find row and column
target.html.partial("url", model); //<----- looking for something like this. cross fingers.
}
Thanks to GregH for a few key words, that lead to some ideas.
I solved it myself, so if you land on this problem also, here is how i solved it:
Controller:
You want to make your controller return PartialView("somePartialViewUrl", new SomeModel()), apparently saving the model and relying on the data collection isn't good enough, i hadto make a new instance of the model.
Javascript
in the "click" that handles the event, put:
$.ajax({
url: "controllerName/actionName",
data: JSON.stringify({ row:1,column:2 .... }),
contentType: "application/json",
dataType: "html",
type: "POST",
success: function (partial) {
$("#div2").html(partial);
}
});
this will override the html in your "#div2".
im sure you can also use $("#div2").innerHTML = partial; or $("#div2").load("url",parameters); and probably many other ways.
done.
I'm developing a rather simple plugin using the Wordpress Plugin Boilerplate. Utilizing AJAX, I set up a action based upon a button press that's supposed to remove an item from the custom database table I set up. The AJAX works, the button works, the call to the operating PHP file works.
However, when I get to the operating PHP file where some simple database manipulation is supposed to take place, nothing happens. The file at this point consists of:
global $wpdb;
$table_name['database_name'] = $wpdb->prefix . 'database_name';
echo var_dump($wpdb);
echo var_dump($table_name);
echo var_dump($wpdb->prefix);
That's it right now. And these var dumps come back as "NULL," "database_name", and "NULL."
What am I doing wrong here? In the few others files involved in this project everything works fine. What did I break? If it's an AJAX thing and Wordpress handles AJAX differently, I'd love to see a good tutorial for it, because the few I've found that handle Wordpress AJAX explicitly have been outdated and/or broken.
it means you are calling $wpdb even before wordpress can initialize it, or you're doing something even more weirder
it can be done something like this,
jquery
$('body').on('click', '.some-click-handler', function() {
$.ajax({
type: 'POST',
url: ajaxurl,
data: {'action':'test_ajax'},
success: function(data) {
console.log(data);
},
error: function(errorThrown) {
console.log(errorThrown);
},
});
});
your php ajax handler, though you should add more security like nonce
//wp_ajax_nopriv for non logged-in user
add_action('wp_ajax_test_ajax', function() {
global $wpdb;
wp_send_json( $wpdb );
});
checkout wordpress ajax docs https://codex.wordpress.org/Plugin_API/Action_Reference/wp_ajax_(action)
Apologies if this particular question has been solved before, I have looked everywhere it seems and can't quite get the answer I'm looking for! I am no expert and can imagine the solution is embarrassingly easy.
My problem is this: I have some php and javascript code working on a html based website, linked to a database (reading data in and also writing data out via a save function called once at the end of the script). I need the javascript code to automatically save/update itself to db via an Ajax request, without the need to keep running the page. The data being saved here needs to be read by various other pages and is relied upon to give correct results elsewhere! (so a solution would be to have the user keep the page open in the background - but suggestions for this separate issue are also welcome!)
Anyway, at the moment I have:
function sessionSave () {
var newData = kpiCA.getData().concat(kpiHA.getData(),kpiStocks.getData(),kpiCV.getData(),kpiPD.getData());
$.ajax({
url: 'saveMain.php',
type: 'POST',
data: {'kpi': newData},
success: function () {
},
error: function () {
$console.text('Data Save Error');
}
});
}
sessionSave();
I have seen some autosave scripts and the addition of timers etc. but as I am a complete noob, some help would be much appreciated,
Thanks guys!
Basically it's just timers or intervals. For example:
window.setInterval(sessionSave, NUMBER_OF_SECONDS * 1000)
// where NUMBER_OF_SECONDS is, obviously, the number of seconds to repeat your function at
Environment:
Windows 8
Apache 2.4
ZF 1.12
PHP 5.4
YUI framework for the behind-the-scenes connection to the server
I am trying to carry out a very simple ajax/js combination where the user interacts with:
2 of 4 people found this review helpful. Was this review helpful to you? Yes No
When the user hits either yes/no the 2 of 4 should be updated through ajax/js. I have the following code in the init() method of my ReviewController (extends Zend_Controller_Action). Mind you, the view script that follows this action (feedbackAction) is /views/scripts/review/feedback.json.phtml
$ajaxContext = $this->_helper->getHelper('AjaxContext');
$ajaxContext->addActionContext('feedback', 'json')
->initContext();
When feedbackAction is executed an exception jumps out stating that it could not find feedback.phtml. This is telling me that AjaxContext is not, in effect, appending the "json" format. Why is this happening?
I read somewhere that the initContext() should be called inside the action. I tried it...same exception.
Then I tried using ContextSwitch, but it seems that it beats the purpose of having AjaxContext be a subclass of ContextSwitch. The code in the init() in ReviewController was replaced by:
$contextSwitch = $this->_helper->getHelper('contextSwitch');
$contextSwitch->addActionContext('feedback', 'json')
->initContext();
This time, inexplicably, the exception does not occur, but instead the following is rendered: the header code (generated by my _header.phtml file called by my layout.phtml file). I don´t understand at all. I had understood (obviously not well) that "addActionContext"+initContext() DISABLED layouts if any was enabled. ¿?
EDIT
I figured out that it wasn´t html content form my _header.phtml file but from another .phtml file that was being rendered because of some actions I had added to my actionStack. Once this was taken care of, what was rendered was the following:
{"originalModule":"default","originalController":"review","originalAction":"feedback","result":true,"id":1,"helpful_yes":"3","helpful_total":"4"}
Which is the variables placed in the $this->view being rendered as json thanks to ContextSwitch helper initiated at the init() method of my ReviewController(). When I say "this was rendred" is because I placed in the address bar the following url: http://localhost/PlacesforKids/public/review/feedback/format/json/id/1/helpful/1
which supposedly is the URL being sent by the YUI framework.
I say "supposedly" because in my javascript success function (being called back by the YUI framework when the ajax call is being executed successfully) I do the fowlling: alert(response), to print out the responce I am getting...and it prints out the whole shabang: html tags, headers...etc. I don´t know how that´s possible.
I thought then that I might be misusing the YUI framework, so I tried to change to jquery.js. To do so I copied the contect of this to a file named jquery.js and placed it under my /public/js directory. Here is the ajax call it´s making to the server:
$.ajax({
url: sUrl,//that would be
//localhost/PlacesforKids/public/review/feedback/format/json/id/$id/helpful/$helpful
type: "GET",
async: false,
success: function(response){
alert(response);
}
});
Here is the HILARIOUS part of all, the action for my ReviewController is NOT being called whatsoever. Instead, the view that was last rendered is re-rendered, meaning it´s re sending the content generated by the view script called by the last action (which belongs to a different controller than ReviewController). I know it´s been re-rendered because in the action that´s the owner of that view script I added this:
if($this->getRequest()->getQuery('ajax') == 1)
throw new Exception ("WRONG controller's action being called");
But it never throws the exception.
EDIT I THINK I GOT IT but I need to know how to clean the baseUrl()
So I opened up the java console on my chrome browser so I could look up the actual http request that my reviewFeedback.js was making through the $.ajax() method. Funny thing, this is what I got:
Request URL:http://localhost/PlacesforKids/public/place/index/id/localhost/PlaceforKids/public/review/feedback/format/json/id/1/helpful/0
Request Method:GET
Status Code:200 OK
Accept:*/*
Referer:http://localhost/PlacesforKids/public/place/index/id/1
X-Requested-With:XMLHttpRequest
WHY in the world is $ajax() APPENDING the url I have as GET to the EXISTING url? It means that whatever url I am trying to generate through my $.ajax() is gettign APPENDED to my "referer". So, I only need to be to CLEAN it and start from zero, for the url I mean... How could I do that in zend framework? Any ideas?
Now if I enter the string in sUrl (localhost/PlaceforKids/public/review/feedback/format/json/id/1/helpful/0) directly onto the address bar in my broswer, it does as it is supposed to do, print out the variables in $this->view that have been set by ReviewController, and send them as json.
{"originalModule":"default","originalController":"review","originalAction":"feedback","result":true,"id":1,"helpful_yes":"3","helpful_total":"4"}
Same problem I had with YUI framework. I´m going crazy.
I could really use the help, thank you.
You need to change the ajax request to asynchronous mode: async: true
Silly silly silly me. Here is the reason why $.ajax() was appending the made up url instead of sending a new one.
$.ajax({
url: sUrl,//that would be
//localhost/PlacesforKids/public/review/feedback/format/json/id/$id/helpful/$helpful
type: "GET",
async: false,
success: function(response){
alert(response);
}
I was writing a GET without a leading "http://", which by default, caused it to append to the existing url.
sUrl was localhost/PlacesforKids/public/review/feedback/format/json/id/$id/helpful/$helpful
and should have been http://localhost/PlacesforKids/public...
Though it still baffles me that ajaxContext did not stop layout rendering as it should have, making me use switchContext instead.
The ajax switch in zend 1.1x.x is only for the "special" html context (if memory serves) and you were trying to set it to a json context.
How can I fix the script below so that it will work EVERY TIME! Sometimes it works and sometimes it doesn't. Pro JQuery explains what causes this, but it doesn't talk about how to fix it. I am almost positive it has to do with the ajax ready state but I have no clue how to write it. The web shows about 99 different ways to write ajax and JQuery, its a bit overwhelming.
My goal is to create an HTML shell that can be filled with text from server based text files. For example: Let's say there is a text file on the server named AG and its contents is PF: PF-01, PF-02, PF-03, etc.. I want to pull this information and populate the HTML DOM before it is seen by the user. A was ##!#$*& golden with PHP, then found out my host has fopen() shut off. So here I am.
Thanks for you help.
JS - plantSeed.js
var pageExecute = {
fileContents:"Null",
pagePrefix:"Null",
slides:"Null",
init:function () {
$.ajax({
url: "./seeds/Ag.txt",
success: function (data){
pageExecute.fileContents = data;
}
});
}
};
HTML - HEAD
<script type="text/javascript">
pageExecute.init();
</script>
HTML - BODY
<script type="text/javascript"> alert(pageExecute.fileContents); </script>
Try this:
var pageExecute = {
fileContents:"Null",
pagePrefix:"Null",
slides:"Null",
init: function () {
$.ajax({
url: "./seeds/Ag.txt",
async: false,
success: function (data){
pageExecute.fileContents = data;
}
});
}
};
Try this:
HTML:
<div id="target"></div>
JavaScript:
$(function(){
$( "#target" ).load( "pathToYourFile" );
});
In my example, the div will be filled with the file contents. Take a look at jQuery .load() function.
The "pathToYourFile" cand be any resource that contains the data you want to be loaded. Take a look at the load method documentation for more information about how to use it.
Edit: Other examples to get the value to be manipulated
Using $.get() function:
$(function(){
$.get( "pathToYourFile", function( data ) {
var resourceContent = data; // can be a global variable too...
// process the content...
});
});
Using $.ajax() function:
$(function(){
$.ajax({
url: "pathToYourFile",
async: false, // asynchronous request? (synchronous requests are discouraged...)
cache: false, // with this, you can force the browser to not make cache of the retrieved data
dataType: "text", // jQuery will infer this, but you can set explicitly
success: function( data, textStatus, jqXHR ) {
var resourceContent = data; // can be a global variable too...
// process the content...
}
});
});
It is important to note that:
$(function(){
// code...
});
Is the same as:
$(document).ready(function(){
// code
});
And normally you need to use this syntax, since you would want that the DOM is ready to execute your JavaScript code.
Here's your issue:
You've got a script tag in the body, which is asking for the AJAX data.
Even if you were asking it to write the data to your shell, and not just spout it...
...that's your #1 issue.
Here's why:
AJAX is asynchronous.
Okay, we know that already, but what does that mean?
Well, it means that it's going to go to the server and ask for the file.
The server is going to go looking, and send it back. Then your computer is going to download the contents. When the contents are 100% downloaded, they'll be available to use.
...thing is...
Your program isn't waiting for that to happen.
It's telling the server to take its time, and in the meantime it's going to keep doing what it's doing, and it's not going to think about the contents again, until it gets a call from the server.
Well, browsers are really freakin' fast when it comes to rendering HTML.
Servers are really freakin' fast at serving static (plain-text/img/css/js) files, too.
So now you're in a race.
Which will happen first?
Will the server call back with the text, or will the browser hit the script tag that asks for the file contents?
Whichever one wins on that refresh is the one that will happen.
So how do you get around that?
Callbacks.
Callbacks are a different way of thinking.
In JavaScript, you perform a callback by giving the AJAX call a function to use, when the download is complete.
It'd be like calling somebody from a work-line, and saying: dial THIS extension to reach me, when you have an answer for me.
In jQuery, you'll use a parameter called "success" in the AJAX call.
Make success : function (data) { doSomething(data); } a part of that object that you're passing into the AJAX call.
When the file downloads, as soon as it downloads, jQuery will pass the results into the success function you gave it, which will do whatever it's made to do, or call whatever functions it was made to call.
Give it a try. It sure beats racing to see which downloads first.
I recommend not to use url: "./seeds/Ag.txt",, to target a file directly. Instead, use a server side script llike PHP to open the file and return the data, either in plane format or in JSON format.
You may find a tutorial to open files here: http://www.tizag.com/phpT/fileread.php