I'm pretty new to ruby on rails . I need to pass data from the view to create method in controller.
*view*
function setDeliveryDetails () {
var all_del_rate= $('#all_dr').val();
var all_del_period= $('#all_dp').val();
var array=[all_del_rate,all_del_period]
$.ajax({
type:"GET",
url:"save_delivary_details" ,
dataType:"json",
data: {deliveries: array},
success:function(result){
// alert(result);
},
error: function() {
}
});
}
*Controller*
def save_delivary_details
#deliaddr = params[:deliveries]
end
and in the create method i coded
logger.info("***#{#deliaddr} ")
but the parameters could not found in the rails console
Step 1: Define route of your controller:
# routes.rb
get '/save_delivary_details', controller: <:controller_name>, action: :save_delivary_details
Step 2: Define script with proper URL
function setDeliveryDetails () {
var all_del_rate= $('#all_dr').val();
var all_del_period= $('#all_dp').val();
var array=[all_del_rate,all_del_period]
$.ajax({
type:"GET",
url:"/save_delivary_details" ,
dataType:"json",
data: {deliveries: array},
success:function(result){
// alert(result);
},
error: function() {
}
});
}
Step 3: Get data inside controller action
Maybe you are looking for this (but it's nasty), more details:
$deliaddr = []
def save_delivary_details
$deliaddr = params[:deliveries]
end
And finally in create method:
logger.info("***#{$deliaddr} ")
UPDATE (maybe you are looking for this)
In controller why don't you save this seliveryDetails in DATABASE? Or if delivery address is temporary and don't want to save it permanently, maybe you can store it in session in this way:
# in controller
def save_delivary_details
session[:delivary_details] = params[:deliveries] # maybe you can make this `delivery_details` key unique by putting current_user id or something
end
And then inside create action you can retrieve it in this way:
def create
logger.info("***#{session[:delivary_details]} ")
end
Hope it'll help you. Cheers!
You have to mention the controller symbol when parsing data from AJAX
Change your code like this.
Your Controller is expecting the controller symbol in the beginning of parameters
$.ajax({
type:"GET",
url:"/save_delivary_details" ,
dataType:"json",
data: {delivary_details: {deliveries: array}},
success:function(result){
// alert(result);
},
error: function() {
}
});
This is my example
$.ajax '/schedules',
type: "POST",
data: { schedule: { days: day_id_array, schedule_title: schedule_name, schedule_type: schedule_type}},
async: true
success:(data) ->
if without_date == true
location.href = "/schedules_without_date/" + data.id + '?saved=true&type=' + getScheduleType schedule_type
else
location.href = "/schedules/" + data.id + '?saved=true&type=' + getScheduleType schedule_type
return false
Related
I have to perform following operation.
On a button click from View1, do Ajax request and get complex object as return.
Pass this object to View2 as parameter.
Process the data sent from view1 in client side(inside $(window).load()).
Below is my code:
View1 :
var Url = baseUrl() + "/InteractiveReport/GetRatingProfitData/";
$.ajax({
type: "POST",
url: Url,
contentType: "application/json; charset=utf-8",
dataType: "html",
// dataType: "json",
data: JSON.stringify({ "Projects": SelectedProjectinfo }),
success: function (JsonData) {
debugger;
var w = window.open('about:blank');
w.document.open();
w.document.write(JsonData);
w.document.close();
},
error: function (retVal) {
alert("error:" + retVal.responseText);
}
});
InteractiveReportController :
public ActionResult RatingProfitReport(ProfitRatingInfoModel RatingProfitData)
{
return View("RatingProfitReport", RatingProfitData);
}
public ActionResult GetRatingProfitData(IRSelectedProjectInfoModel Projects)
{
ProfitRatingInfoModel RatingProfitData = new ProfitRatingInfoModel();
//GET RatingProfitData from Database
return RatingProfitReport(RatingProfitDataMdl);
//var jsonSerializer = new JavaScriptSerializer();
//string response = jsonSerializer.Serialize(RatingProfitDataMdl);
//return Json(response, JsonRequestBehavior.AllowGet);
}
View2 :
#using Enterprise_Dashboard.Models
#model ProfitRatingInfoModel
<script>
//Control not entering this section
$(document).ready(function () {
init_bind_rating_profit_table();
});
function init_bind_rating_profit_table()
{
debugger;
var RatingProfitData = #Model.ProfitRatingData;
alert(RatingProfitData[0].BU);
}
</script>
Is there any better way to redirect to different view from Ajax call with parameters.
from my View1, if i directly make Ajax call to View2, i cannot pass complex object as parameter, since its too big string.
Is there any way i can set RatingProfitDataMdl into Session or ViewBag or ViewData or anything else and i can access it in View2?
OR
Is there any way i can eliminate Ajax call on button click so button click on View1 will automatically call GetRatingProfitData and it internally redirects to RatingProfitReport with modal object parameter?
OR
Completely different approach available to handle this scenario?
I am creating simple "rock paper scissors" game with some css animations and so on, where most of the stuff happens in javascript, as learning JS is what I am focusing on mostly at the moment.
User vs computer match also happens in javascript. When match is finished I am assigning users earned exp(points) to new variable.
What I am trying to do now is sending that data (earned exp) to the views, so I can save it back in a database (users.exp).
I think jQuery ajax or fetch api should do that if I am right but after hours of trying I probably just don't get it.
Any1 can give me some tips, explanation? Not just solution please.
Views:
#login_required
def profile(request):
if request.user.is_authenticated:
user = request.user
userObj = Profile.objects.filter(user=user)
usersLevel = userObj[0].level
usersPoints = userObj[0].points
context = {
'usersLevel': usersLevel,
'usersPoints': usersPoints,
}
return render(request, 'rps_app/game.html', context)
else:
print('No user logged in!')
return render(request, 'rps_app/game.html')
This is my template where Iam loading users data:
<script type="text/javascript">
var usersLevel = '{{usersLevel|safe}}';
var usersPoints = '{{usersPoints|safe}}';
</script>
js:
let users_level = Number(usersLevel);
let users_points = Number(usersPoints);
progressbar.style.width = `${users_points}%`;
...
javascript:
$(document).ready(function(){
$('#btn-ajax').click(function(){
$.ajax({
url: 'http://127.0.0.1:8000/game',
csrfmiddlewaretoken: "{{ csrf_token }}",
type: 'get',
success: function(data) {
console.log(data);
alert(data);
},
failure: function(data) {
alert('Your code is crap mate');
}
});
});
})
************ . E D I T E D . ***********
Thats what I got now:
js:
$(document).ready(function(){
$('#btn-ajax').click(function(){
$.ajax({
url: 'http://127.0.0.1:8000/test/earned_exp=100/',
csrfmiddlewaretoken: "{{ csrf_token }}",
success: function(data) {
alert('succes');
},
failure: function(data) {
alert('Your code is crap mate');
}}); });})
views:
def pass_variable(request, earned_exp=None):
some_variable = request.GET.get('earned_exp')
console.log(some_variable)
return HttpResponse('<h1>ok.{}</h1>'.format(earned_exp))
url:
path('test/<earned_exp>/', user_views.pass_variable, name='pass_variable'),
You can pass variables as URL parameters and get them through the request object.
$.ajax({
url: 'mycoolwebsite.com/path/?earned_xp=100'
success: function(e){
alert("success");
},
error: function(e){
alert("error")
}
});
class MyView(View):
def get(self, request):
xp = request.GET.get("earned_xp")
# do whatever you want with the XP now.
In case you want to send multiple URL parameters, you can seperate them by & here's an example url
https://example.com/?hello=world&goodbye=coding
I am trying to send values to other page Using Ajax
But i am unable to receive those values , i don't know where i am wrong
here is my code
<script type="text/javascript">
function get_more_info() { // Call to ajax function
var fval = document.getElementById('get_usecompny').value;
var dataString1 = "fval="+fval;
alert(fval);
var sval = document.getElementById('country').value;
var dataString2 = "sval="+sval;
alert(sval);
$.ajax({
type: "POST",
url: "getmoreinfo.php", // Name of the php files
data: "{'data1':'" + dataString1+ "', 'data2':'" + dataString2+ "'}",
success: function(html)
{
$("#get_more_info_dt").html(html);
}
});
}
</script>
in alert i am getting those value but in page 'getmoreinfo.php' i am not receiving any values
here is my 'getmoreinfo.php' page code
if ($_POST) {
$country = $_POST['fval'];
$country1 = $_POST['sval'];
echo $country1;
echo "<br>";
echo $country;
}
Please let me know where i am wrong .! sorry for bad English
You are passing the parameters with different names than you are attempting to read them with.
Your data: parameter could be done much more simply as below
<script type="text/javascript">
function get_more_info() { // Call to ajax function
var fval = document.getElementById('get_usecompny').value;
var sval = document.getElementById('country').value;
$.ajax({
type: "POST",
url: "getmoreinfo.php", // Name of the php files
data: {fval: fval, sval: sval},
success: function(html)
{
$("#get_more_info_dt").html(html);
}
});
}
</script>
Or cut out the intermediary variables as well and use the jquery method of getting data from an element with an id like this.
<script type="text/javascript">
function get_more_info() { // Call to ajax function
$.ajax({
type: "POST",
url: "getmoreinfo.php", // Name of the php files
data: { fval: $("#get_usecompny").val(),
sval: $("#country").val()
},
success: function(html)
{
$("#get_more_info_dt").html(html);
}
});
}
</script>
No need to create 'dataString' variables. You can present data as an object:
$.ajax({
...
data: {
'fval': fval,
'sval': sval
},
...
});
In your PHP, you can then access the data like this:
$country = $_POST['fval'];
$country1 = $_POST['sval'];
The property "data" from JQuery ajax object need to be a simple object data. JQuery will automatically parse object as parameters on request:
$.ajax({
type: "POST",
url: "getmoreinfo.php",
data: {
fval: document.getElementById('get_usecompny').value,
sval: document.getElementById('country').value
},
success: function(html) {
$("#get_more_info_dt").html(html);
}
});
I am building a chatroom-type app using the Parse Javascript API. The task is to get some data from Parse, display it, add user input to the messages, and send it right back to parse.
The problem is I am not being able to see the data from parse, and receive a 502 error. I am a bit newer to javascript, so any advice on how to accomplish this, or any mistakes you may see in my code, would be fantastic. I also commented out my code the best I could. Thanks for the help.
Here is my code;
$(document).ready(function(){
delete Chat.display;
delete Chat.send;
delete Chat.fetch;
var my_messages = $('ul.messages')
//fetches data from parse
var myChat = function() {
$.ajax({
url: "https://api.parse.com/1/classes/chats",
dataType: "json",
success: console.log("Success"),
function message(a) {
my_messages.append('<ul>' + a +'</ul>'); //adds ul 'text' to messages
};
});
};
myChat(); // call mychat
$('button.send').on('click', function() { // when user clicks send
// send post to
$.ajax({
type: "POST",
url: "https://api.parse.com/1/classes/chats",
data: JSON.stringify({text: $('input.draft').val()}), // stringify the text on value input.draft
function(message){
window.location.reload(1) //refresh every 3 seconds
});
});
});
</script>
you have syntax error in both of your success functions of $.ajax calls. In the first ajax call you have places console.log, which should be inside the success callback. In the second one u haven't even added success: callback.
Try below updated code
$(document).ready(function(){
delete Chat.display;
delete Chat.send;
delete Chat.fetch;
var my_messages = $('ul.messages');
var myChat = function() {
$.ajax({
url: "https://api.parse.com/1/classes/chats",
dataType: "json",
success:function message(a) {
console.log("Success")
$.each(a,function(i,item){
my_messages.append('<ul>' + item.username +'</ul>'); //adds ul 'text' to messages
});
}
});
};
myChat(); // call mychat
$('button.send').on('click', function() { // when user clicks send
// send post to
$.ajax({
type: "POST",
url: "https://api.parse.com/1/classes/chats",
data: JSON.stringify({text: $('input.draft').val()}), // stringify the text on value input.draft
success:function(message){
window.location.reload(1) //refresh every 3 seconds
}
});
});
});
Is it possibe to simply load a php script with a url with js?
$(function() {
$('form').submit(function(e) {
e.preventDefault();
var title = $('#title:input').val();
var urlsStr = $("#links").val();
var urls = urlsStr.match(/\bhttps?:\/\/[^\s]+/gi);
var formData = {
"title": title,
"urls": urls
}
var jsonForm = JSON.stringify(formData);
$.ajax({
type: 'GET',
cache: false,
data: { jsonForm : jsonForm },
url: 'publishlinks/publish'
})
//load php script
});
});
Edit:
function index() {
$this->load->model('NewsFeed_model');
$data['queryMovies'] = $this->NewsFeed_model->getPublications();
$this->load->view('news_feed_view', $data);
}
simple
jQuery and:
<script>
$.get('myPHP.php', function(data) {});
</script>
Later edit:
for form use serialize:
<script>
$.post("myPHP.php", $("#myFormID").serialize());
</script>
like this ?
$.get('myPHP.php', function(data) {
$('.result').html(data);
alert('Load was performed.');
});
There are various ways to execute a server side page using jQuery. Every method has its own configuration and at the minimum you have to specify the url which you want to request.
$.ajax
$.ajax({
type: "Get",//Since you just have to request the page
url:"test.php",
data: {},//In case you want to provide the data along with the request
success: function(data){},//If you want to do something after the request is successfull
failure: function(){}, //If you want to do something if the request fails
});
$.get
$.get("test.php");//Simplest one if you just dont care whether the call went through or not
$.post
var data = {};
$.post("test.php", data, function(data){});
You can get the form data as a json object as below
var data = $("formSelector").searialize();//This you can pass along with your request