AJAX call how to retrieve my javascript variable - javascript

I work with Rails 4 and basically I am searching a value on my html webpage traversing the DOM with jquery.
I store the value in a variable named key and I want to use this value to then make a request that would look like this :
Record.find(id: key).name
I perform an AJAX call and it works well (I checked it rendering status json ok). But now how can I use/retrieve the parameter key in my controller ?
I have a User and a Record model. In the app/views/usersdirectory I have the partial _form.html.erb in which I am doing some javascript.
var key = $('input#record_id').val();
And I want this variable to be available in the method search of my user controller, so that I can make a request with the parameter key.
So I am doing an AJAX call that looks like this :
$.ajax({
url: "/search",
type: "POST",
data: {
value: key
},
complete: function(){
console.log('success');
}
});
And in my config routes file I wrote this route :
post '/search' => 'users#search'
In my User controller I wrote the method like this :
def search
#record = Record.find(params[:key])
end
Is #record available in my partial ? How can I print in my view the result of my request ?
Can anyone tell me if I am doing right or wrong for my AJAX call ? Thanks for any help. If I forgot to mention any information you might need tell me and I'll edit my post.
I added a complete function in my AJAX call, that is supposed to show successif the AJAX call had been done and in my console log I have this message 'success' that appears

For 404 not found the url must be wrong.
And to get the param key in your controller you must change data to data: {key: key} or if you use data: {value: key} then your action must change the name of the param like #record = Record.find(params[:level])
Basically, you are not using the right param name in your controller which is why the issue arises. Hope it helps.
To answer your second question:
#GDMN, you need to get your basics right! Every ajax has a success and failure callback.You could return json from your action which will be used by success callback and you could do whatever you want from there. Essentially in rails you might want to render a js file like this
Create a file named search.js.erb and use your javascript code in it like below
$('.some_id_or_class').html("<%= #record.name %>")
that will simply replace the element of that class with the value that is returned by #record.name

put the full url
url: "http://yoursite.domain/search",

Related

How to get checkbox value in AJAX

I want to get the value of my checkbox in Ajax so that I can save it in database as a preference for each of my user. I've never done AJAX before so i'm quite lost about it.
My javascript file :
$(document).ready ->
E.accounts.changeUnmarkVisibility()
$('#letters-visibility').on 'click', (e) ->
E.accounts.changeUnmarkVisibility()
$('#label-letters-visibility').on 'click', (e) ->
if $('#letters-visibility').is(':checked')
$('#letters-visibility').prop('checked', false)
else
$('#letters-visibility').prop('checked', true)
E.accounts.changeUnmarkVisibility()
$('#letters-visibility').on 'change', (e) ->
$.ajax
url: "/backend/accounts/{#id}"
type: 'POST'
data:
isChecked: $('#letters-visibility').is(':checked')
success: (data, status, request) ->
console.log data
E.accounts =
changeUnmarkVisibility: ->
unmarkLines = $('.active-list .unmark').closest('tr')
if unmarkLines.is(':visible')
unmarkLines.hide()
else
unmarkLines.show()
)
My post request send me back a 404 error, I think the error is in my 'Data' option
Yeah Deckerz is right normally you have an ajax call which has a 'Data' option and then a success option. The data is an array/object of values that you want to send.
There are lots of options on the jquery ajax page and it's quite easy to get lost in them. This though is the norm. Done is called after some.php (in this case) has finished and msg has the data that is sent back from msg. Normally you'll want this in a json format. This is good practise for if you want to send back 2 variables. e.g Status (success/error) and ErrorMessage = ""
if you're using php json_encode is the function to use to achieve this.
$.ajax({
method: "POST",
url: "some.php",
data: { name: "John", location: "Boston" }
})
.done(function( msg ) {
alert( "Data Saved: " + msg );
});
I'm not sure I've understood where you're stuck at: it seems to me you've already read the checkbox's value without problems, so I'll assume you don't know what to do with the AJAX call.
The AJAX call is really just a request to your server: you probably want to call a script (pointed to by the URL you pass), with the parameters you need to identify the user and the option, that writes the checkbox's value to the database.
One thing that may be useful to know: you don't need to construct a query string to pass your parameters along with a GET request, you can just pass them in the data parameter of the jQuery.ajax call as a regular JSON object.
AJAX doesn't do that. AJAX returns the value. And then you look at the value to decide what to check. If you are doing this in jquery, then look here: https://api.jquery.com/checked-selector/

passing javascript parameter to asp.net

I have a Javascript function and i want to pass a parameter from javascript to asp.net. my sample code like below:
function ConfirmMessage(message) {
var msg = "<%= Efe.UI.WebApplication.AppCode.HelperClass.GetScreenMessage(message); %>"
alert.confirm(msg);
}
But I am getting error at "message" parameter. The error is:
The "name" does not exist in the current context.
How can I pass parameter from javascript to asp.net?
You cannot pass parameter from javascript to server side at inline code.
You should use jquery ajax for that.
var message = "value";
$.get(
url: "/yoururl/GetScreenMessage",
data: {message : message},
success: function(data){
alert(data);
});
You're trying to dynamically call a server side function with a parameter, but the <%= %> part is actually a Response.Write. So, during the page load the page will try to render with the Efe.UI.WebApplication.*xxx* method's output.
That won't work.
You'll need a different solution all together. Most likely you'll want to use a "REST-like" service call to get the result of the "message" parameter. I would suggest you take a look at AJAX : http://msdn.microsoft.com/en-us/library/bb398874%28v=vs.100%29.aspx and http://www.codeproject.com/Articles/29400/Ajax-Quick-Start-FAQ

Passing array through ajax

