Okay here's my problem.
I have an html page that has a javascript variable initialized in it.
<html>
<script>
MyVaribale = "Random Data";
</script>
<!-- Then I include an external js file to handle the processes in this html file -->
<script type="text/javascript" language="javascript" src="/scripts/some_random_script.js"></script>
</html>
Now, inside that script. I used the MyVaribalevarible in one of the ajax request there, like this :
$(document).ready(function() {
$.ajax(
url : '/some/random/url',
data : { MyVariable : MyVaribale }
etc ...
);
});
So, on page load, that ajax code is executed immediately.
In the url specified above, i checked for the existence of MyVaribale, then flag an error that it is a required value if it doesn't exist.
Backend code like this (in Perl):
my $MyVariable = trim_param('MyVariable'); # trim_param() is a function that gets the passed data from ajax.
if ( $MyVariable ) { # Test if it exists
# Display something
}
else {
# Flag an error, which is my problem
}
Now I am sure that in the html page, that variable is always populated (yes 100% sure). But I always get flag errors that that value doesn't exist in my backend code (url above).
So question,
Does ajax have some issue with document.ready, maybe it executes before the variable has finished assigning a value? Any idea why this happens? Because sometimes my ajax request is successful, sometimes it's not
Thanks
The syntax of your ajax call is not correct. Have a look here and then try this code (note the addition of {, } and ,):
MyVaribale = "Random Data";
$(document).ready(function() {
$.ajax({
url: '/some/random/url',
data : { myVariable : MyVaribale }
});
});
Did not you try out some complete ajax calls? Like this.Sometimes no need to use JSON.stringify for MyVariable.
$.ajax({
url: "/some/random/url",
type: 'POST',
dataType: 'json',
data: JSON.stringify(MyVaribale),
contentType: 'application/json',
mimeType: 'application/json'
}).done(function(data) {
}).fail(function(error) {
}).always(function(){
});
Related
I was trying to make an ajax call and show an html part inside a div class. For that i used the following way.
$.ajax({
type: "get",
url: "{{url('searchByCheckbox')}}",
dataType: 'html',
success: function(html)
{
$(".infinite-scroll").html(html)
}
});
But the problem is there is a script inside that html part which i wanted to load when i make first ajax call it's not loaded but for the second one it's loaded the script.
suppose the html response like this :
<script>
alert()
</script>
// html
How do i make it work?
I put the script above the html page which i'm getting as response.
(those who are marking the Question as duplicate should read at least what i want and what they wanted )
Im sure that the error is happening because of the script, because you are closing the </script> tag inside the html.
The best solution is to return the data from your ajax call as a json
To do that you should:
1- add a dataType to your ajax parameter as the below:
$.ajax({
type: "get",
dataType: "json",
2- In the php file handling the ajax call, you must resurn the values as a json as below:
Assume that currently you are doing the following:
echo $html
You should change it to match the below:
$retArr = array(
"html" => $html, //Your html code without the javascript function
"jsFunc" => $jsFunc //Your java script function parameters
) ;
echo json_encode($retArr) ;
And then your ajax success must be as the below:
success: function(data)
{ //You can access all the object parametes by calling the object name `data` followed by a dot `.` and then by the parameter key
data.jsFunc // Your javascript function params
$(".infinite-scroll").html(data.html) ;
}
I have a div element in my index.cshtml with id #myresults and i am trying to load data through jquery.load method by calling a mvc controller method. But i am not able to get the right syntax.
I am passing a custom object as a parameter as well.
var mycustomObject = {
obj1:value1,
obj2:value2,
..
}
The following does not work...(an i have tried other combinations as well..i get server not found error)
$("#myresults").load ('#Url.Action("MyActionMethod","Home")',mycustomObject);
while the following works
$("#myresults").load('/Home/MyActionMethod', mycustomObject);
While the last statement works, it works only on localhost.
Whats the right syntax to use for jquery load with Url.Action ?
#Url.Action() will always generate the correct url, so if your getting a 404, it means this code is in an external script file. Razor code is not executed in external scripts so your url would literally be the text "#Url.Action("MyActionMethod","Home")".
Options to solve this include
moving the code into the view or its layout
declaring a global variable in the view - var url =
'#Url.Action("MyActionMethod","Home")'; an in the external file use
$("#myresults").load(url, mycustomObject);
assign the url to an element as a data-* attribute, for example
<button type="button" id="loadSomething" data-url="#Url.Action("MyActionMethod","Home")">...</button>,and in
the external file
$('#loadSomething').click(function() {
var url = $(this).data('url');
$("#myresults").load(url, mycustomObject);
});
Define the div element as:
<div id="myresults" onload="loadMyData();"></div>
And make the ajax call in your method:
<script type="text/javascript">
function loadMyData() {
$.ajax({
cache: false,
url: '#Html.Raw(Url.Action(MyActionMethod","Home"))',
data: { obj1:value1, obj2:value2 },
dataType: "json",
type: 'post',
success: function (result) {
if (result.success) {
$('#myresults').html(result.data);
}
else {
alert("Failed to load data!");
}
}
});
}
</script>
Ive been checking out how to add variables to a ajax request which I can use in my server side script. I checked this stackoverflow post here and checked the jquery api docs here for a ajax request. I am getting error variable in my code is not defined.
I have this line in my code
return $.ajax({
type: 'GET',
url: '/users/show',
data: {'currentusershow': variable},
});
I was wanting it to do something like this with the results so I can keep all my different script in the one file.
if ($.get("currentusershow")) {
// do something here
}
else if...
i am not sure how to add the value to my code?
Also my url does not work going to the show.js.erb where my code is kept.
You need to declare and assign some value to the variable before the request.
Also you need to change the method type from GET to POST.
var variable = 'some data';
/*$.ajax({
type: 'POST',
url: '/users/show',
data: {currentusershow: variable},
success: function (response) {
// Do something with respsone
},
error: function () {
alert("error");
}
});*/
$.get( "/users/show", {currentusershow: variable} )
.done(function( response ) {
//do something with the response here.
});
Mamun was kind of right here as I did not explain myself very well in my question but I thought I would post this and clarify my question with what I was trying to do. The ajax call should be
return $.ajax({
type: 'GET',
url: '/users/show',
data: { currentusershow: 'variable'},
});
where the key is currentusershow and the value variable 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?currentusershow=variable. And in my destination file add my ruby code there to use the variables. In my question that code was more a php type code as I did not know what I was doing at the time.
I have the following HTML structure:
<form method="POST">
Name : <input id="asgname" type="text"> <br>
Description : <input id="asgdescription" type="text"> <br>
Save
</form>
I want that on clicking the save button, the form values are sent to the server via AJAX call.
For that, I've attached the click event via following command
$("#asgsave").click(save_assignment);
save_assignment is also a javascript function defined as follow:
function save_assignment() {
return $.ajax({
type: "POST",
url: "<?php echo base_url();?>index.php/user/save_assignment",
data: $('form').serialize(),
success: function(response) {
alert('Form was submitted');
},
error: function(error) {
alert("Error");
}
});
}
The above is not working. So I tried the following approach as well:
function save_assignment() {
var formvalues = {
name : $('#asgname').text(),
descripion : $('#asgdescription').text(),
};
return $.ajax({
type: "POST",
url: "<?php echo base_url();?>index.php/user/save_assignment",
data: {values : formvalues},
success: function(response) {
alert('Form was submitted');
},
error: function(error) {
alert("Error");
}
});
}
But this is also not working.
Can anyone please guide me as to why are the above methods not working and what is the correct way to do so ?
EDIT-1 :
By not working, I mean: in the first case ($('form').serialize() approach) the data is not being sent to the server. I checked it via chrome and firefox debugger that there was no post data sent corresponding to the form.
And in the second case, empty values are being sent. i.e. the post data sent to server is like following:
values[name]
values[description]
i.e. the above values are empty.
EDIT-2:
By logging on firephp, I have confirmed that the save_assignment PHP script is BEING EXECUTED. Thus ajax call is working fine but it is NOT passing the data correctly.
Try to use event.preventDefault() like,
$("#asgsave").on('click',function(e){
e.preventDefault();
save_assignment();
});
or use return false after ajax call like,
function save_assignment() {
//ajax code
return false;
}
you have to use callbacks in the success function, cause ajax is asynchronously
edit
have you already tried console.log('foo'); in your function? so you are able to test if the function is called ;)
edit 2
add the following line to your ajax options
dataType: "json"
You could just serialize your form values:
http://api.jquery.com/serialize/
However, looking over your code, I'll take a stab and guess that you are not getting and sending your values properly. Using jQuery, you grab a value from input like so:
$('#idofInput').val();
http://api.jquery.com/val/
You are doing: $('#asgname').text()
Format your data properly: data : { foo : 'bar', bar : 'foo' }
One last guess, make sure your CodeIgniter config has CSRF protection disabled, otherwise you would need to pass: $this->security->get_csrf_token_name() & $this->security->get_csrf_hash();
In my webpy app I have a function:
def POST (self):
signal = web.input()['signal']
if signal == 'next':
errMessage = self.cinstall.testConnection()
print signal
print errMessage
return errMessage
According to the python console it works correctly; it receives and returns strings as I expect it to.
In a template I have a script like this:
<script src="/static/jquery-1.7.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
$$(function() {
var value = $$('#continue').attr('value');
$$("#continue").click(function(){
jQuery.ajax({
type: "POST",
data: {signal : value},
success: function(html) {
jQuery('#errmessage').html(html).hide().fadeIn(1500);
},
});
});
});
</script>
I know that the request is successful, because if I put an alert in the success handler it works well, but the function jQuery('#errmessage').html(html).hide().fadeIn(1500); doesn't execute. I have a <p> tag with id=errmessage in my template.
So I have several questions:
Why it doesn't work?
Can I isolate the data recieved from POST in JS for further iterations and if statements?
Can I put if statements inside the jQuery.ajax success function?
Unfortunately, jQuery API gives limited info about success().