Using jQuery AJAX to Invoke Rails Server Method on Client Side - ajax

I am using Ruby on Rails, and I want to invoke a controller method as an onclick event of my pre-existing links.
I am using jQuery and AJAX to do the same. But I don't know much about AJAX.
Here is my code.
<script type="text/javascript">
$("a.browse_history").live("click", function()
{
alert("i am here");
$.ajax({
url: "/user_profile_controller.rb/save_user_history",
type: 'PUT'
});
});
</script>
In user_profile_controller.rb:
def save_user_history
$doc_list << "hello hi"
end
And my link is:
Click here
But this is not working..
Any solutions would be appreciated.

Your URL looks wrong. Run rake routes to get a list of existing routes in your app.
Should be something like
url: "/user_profile/save_user_history"
or
url: "/user_profiles/save_user_history"

Thank you for your reply Stefan.
I changed my code like this:
<script type="text/javascript">
function u_profile(user,url,query)
{
$.ajax({
type: 'POST' ,
url: "http://localhost:3000/user_profiles",
data : {
user_profile : {
user_id : user ,
query_term : query,
visited_url: url
}
} ,
success: function(data){
alert(data);
}
});
};
</script>
And i am invoking it as onclick event of link.
It full fills my requirement of creating an object in database with passed data.

Related

Vue JS Ajax Calls

I am trying to make the change from jQuery to Vue.js and am having some difficulty running an Ajax Call using vueresource. Below is a sample script I am using, with both jQuery and Vuejs. Both trying to access the same ajax call. The jQuery call works, the vuejs call doesn't. The sendAjax method is being called because the first 2 alerts show - then nothing.
Edit - this is only causing an error while running the Ajax call through Wordpress. Outside of WP, it does work. Any ideas??
<!DOCTYPE html>
<html>
<head>
<title>Vue Resource</title>
<script src="https://cdn.jsdelivr.net/npm/jquery#3.2.1/dist/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/vue/latest/vue.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vue-resource#1.5.1"></script>
</head>
<body>
<button id="jQueryAjax">Jquery AJAX</button>
<div id="myvue">
<button #click.prevent="sendAjax()">AJAX</button>
</div>
<script>
let AjaxUrl = "http://localhost:8888/mySite/wp-admin/admin-ajax.php";
const postData = { action: 'my_ajaxcall', function: 'AjaxTest' };
Vue.use(VueResource);
const ajax_app = new Vue({
el: '#myvue',
methods: {
sendAjax() {
alert("VueAjax");
alert(JSON.stringify(postData));
this.$http.post(AjaxUrl, postData).then(res => {
alert(JSON.stringify(res));
});
}
}
});
$("#jQueryAjax").click(function() {
alert("jQueryAjax");
alert(JSON.stringify(postData));
alert(AjaxUrl);
$.ajax({
type: 'POST',
url: AjaxUrl,
data: postData,
dataType: 'json',
success: function(data) {
alert(JSON.stringify(data));
},
error: function (xhr, ajaxOptions, thrownError) {
alert("Error");
}
});
});
</script>
</body>
</html>
You AJAX call probably encounters an error and you handle only the successful calls. Please extend your sendAjax function like this:
this.$http.post(AjaxUrl, postData).then(res => {
alert(JSON.stringify(res));
}, err => {
alert(err);
});
Now an error should be alerted.
BTW: It is better to use console.log() instead of alert(), it is much more readable and you won't have to confirm every alert.
After #mbuechmann pointing me to be able to see the actual error, I was able to determine that the issue I was having was actually to do with Wordpress. In order to use the Wordpress Ajax handler, you need to send an action to the REQUEST header. To do this, you need to send FormData, and without sending headers.
This code was found in this question : Custom Shortcode AJAX 400 Bad Request and enabled me to get my Fetch working with Wordpress.
var data = new FormData();
data.append( 'action', 'aj_ajax_demo' ); data.append( 'nonce', aj_ajax_demo.aj_demo_nonce );
fetch(aj_ajax_demo.ajax_url, {
method: 'POST',
body: data, }).then(response => {
if (response.ok) {
response.json().then(response => {
console.log(response);
});
} });

How to make a ajax request using post method

I made an ajax request using post method in django..its wokring perfectly..the problem is its calling the complete html page rahter than a div..i want to call only a div..i tried but unable to find the exact solution..
<script>
$(document).ready(function(){
$('#Category').change(function(event){
event.preventDefault();
var e = document.getElementById("Category");
var value = e.options[e.selectedIndex].value;
$.ajax({
url: "/charts/",
type: "post",
dataType: "html",
data: value,
success: function(data) {
$('#div1').html(data);
}});
return false;
});
});
</script>
I want only div content with id #div1..i already tried find and replace method
What is the nature of the event ? Is it a button ? an Input ?
If it is an input as <input type="submit">, the default action is to reload the page like a form.
Did you check if your div id is really div1?
$("#div1").append("your html code"+data+" your html code")

Why Does An AJAX Request Have To Have This?

<script type="text/javascript">
$(document).ready(function() {
$("button").click(function(){
$.ajax({
type: 'POST',
url: 'script.php',
success: function(data) {
alert(data);
$("p").text(data);
}
});
});
});
</script>
why does an AJAX request have to have a placeholder for the function? (in this case it is 'data'). If you remove it, or use any other word it still works fine. Can someone please explain why?
Your data here is an alias for returned value (the "answer" for your ajax request to script.php), so you can reefer to it. It is NOT the placeholder for function itself.
How you name it is up to you - just like with names of lambda parameters in c++ (I find them similar to JavaScript anonymous functions in that case):
[](string data){
... = data...
}
or with "out" parameters of functions/methods in other languages.
For the C++ analogy: how it would look to pass an lambda as a parameter to another method (you would have to define the Button class of course):
button.click(/*...,*/ [&](string data){ //"on success"
MessageBox(NULL, data.c_str(), "Alert", NULL);
...
});

