I have a few ajax calls in my app they all go to the same file server side. i want to know if I can use a variable... I want to have a way to distinguish the call from other calls and of course, use the variable to select which script in the file to send back to the client. I do not need to use the variable after the script has run in any way. Or am i going about this the wrong way?
for example this is one of my ajax calls
var variable1 = 'currentuser1var';
return $.ajax({
type: 'GET',
url: '/users/index',
data: {currentuser1var: variable1},
dataType: 'script',
});
then the script in my server side file would be
if (currentuser1var) { script here }
else if (currentuser2var) { script here }
...
I am not sure how to access the string, inside the object call. Do i need to access the object first then the string? Or just reference the variable some how.
EDIT Tried
if(typeof(currentuser1var) != "undefined") { script here }
to no avail.
If you were using PHP, your server side script would be:
if(isset($_GET['currentuser1var'])) {
... script to process the currentuser1var variable ...
} else if (isset($_GET['currentuser2var'])) {
... script to process the currentuser2var variable ...
}
Aj was right here I guess for php as I did not list what server side code I was using, but simply put, I changed my ajax call to
return $.ajax({
type: 'GET',
url: '/users/show',
data: { currentuser1var: 'variable1'},
});
where the key is currentuser1var and the value variable1 is a string and leave out defining the variable else where in the code. That way the url comes through correctly to the server being /users/show?currentuser1var=variable1. And in my destination file add my ruby code there to use the variables.
Related
I make an ajax call to a server and the server returns javascript and jquery code such as
$('someclass').html('<form id='billform'>......</>');
$('#billform').submit();
How do I execute this on the client side?
You could put that code inside a script tag and append it to the body
This procedure is described best here: https://stackoverflow.com/a/611016/4202031
However, it is not recommendet to simply execute some javascript which is loaded via ajax. I would recommend to work with events that would trigger this code which is on your page already.
$.get('/sumUrl', function(data) {
switch(data.action) {
case 'event1':
//do sth.
break
case 'event2':
// do sth. else
break
}
})
You can include the code as a function in your static page, then call the function from the returned ajax call. A small example:
on your static page:
function submitmyform(formcontents)
{
$("someclass").html(formcontents);
$("#billform").submit();
}
on your ajax success method:
$.ajax({
url: "/getform",
method: "POST",
data: $(".myform").serialize(),
success: function(data){
submitmyform(data);
}
});
You have to put your id in quotation marks, and as id instead $ use #
$('someclass').html('<form id="billform"></>');
$('#billform').submit();
You can use eval function from javascript to execute the scritp which are string
e.g.
eval('alert("Hello!")');
I your case
eval('$(".someclass").html("<form id="billform">......</>")');
eval('$("#billform").submit()');
I have been trying to redirect page with variable through javascript.
I have found window.location.href = "test.php?variable=" + variabletosend;
but in this way user can change url and hence values.
Please tell me, how to pass variable to another page through javascript, hidden from user.
Your entire approach is wrong.
You can never trust a URL from a user, nor prevent the user from seeing the URL to the page.
Instead, you need to write server-side code to return an error if the user tries to access they're not supposed to.
You could do something like:
Instead of GET request, use POST (if you don't want parameters in url)
If you want to pass parameter + redirect then, it would be better if you could store those values as session variable.
If you worry about user accessing improper pages of your site you should correclry handle such requests either in server-side running code or using your web-server (IIS, Apache, etc)
You basically want to send the variable to a php page via js.I also had this kind of problems.you should use AJAX request.I know it sounds complex but after you google it this would be easy.In jquery you could use(it would be good to check for syntax error):
$(document).ready(function() {
$.ajax({
type: "POST",
url: 'test.php',
data: { variable : variable },
success: function(data)
{
alert("success!");
}
});
});
use this file."jquery.redirect.js"
$("#btn_id").click(function(){
$.redirect(http://localhost/test/test1.php,
{
user_name: "khan",
city : "Meerut",
country : "country"
});
});
see=https://github.com/mgalante/jquery.redirect
I have the following code, as part of a code to add some value to a database.
After executing the $.ajax succesfully, I want a specific div (with class 'lijst') to be reloaded with the refreshed data.
$.ajax({
url: \"frontend/inc/functions/add_selectie.php\",
type: \"POST\",
data: ({ 'p_id' : p_id, 'v_id' : v_id, 'pd_id' : pd_id }),
cache: false,
success: function()
{
$(\".lijst\").hide().fadeIn('slow');
}
});
However, with this solution, only the div is refreshed, not the actual PHP variables that are specified in there. When I refresh my browser manually, the values are updated.
How can I refresh the div and also update the variables?
According to the jQuery.ajax documentation, the function signature of "success".
Type: Function( PlainObject data, String textStatus, jqXHR
jqXHR ) A function to be called if the request succeeds. The function
gets passed three arguments: The data returned from the server ...
So in other words:
success: function(data) {
$(".lijst").html(data).hide().fadeIn('slow');
}
Actually, the PHP variables specified in the html are worked at the sever part. PHP variables in the html have replaced by the string of there value when it is ready to be sent to the browser. And your ajax request will cause PHP to update database. So when you have sent the request and then refresh the page, PHP will replace the varables in the html again.
According to this above, your ajax request and the server repsonse are not aware of the PHP variables's existence. So you must update the content yourself.
Maybe you will do something like this:
success: function(data) {
$(".lijst").hide();
$(".title").html(data.title); // $(".title") may be a tag that surround a PHP variable
$(".content").html(data.content); // the same as $(".title")
$(".lijst").fadeIn('slow');
}
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¶m2=whatever¶m3=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+'¶m2='+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¶m2=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.
I'm working on this function that loads a php file in the background:
<div id="content1"></div>
<script type="text/javascript">
<!--
$("#content1").load("/bm_products_filter.php");
//-->
</script>
The original php code is this:
<?php require('/bm_products_filter.php');
?>
With the original code the page works fine, with the java code it gives errors. This is because the php doesn't use the variables in the current page. I know how to pass variables to the external php but is there a way that it uses all the variables on the current page?
I am not sure if I got you wrong but you cannot load PHP files with JavaScript or JQuery.
JavaScript is client sided and has no access to the server if you want to load some data on a point of time when the template builds / is built without PHP oyu have to use an Ajax request which is also pretty simple with JQuery.
Please check out:
http://api.jquery.com/jquery.ajax/
If you can rewrite the bm_products_filter.php to return a JSON output, you can use a function as below to get values returned from the php.
jsonKey1 I have used below is one of the JSON keys returned from the php.
function getToken() {
var requestStr = "./bm_products_filter.php";
$.ajax({
url: requestStr,
type: "GET",
cache: true,
dataType: 'json',
success: function (data) {
bmProductsData = data.jsonKey1;
}
});
}
Hope this helps.