This is my test.rb
require 'sinatra'
require 'json/pure'
get '/2015/:teachername/teaching/:subjectname' do
content_type :json
{
"message" => "#{params[:teachername]} teaching #{params[:subjectname]}."
}.to_json
end
It's all fine, like when I access through url localhost:4567/2015/Anil/teaching/Sunil, but when I access this url in jquery I couldnot get passed :teachername and :subjectname.
Here is my test.html
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script>
$.getJSON('/2015/:teachername/teaching/:subjectname', function(data) {
alert(data.message);
});
</script>
You'll have to construct the URL string by appending your parameters in Javascript.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script>
var teachername = 'Anil';
var subjectname = 'Sunil';
$.getJSON('/2015/'+teachername+'/teaching/'+subjectname, function(data) {
alert(data.message);
});
</script>
Related
I am trying to pass the #Model.Id from my razor view to the javascript so that I can pass it to the dataTables ajax url but I cant manage to get the value to the javascript file.
Even just a point in the right direction would help at this point
Here is the View:
#model GTravel.Domain.Package
#{
var title = Model.Name;
}
//boring html code
#section Scripts{
<script src="~/js/packageCity.js" data-packageId="#Model.Id"></script>
}
And a snippet of the js:
var dataTable;
var url;
$(document).ready(function () {
url = "/admin/packageCity/GetAll/" + packageId.toString();
loadDataTable();
});
function loadDataTable() {
dataTable = $('#tblData').DataTable({
"ajax": {
"url": url,
"type": "GET",
"datatype": "json"
},
"columns": [
{ "data": "city", "width": "10%" },
//more code etc
Based on your method, you are missing some key content.
To ensure that the value passed by data-packageId can be accurately obtained in the js file, you need to add an id to the script that references the js file, and then obtain the passed value by obtaining the corresponding id in the js file:
#section Scripts{
<script id="Index.js" src="~/js/packageCity.js" data-packageId="#Model.Id"></script>
}
js file:
$(document).ready(function () {
var $vars = $('#Index\\.js').data();
url = "/admin/packageCity/GetAll/" + $vars.packageid;
loadDataTable();
});
And it should be noted that when obtaining the packageId through $vars, make sure that the packageId are all lowercase letters.
Another method:
You can create a variable in the view directly before referencing the js file, and then accept the value that needs to be passed, so that in the js file, you can directly call the variable to get the value that needs to be passed.
#section Scripts{
<script>
var data = '#Model.Id';
</script>
<script src="~/js/packageCity.js" ></script>
}
js file:
$(document).ready(function () {
url = "/admin/packageCity/GetAll/" + data;
loadDataTable();
});
My complete script is as follows
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://code.jquery.com/jquery-3.1.1.slim.min.js" integrity="sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/EheAdgtzNs3hpfag6Ed950n" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js" integrity="sha384-DztdAPBWPRXSA/3eYEEUWrWCy7G5KFbe8fFjk5JAIxUYHKkDx6Qin1DkWx51bBrb" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js" integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn" crossorigin="anonymous"></script>
<script type="text/javascript">
$(window).on('load',function(){
$('#myModal').modal('show');
});
</script>
<script>
$( document ).ready(function () {
$("#vote").click(function (e) {
var poll_id = $('input[name=pollID]', '#myForm').val();
var poll_option_id = $('input[name=voteOpt]:checked', '#myForm').val() ;
//alert(poll_id + "AND" + poll_option_id);
$.ajax({
type: "POST",
url: "http://localhost/poll/index.php/form/poll",
data: {poll_id: poll_id, poll_option_id: poll_option_id},
dataType: "json",
success: function(data) {
alert(data);
}, error: function() {
alert("ERROR");
}
});
});
});
</script>
And I have the following inside poll function in form controller
public function poll() {
$pollid = $this->input->post('pollID');
$voteData = array(
'poll_id' => $pollid,
'poll_option_id' => $this->input->post('voteOpt')
);
$voteSubmit = $this->modal->vote($voteData);
if($voteSubmit){
echo 'Your Vote Has Been Submitted successfully.';
}else{
echo 'You Had Already Voted.';
}
}
Now the thing is that, modal is executing perfectly on page load. But ajax is not working neither success part is executing nor error. Also on uncommenting the alert before ajax, correct values are alerted. I cannot figure the error.
Please help
I can see there are many javascript libraries included. Very sure some of them are conflicting.
Try this before $(document).ready():-
$.noConflict();
After looking at your form controller code, I can see you are just returning a text. So ajax dataType should be HTML and not json. dataType parameter is to define the type of return value.
I can only see this one wrong point in your code. Your console response status is also fine, which means it is the dataType which is wrong.
dataType = The data type expected of the server response.
dataType:'html'
For Example.
See you can check is you script is actually sending post values or not these way.
In you console > Network Tab. You can view which post values are sent as POST.
Now I had code in PHP Codeigniter and for me following code worked fine.
$("#username").keyup(check_if_username_exists);
function check_if_username_exists() {
var username = $("#username").val();
var sRet = false;
$.ajax(
{
type:"post",
async: false,
url: "<?php echo site_url('distributor/tenant/check_username_exists'); ?>",
data:{ username:username},
success:function(response)
{
var parent_fieldset = $("#username").parents('fieldset');
$("#username").parent().addClass('has-error');
if (response == "true")
{
$('#span').html('<span style="color: #0fa7b5;">'+"Login Username"+"</span>");
$("#username").removeClass('input-error');
$("#username").parent().removeClass('has-error');
console.log('Success! This Username is available');
hideToastr();
sRet = true;
}
else
{
show_error("Error","Oops! This Username is already taken");
$("#username").addClass('input-error');
$('#span').html('<span style="color:red;">Username already Exists!</span>');
console.log('Oops! This Username is already taken');
sRet = false;
}
}
});
console.log("End Of Username Exists " + sRet);
return sRet;
}
Also there is third party application POSTMAN which will help your debug your application. It allows you to sent post data with form values.
Update
Also I think you might have multiple JS files include issue or problem with the order they are placed. FYI I used only bootstrap.js and jquery.min.js and everything worked fine. So try removing
<script src="https://code.jquery.com/jquery-3.1.1.slim.min.js" integrity="sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/EheAdgtzNs3hpfag6Ed950n" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js" integrity="sha384-DztdAPBWPRXSA/3eYEEUWrWCy7G5KFbe8fFjk5JAIxUYHKkDx6Qin1DkWx51bBrb" crossorigin="anonymous"></script>
UPDATE 2 :
Now for your controller I don't see where you encode or decode your json data.
If Your are sending the values as JSON POST to your controller then you must decode it.
First Check is you are getting JSON data in your controller.
If its working fine, then try for second step.
Step 1:
public function poll() {
$polldata = json_decode($_POST);
echo $polldata;
}
Step 2:
public function poll() {
$polldata = json_decode($_POST);
echo $polldata;
$pollid = $polldata->pollID;
$voteData = array(
'poll_id' => $pollid,
'poll_option_id' => $polldata->pollID->voteOpt
);
$voteSubmit = $this->modal->vote($voteData);
if($voteSubmit){
echo 'Your Vote Has Been Submitted successfully.';
}else{
echo 'You Had Already Voted.';
}
}
Let me know if you face any issues.
Your pool if should be like
if($voteSubmit){
echo json_encode(array('msg' =>'Your Vote Has Been Submitted successfully.'));
}else{
echo json_encode(array('msg' =>'You Had Already Voted.'));
}
and ur ajax success should be like
success: function(data) {
alert(data.msg);
},
error: function() {
alert("ERROR");
}
//change your Poll function
public function poll() {
$this->output->set_content_type('application/json');
$pollid = $this->input->post('pollID');
$voteData = array(
'poll_id' => $pollid,
'poll_option_id' => $this->input->post('voteOpt')
);
$voteSubmit =$this->modal->vote($voteData);
if($voteSubmit){
$this->output->set_output(json_encode(array('msg' => 'Your Vote Has Been Submitted successfully.')));
}else{
$this->output->set_output(json_encode(array('msg' => 'You Had Already Voted.')));
}
}
And a small change in success callback of Ajax
success: function(data) {
alert(data.msg);
//option to view data in console log
console.log(data);
},
Actually i've used this script to get the profile picture of instagram user
<script src="http://codeorigin.jquery.com/jquery-2.0.3.min.js"></script>
<script type="text/javascript">
var user_id = <? echo $page_id; ?>;
var url = "https://api.instagram.com/v1/users/"+user_id+"?client_id=775829274b6f48c1ac2bf218dda60e16&callback=?";
$.getJSON(url, function(data) {
$("body").append("<img src='"+data.data.profile_picture+"' />");
}
);
</script>
The Output of this script is 100% what i need.
All i need now is to take the image link to a PHP variable which is (+data.data.profile_picture+)
if tried to reload the same page with + ?link="+data.data.profile_picture+"
so i can grab it with $_GET['link']
Like this:
window.location.href = location.href + '?link="+data.data.profile_picture+";
but it doesn't .. What should i do to pass this javascript variable to a PHP variable.
Try This
window.location.href = location.href + '?link='+data.data.profile_picture;
You need to send your data to the PHP, and the simplest way would be using jQuery.ajax().
var picture = data.data.profile_picture;
$("body").append("<img src='"+picture+"' />");
$.ajax({
url: "http://example.com/webservices/getProfilePicture.php",
type: "POST",
data: {
'profile_picture': picture
},
success: function () {
console.log('Success!');
// Place eventual post-treatment here
},
error: function () {
console.log('Error..');
// Place eventual error-handling / debugging here
}
}
);
});
Then in PHP you can access it with this:
<?php $profile_picture = $_REQUEST['profile_picture']; ?>
I have simple code in GoogleOauth2.js file
function storedAccsessToken(token) {
$.ajax({
type: "GET",
url: '<%=HttpContext.Current.Request.ApplicationPath %>/SaveToken.ashx?accToken=' + token,
dataType: "text",
complete: function (resp, status) {
if (status == "success" || status == "notmodified") {
if (resp.responseText != '');
alert(resp.responseText);
window.location = window.location;
}
}
});
}
and
function refresh() {
var akkToken = '<%=Session["googleAccToken"]%>';
$.ajax({
url: 'https://www.googleapis.com/oauth2/v1/userinfo?access_token=' + akkToken,
data: null,
success: function (resp) {
user = resp;
alert(user.name);
},
dataType: "jsonp"
});
}
when i put js file in teg head
<head runat="server">
<title></title>
<script type="text/javascript" src="Scripts/jquery-1.8.2.min.js"></script>
<script src="Scripts/GoogleOauth2.js" type="text/javascript"></script>
</head>
and when i start my project and debug js i see that <%=Session["googleAccToken"]%>
compilator understand this as text
but when i put js code in head tag between simple <script type="text/javascript"></script> it work fine and i get my value in session i want to know can i keep this code
in separate file and that it worked fine
Your error is that you have include the <%= %> inside the javascript .js files, and they are not compile to give the results you expect - they stay as they are.
There are two possible solutions to that.
Ether include the variables before the javascript file, ether full move it to the page so the <%= %> can be compile. For example, you can do that :
<head runat="server">
<script type="text/javascript" src="Scripts/jquery-1.8.2.min.js"></script>
<script>
var akkToken = '<%=Session["googleAccToken"]%>';
var UrlTo = '<%=HttpContext.Current.Request.ApplicationPath %>SaveToken.ashx?accToken=';
</script>
<script src="Scripts/GoogleOauth2.js" type="text/javascript"></script>
</head>
and remove the akkToken from the GoogleOauth2.js file, and place url:UrlTo + token on the other line that also have the <%= %>
It's because in the latter case the javascript was processed by .NET. When the script is part of the .NET page the <%= %> tags are processed and replaced by whatever value is calculated.
When the script is an external file, it's requested by the browser separately (and even cached by the browser on subsequent page visits) and so .NET will not be processing it, resulting in the string '<%=Session["googleAccToken"]%>'.
I have a django url : '127.0.0.1:8000/showsym' mapped to view returning json response
def get_symptoms(request):
bp=BodySubPart.objects.get(body_subpart="head")
data1=bp.symptoms.all()
data = serializers.serialize('json', data1)
return HttpResponse(data,mimetype='application/json')
now i am trying to parse this in ajx_form.html and code for that is :
<html>
<head>
<title>Hist</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript"></script>
</head>
<body>
<script type="text/javascript">
(function() {
$.get('127.0.0.1:8000/showsym/', function(data1) {
alert(data1);
});
});
</script>
</body>
</html>
but it is not giving me any output
the page is coming blank
please help me here somebody
It is because your code tries to get the url: /127.0.0.1:8000/showsym/
Change 127.0.0.1:8000/showsym/ to /showsym/.
I suggest you use $.getJSON and name urls, assuming the url name of /showsym is showsym:
$(document).ready(function() {
$.getJSON('{% url showsym %}', function(data, textStatus, jqXHR) {
alert(data);
})
})