I'm fairly new to the jQuery execute on the same page stuff. So far I have been passing only single values trough ajax which is working fine. Now, I need to pass an array which is created by checkboxes through ajax.
My form html, dynamically created by php:
<input type=checkbox class=box name=box[] value=".$row['DoosID']." />
My jQuery:
var BackorderDate = $("#BackorderDate").val();
var Box = $(".box").val();
if( (TerugleverDatum == "") ){
$("#backorderresult").html(" * Some Error .").fadeIn("Slow").fadeOut(3000);
} else {
$("#backorderresult").fadeOut();
$.ajax({
type :'POST',
url :'./backorder.php',
data : box : Box,
backorderdate: BackorderDate,
dataType:"json",
success: function(data){
// Do Something
}
});
}
My PHP:
$boxlist = json_encode($box);
foreach($boxlist as $boxvalue){
// Do something with every value
}
this gives me a javascript error on submit saying box is not defined.
change this:
data : box : Box, backorderdate: BackorderDate, // invalid way of sending
to this:
data : {box : Box, backorderdate: BackorderDate}, // valid way
data
Type: PlainObject or String
Data to be sent to the server. It is converted to a query string, if not already a string. It's appended to the url for GET-requests. See processData option to prevent this automatic processing. Object must be Key/Value pairs.
More Info
Why don't you try enclosing all the data values in a open and close curly braze( { and } ) .
Else it will conflict with the syntax of $.ajax method.
I think it is causing the problem.
You are sending data value in wrongly manner -
The data property should always be a JavaScript object. It's properties are serialized into a regular query string (for GET requests), or a normal post body parameter string (for POST requests). This serialized string is then sent to the server, along with the AJAX request.
On the server you can read the properties of the data object as if they were sent as simple request parameters, via either GET or POST. Just like if the properties had been fields in a form.
Try this :
$.ajax({
type :'POST',
url :'./backorder.php',
data : 'box='+Box+'&backorderdate='+BackorderDate,
dataType:"json",
success: function(data){
// Do Something
}
});
For more information see jQuery Ajax
You might want to refer to the php file like this: url :'../backorder.php' (double dots). At least, that's how I do it always.

Passing multiple arguments through HTTP GET

I have an HTML file referencing a PHP script to perform various functions. One of the ways the HTML file calls the PHP script is through an HTTP GET. The GET request should pass three parameters and return a list of all saved events as a JSON-encoded response.
So far, I have the following but I'm not sure how to pass the three arguments through the HTTP GET. Also, I'm not sure if I am returning the JSON-encoded response correctly:
if($_SERVER['REQUEST_METHOD'] == 'GET'){
echo json_encode(events.json); }
GET requests are done through the URL... So if you want to pass three GET requests you would do...
http://www.domain.com/target.php?param1=whatever&param2=whatever&param3=whatever
target.php represents the PHP script file you want to send the information to. You can have as many variables as you want but just keep in mind that every other GET request has to be separated by an & symbol. The first param simply has to be started off with a ? symbol.
If you want to use Javascript, I would recommend using JQuery. You can do something like this
$.get('target.php?param1='+whatever+'&param2='+whatever2, function(data) {
alert(data);
});
Or you can use window.location to send a link with the appropriate link above.
If you want to use AJAX specifically, here is a way of doing it with JQuery (there are ways with Javascript that I could update later if necessary:
$.ajax({
type: "GET",
url: "http://www.domain.com/target.php",
data: { param1 : "whatever", param2 : "whatever", param3 : "whatever" },
success: function(result){
//do something with result
}
})
If you want to access the variables, you can call $_GET['param1'] or $_REQUEST['param1'] to get access to them in PHP. Simply change the name in the brackets to the desired variable you want and store it in a variable.
If you want to access the params with Javascript... well the most efficient way is to go and decode the URL that was used and pull them out. See here
Hope this helps!
You can access the parameters from the URL via the $_GET superglobal in PHP.
For example, if your URL is http://example.com/test.php?param1=foo&param2=bar, then you could access them in PHP like so:
$param1 = $_GET['param1'];
$param2 = $_GET['param2'];
See http://www.php.net/manual/en/reserved.variables.get.php for more details.
As for returning a valid JSON response, you can check out this answer. It uses PHP's header function.

Use the result of an ajax request in my views.py, Django

Thanks to a javascript function and an ajax request, I have a count indicating the number of points a user makes when he uses my app. He can see that count on the page where he 'plays'.
Now, what I would like to do, is to pass this number into my views.py so that it modifies the object "Score" of my user.
I explain. Thanks to this function, I get the count:
var count = parseInt(0);
setInterval(function() {
$.ajax({
type: "GET",
url: "http://myxml",
success: Escore
});
}, 60000);
function Escore(xml){
$(xml).find("user").each(function() {
if($(this).attr("id") === id ) {
count += parseInt($(this).attr("count"));
$(".PlayerScore").html(count)
}
});
}
displayed in my html:
<div class="PlayerScore"> </div>
Now, I would like to modify the object "score" of my user thanks to that. Every minute, I have a request that gives me the number of points the player makes in my div. How can I take this count in order to modify my "request.user.userprofile.score" in my views.py?
I hope my question is not too confusing. Any help would be really welcome. thanks!
Hm If I understand the question, you need to do the following:
Create your view function, and create a URL pattern in URL.conf that attaches to this view function. Something like /points/save/
This function will likely require the points of the user and the user ID (so you can make changes to the specific user in the database)
You need to make an ajax request that sends the point data and the user ID To the URL that points to your view function. Sent through GET/POST
Your view function will lookup the user from the user id sent from jquery ajax call, then edit the user points with the points sent from the ajax call
Here are a few guides to help
Ajax with Jquery and Django
Django and Jquery

Categories

Resources