yii Ajax link not working - ajax

I put a Ajax link using the following code:
echo chtml::ajaxLink('GO', 'http://localhost/index.php?r=user/delete', array('method'=>'POST'));
But, regardless of giving the second parameter as URL i,e 'http://localhost/index.php?r=user/delete'. It generates link with the current URL in the browser not the URL I just specified.
What is the issue? How could I create AJAX link? Google several hours but can't solve the issue.
Any kind of help is highly appreciated.

First of all, you should always try and create normalized urls.
But i think your doubt lies in the # that is generated/appended. If you go and check the source of yii ajaxLink you'll see this:
public static function ajaxLink($text,$url,$ajaxOptions=array(),$htmlOptions=array())
{
if(!isset($htmlOptions['href']))
$htmlOptions['href']='#';
$ajaxOptions['url']=$url;
$htmlOptions['ajax']=$ajaxOptions;
self::clientChange('click',$htmlOptions);
return self::tag('a',$htmlOptions,$text);
}
so if you don't set the href property of the a tag in the htmloptions array, the # will be appended.
You should also understand that yii uses jquery, so if you check out the source of the page, you'll see at the bottom, how jquery is used to carry out an ajax request, your actual url that is called will also be seen in that script. So the third option/parameter in ajaxLink is for options for jquery's ajax function. You can create better ajax links using this option.
Regardless of where(which controller) your url points to in your project, the action associated with that url will be called.
So anyway, you can modify your code like this if you want the url to be shown and not a # :
echo CHtml::ajaxLink('GO', 'http://localhost/index.php?r=user/delete',
array('type'=>POST), //there are various other options for jquery ajax
array('href'=>'http://localhost/index.php?r=user/delete'));
To make better ajax links i would suggest going through jquery's ajax documentation. There is an option for a success function, that you can use to let the user know that the operation was completed.
Hope this helps, don't hesitate to leave comments if i haven't answered your question completely.

Have you tried:
echo CHtml::ajaxLink('GO', array('/user/delete'), array('method'=>'POST'));
as the ajaxLink documentation suggests...? Look also at the normalizeUrl method.
Using these methods, which in turn are using createUrl, is usually better since it will take care to create a valid url for your site.

I had the same issue(or maybe similar).
I've used renderPartial to load view and later in that view i was using ajaxLink and it was not working.
What i have found, that when using renderPartial, there was no jquery script for ajax action.
What you have to do is to add 4th argument(true) in renderPartial function to generate jquery script.
See the documentation: http://www.yiiframework.com/doc/api/1.1/CController/#renderPartial-detail
Hope it helps and saves time to figure it out.

Related

RedirectToAction MVC 3 after $.ajax call

From my view I am sending via $.ajax a JSON object to my controller to save it in the database.
If all succeeded i want to redirect to another action which will show a diferent view.
If i use this code:
return RedirectToAction("CreatePage", "Survey", new {id = question.PageId});
The execution goes to the Survey controller which returns a view but it is not shown.
I have read some post which said that it is not posible to redirect via ajax.
The solution I use so far is to redirect via javascript like this:
success: function (ret) {
window.location.href = "/Survey/CreatePage/" + $("#PageId").val();
}
Although this always works, sometimes i need to refresh the CreatePage view to show the last changes made.
Any idea of how to solve this problem better?
Thanks in advance
As mccow002 suggested, I wasn't really needing to make the call via AJAX for that part. After studying the solutions suggested, i realized that i could simple submit it in a form. My confusion came because I have a save and continue editing and a save. For the save and continue I use the AJAX call, but for the save option with the form being submitted is ok.
Thanks very much for your help.
Instead of redirecting to a new page, you can send a rendered html from .net code back to client and load that html in page, like this $("#main").load(renderedHtml).
But for refreshing the page you can write a simple script that run at specified intervals and refresh the page contens.
You could use [OutputCache] on the CreatePage action so that it doesn't cache the page or only caches for so long.
output caching

how to get information from php without refreshing the page