how do basic jquery ajax in typo3 flow?

I am trying to do some very basic ajax. I just want an onchange event on a select that will call an ajax function that will get the options for another select and fill it in. However I am not sure how to do this in a simple way in Typo3 Flow. My php code for the action just looks like this:
public function getProductsByCategoryAction( $category='' ) {
$postArguments = $this->request->getArguments();
echo __LINE__;
TYPO3\Flow\var_dump($postArguments); die;
}
and my ajax call looks like this:
jQuery('#get_category').change(function(event) {
event.preventDefault();
alert('get products');
var category = jQuery('#get_category').val();
alert(category);
jQuery.ajax({
url: "/admin/orders/getproductsbycategory.html",
data: {
'category': category
},
async: true,
dataType: 'html',
success: function(data) {
alert('hi mom');
...
}
});
});
when I try this url in the browser mysite-dot-com/admin/orders/getproductsbycategory.html?category=17ca6f3e-a9af-da7d-75cd-20f8d6a05ed0
on the page the var_dump just gives me array(empty). Why doesn't the request->getArguments() call work and give the category argument?
The getproductsbycategory.html is created in Neos and has the right plugin for the action call. So I know the right action gets run but it does not get any args. At this point the argument is just a string and not an _identity even though I should eventually do it that way, I'm trying to keep things simple for now for the sake of expediency.
Thanks
Update: as a temp workaround shameless hack I just did this to get the variable:
$categoryID = $_GET['category'];
which works but I'd like to know the proper way especially if it does not involve writing my own view helpers.
First define variable in your html file
<script>
var ajaxUrl = '<f:uri.action action="actionName" controller="(controllername)Ajax"/>';
</script>
Your Ajax code will look like :->
$.ajax({
data: '&lookup='+{somevalue},
type: 'POST',
url: ajaxUrl,
success: function(data) {
$('.lookup-id').append(data);
},
});
Your conroller action will look like :->
public function getLookupIdAction(){
// Get company detail for set logo of company
$companyDetail = $this->getUserCompany();
// Template Name
$templateName = 'GetLookupID.html';
$viewVariables = $this->lookupIdentifierRepository->findByCompany($companyDetail);
$templatepath = 'resource://WIND.Alertregistration/Private/Templates/LookupIdentifier/' . $templateName;
$this->standaloneView->setLayoutRootPath('resource://WIND.Alertregistration/Private/Layouts');
$this->standaloneView->setPartialRootPath('resource://WIND.Alertregistration/Private/Partials');
$this->standaloneView->setFormat('html');
$this->standaloneView->setTemplatePathAndFilename($templatepath);
$this->standaloneView->assignMultiple(array("lookUpValue" => $viewVariables));
$this->standaloneView->setControllerContext($this->getControllerContext());
return $this->standaloneView->render();
}
Your view file look like :->
<f:layout name="Lookup" />
<f:section name="Content">
<label for="lookupId" style="box-sizing: border-box;">Identifier</label>
<div class="select-box" style="box-sizing: border-box;">
// Your Code
</div>
</f:section>

ASP.NET MVC3 & jquery.getJSON not making request

I am working on a MVC 3 site and everything was working until I util I upgraded to jquery1.7.1 using nuget. Now my $.getJSON calls are not making the request to the server. Fiddler does not show a request being made back to the server and code before and after the $.getJSON is executing. Any ideas would be appreciated.
Here is a sample client script:
var srvBaseUrl = "http://localhost:15627/Home/";
$.getJSON(srvBaseUrl + "GetInfo", { 'id': 1 }, function (allData) {
alert(allData);
});
and the corresponding server code:
[HttpGet]
public ActionResult GetInfo(int id)
{
return Json(id, JsonRequestBehavior.AllowGet);
}
I tested that the server code works building up the request in Fiddler.
I had a similar problem, it turned out that JQuery was caching the results. This would explain your comments above that it started working after you made a change.
If you have a look at http://api.jquery.com/jQuery.getJSON/, you will see that $.getJSON is just shorthand for
$.ajax({
url: url,
dataType: 'json',
data: data,
success: callback
});
If you use the $.ajax instead of the shorthand $.getJSON you can disable caching using the cache parameter, meaning you should be able to replace your code with:
$.ajax({
url: srvBaseUrl + "GetInfo",
dataType: 'json',
data: { 'id': 1 },
success: function (allData) { alert(allData); },
cache: false
});
Nuget is not going to update your Views/Shared/_Layout.cshtml file with the updated reference to the latest version of jQuery installed. You will need to update this yourself:
<script src="#Url.Content("~/Scripts/jquery-1.7.1.min.js")" type="text/javascript"> </script>
EDIT
Assuming that is all in order like you said, make sure your getJSON call is inside a document ready function as it work as-is for me. I would however change how you are building the Url to use the helper method instead:
<script type="text/javascript">
(function ($) {
$.getJSON('#Url.Action("GetInfo")', { 'id': 1 }, function (allData) {
alert(allData);
});
})(jQuery);
</script>
This tested out fine in a stock ASP.NET MVC3 Internet Application template project using your controller action as-is.

Resources