hi
sorry for the bad title but I'm not 100% sure what I need for this problem
I created a welcome page and then when you click on links you get more information, for example:
Click Me
And then the php would get the information based on the id.
so the information received is reloaded on the page after the pages refreshes
what I would like to be able to do is when user clicks on the link, use jquery to not allow the link to run but still run the url in the background (without refreshing the page)
I have no idea where to start from so I really hope you could help
thanks
In a nutshell, it's called Ajax: sending an HTTP request to your server through javaScript, and receiving a response which can contain results, data, or other information.
You mention jQuery, here are the docs about that:
http://api.jquery.com/jQuery.get/
http://api.jquery.com/jQuery.post/
are convenience methods, which encapsulate $.ajax with preset options.
http://api.jquery.com/category/ajax/ is an overview of the whole system in jQuery.
The basics go like
//include jquery, etc.
$(document).ready(function(){
$('#some_element').click(function(){
$.get('some_url_on_your_server.php',{'data':'whatever params'},function(data){
do_something();//
},'json');
});
This will bind an element to make an Ajax call on click, and then you use the function ('success' function, in $.ajax) to handle the json data.
Have your server send back the data in JSON by using json_encode in php. Be sure to send the right header back, like
<?php
header('Content-Type: application/json');
echo json_encode($some_array);
exit;
There's a lot of resources on the web and SO for learning about Ajax, it's a big topic. Best of luck.
Make a JavaScript function, like sendData(linkId) and then each tag would have an onclick event called sendData(this). SendData(linkId) can then do an HTTPRequest (also known as an asynchronous or AJAX request) to a php file, let's call it handler.php, which receives GET or POST methods. I prefer using the prototype framework to do this kind of thing (you can get it at prototypejs.org).
Okay, now that I have said all that, let's look into the nitty-gritty of how to do this (way simplified for illustrative purposes).
Download the prototype script, save it on your server (like prototype/prototype.js, for example) and then put somewhere in your html <script type='text/javascript' language='Javascript' src='prototype/prototype.js'></script>
Your tags would look like this:<a id='exampleLink' onclick = 'sendData(this)'>Click me!</a>
You need JavaScript to do this: function sendData(tagId){
var url = 'handler.php?' + 'id=' + tagId;
var request = new AJAX.Request(url, {method = 'get'});
}
Finally, you need a php file (let's call it handler.php) that has the following: <?php
$tag_to_get = $_GET['tagId'];
do_a_php_function($tag_to_get);
?>
That's it in a nutshell, but it's worth mentioning that you should give your user some sort of feedback that clicking link did something. Otherwise he will click the link furiously waiting for something to happen, when it is actually doing just what its supposed to but in secret. You do that by making your php script echo something at the end, like 'Success!', and then add an onSuccess parameter to your JavaScript's new Ajax.Request. I'll let you read how to do that on your own because the prototype website explains how to receive a response from the handler and put the feedback somewhere in your HTML without making the user refresh.
you can achieve that behavior with a jquery function called $.get ... you can get more information on how to use here http://api.jquery.com/jQuery.get/
If you really want to (and I don't think you really do), you can use XMLHTTPRequest (wrapped in jQuery.get) to facilitate loading content into the page without page refreshing. You want an id or class on that tag, i.e. Click Me, and then:
<script>
$(".fetch").bind("click", function(evt)
{
$.get(this.attr("href"), function(data)
{
$("#whereIWantMyContent").html(data);
});
evt.preventDefault();
});
</script>
I would recommend you use AJAX to start with. A good place to being is http://www.w3schools.com/Ajax/Default.Asp
The link comes with a handy AJAX ASP/PHP Example too =))
Good Luck.

CodeIgniter jQueryUI dialog form example

I am trying to use CodeIgniter and jQuery-ui dialog to create a modal window with form to update user information.
The process should be like:
1. Press a button on a view page.
2. A modal window pops up.
3. Inside the window is a form that a user can fill.
4. If the user filled something before, the information should be shown in corresponding field
5. Click the update button on the modal window to save the changes to database.
Can anyone provide a good sample of this process?
I used ajax to pass the data but it didn't work when I was trying to update the data to the database. It would be nice if an example of how to pass data from ajax to php and how php handle that.
Thanks,
Milo
well the jquery bit for post(), get(), ajax() works the same in any measure you would normally use it.. key difference here is with CI you can't post directly to a file-name file-location due to how it handles the URI requests. That said your post URL would be the similar to how you would access a view file normally otherwise
ie: /viewName/functionName (how you've done it with controllers to view all along. post, get, ajax doesnt have to end in a extension. I wish I had a better example then this but I can't seem to find one at the moment..
url = '/home/specialFunction';
jQuery.get(url, function(data) {
jQuery("#div2display").html(data);
});
in the case of the above you notice despite it not being a great example that. you have the url with 2 parameters home and specialFunction
home in this case is the controller file for home in the control folder for the home file in views the specialFunction is a "public function" within the class that makes the home controller file. similar to that of index() but a separate function all together. Best way I have found to handle it is through .post() and a callback output expected in JSON cause you can form an array of data on the php side json_encode it and echo out that json_encode and then work with that like you would any JSON output. or if your just expecting a sinlge output and not multiples echoing it out is fine but enough of the end run output thats for you to decide with what your comfortable doing currently. Hopefully all around though this gives you some clairity and hopefully it works out for you.

How can I add a URL parameter but hide others in a POST - Spring MVC

I'm trying to add a URL parameter within a Spring MVC application. It's a basic search page that shows results.
In the search page, there is a form that is set to POST. There are many hidden fields and other fields I don't want in the URL. So, I don't want to do a GET.
I do want the search query in the URL. So after clicking the search button, the resulting search results page needs to have a URL like /search?query=hello
To get it to work, I'm creating a RequestMapping method in the Spring MVC Controller and doing a redirect: tacking on the query parameter. However, I'm not sure using a redirect is the best answer, seems there could be performance concerns redirecting as well.
I looked around and noticed folks using javascript and the location object, but setting the location object obviously relaunches the URL you set it to. I also looked at the HTTPServletResponse & HTTPServletRequest objects, but couldn't find much.
Any thoughts on how I can force the search parameter to be added to the URL?
Your form will have an 'action' specified telling it where to POST to. I'd have thought you could attach an onclick event to your submit button (or an onsubmit event to your form) that updates the action url by appending "?query=" to it.
document.<form name>.action += "?query=...";
Then you just have to worry about someone posting your form without JavaScript enabled - in this case you could fall back to your redirect.
I don't know how the server technology so I can't say if it will be happy giving you both GET and POST parameters, if not you'll have to manually strip the GETs out of the URL.
But anyway, this seems like a rather odd situation to be in - is it really that big a deal to show the parameters in the URL? Anything that gets posted by an HTML form can still be inspected with the right tools, it's just ever so slightly more difficult.
I wanted to provide a more complete answer to my question with code. The previous user helped me down this path, so I'll keep it as the accepted answer. However, there is one item to note:
If you add on to the action, and you have an input text box with the same name, the page posts a duplicate value like: query=hello,hello.
So, I needed to remove the name on the input box, and use the following javascript. Note, I am using the prototype.js framework:
Event.observe(window, 'load', function(event) {
Event.observe('searchForm', 'submit', function(event) {
$('searchForm').action += "?query="+$('searchBox').value;
});

update the row using ajax in cakephp

i am using cakephp in my project. in this at one section i need to update the particular row onclick of the image. using ajax. i used mootools as javascript library. so please help me how could i do this.
thanks in advance
Simply speaking:
Create a CakePHP controller action that performs the row update.
Determine the URL of the controller action you just created. (ie. /controllername/actionname)
Determine if you need to do a GET or POST request to this URL for it to work.
Put code in your view that attaches an "onclick" event that makes and AJAX (GET/POST) request to the above controller.
CakePHP has a javascript helper that traditionally produced Prototype code, but in v1.3 it is now able to produce code for other Javascript frameworks (such as Mootools, jQuery, etc.)
However, many suggest writing your javascript in javascript (eg. actually using the Mootools framwork), rather than writing your javascript in PHP (like using CakePHP's helper to produce Mootools code).
Either way, in your view you need to have something like: <?php echo $js->link(.. or <script>Moo.. or <a onclick="Moo.. to attach your Javascript to that link.
You may also wish for your controller action to return some sort of response indicating whether or not the row update failed or succeeded. In that case you need to make sure the CakePHP controller action you are calling has a view that outputs this. JSON seems to be the ideal format for this (eg. { success: true }), but you need to remember to turn off Cake's debug output. This response can be captured into a variable by your Mootools code where you can decide what to do with it (eg. displaying an error).
As i know most programmer work with protype.js library.
i am giving you link see
go to there

Resources