How to print json console.log data in browser? - javascript

I'm trying to output Json data in browser using javascript but i was only able to output in console.log i don't know what to search of. I'm a beginner in javascript please help me out here.
script.js
$(document).ready(function() {
var url = 'http://api.themoviedb.org/3/',
mode = 'movie/',
movie_id,
key = '?api_key=e9dfeccf734a61b9a52d9d7660f0d0a1';
$('button').click(function() {
var input = $('#movie').val(),
movie_id = encodeURI(input);
$.ajax({
type: 'GET',
url: url + mode + movie_id + key,
async: false,
jsonpCallback: 'testing',
contentType: 'application/json',
dataType: 'jsonp',
success: function(json) {
console.dir(json);
},
error: function(e) {
console.log(e.message);
}
});
});
});
index.php
<input id="movie" type="text" /><button>Search</button>
This code output all the data in console.log but i wanna do is it should display data in browser and i wanna output some specific objects like title of movie and overview and image.

Retrieve the specific values using key and show it. The object have keys and values. Doing object.key will give the value
$(document).ready(function() {
var url = 'https://api.themoviedb.org/3/',
mode = 'movie/',
movie_id,
key = '?api_key=e9dfeccf734a61b9a52d9d7660f0d0a1';
$('button').click(function() {
var input = $('#movie').val(),
movie_id = encodeURI(input);
$.ajax({
type: 'GET',
url: url + mode + movie_id + key,
async: false,
jsonpCallback: 'testing',
contentType: 'application/json',
dataType: 'jsonp',
success: function(json) {
$("#title").text(json.title);
//$("#movTitle").prop('src'); // add image path here
$("#overview").text(json.overview) //overview is a key
},
error: function(e) {
console.log(e.message);
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="movie" type="text" /><button>Search</button>
<!-- Search This: 346364 -->
<div id="title">
</div>
<div>
<img id="movTitle" src="" alt="">
</div>
<div id="overview">
</div>

To output your JSON data to the browser, you need to modify the HTML of the page.
First, add a few elements to your index.php like so:
index.php
<input id="movie" type="text" /><button>Search</button>
<h1>Movie info:</h1>
<p>Movie title: <span id="movie-title"></span> </p>
<p>Movie budget: <span id="movie-budget"></span> </p>
Then, in your success callback that you are defining in the jQuery ajax request, you can grab the span elements and replace their text by using jQuery's text function like so:
$(document).ready(function() {
var url = 'http://api.themoviedb.org/3/',
mode = 'movie/',
movie_id,
key = '?api_key=e9dfeccf734a61b9a52d9d7660f0d0a1';
$('button').click(function() {
var input = $('#movie').val(),
movie_id = encodeURI(input);
$.ajax({
type: 'GET',
url: url + mode + movie_id + key,
async: false,
jsonpCallback: 'testing',
contentType: 'application/json',
dataType: 'jsonp',
success: function(json) {
// grab the span elements by ID and replace their text with the json text
$("#movie-title").text(json.title);
$("#movie-budget").text(json.budget);
console.dir(json);
},
error: function(e) {
console.log(e.message);
}
});
});
});

Related

Profile image not loading from delve on Sharepoint

I'm trying to get the profile image from delve and display it on a Sharepoint page using Javascript,the problem i'm getting is that the image isn't loading always
var profileimage="https://eur.delve.office.com/mt/v3/people/profileimage?userId="+userInfo["SPS-ClaimID"]+"&size=L";
If you want to display the profile image, we can use the url as below.
var profileimage="/_layouts/15/userphoto.aspx?size=L&username=lz#tenant.onmicrosoft.com";
Example code:
<script src="//code.jquery.com/jquery-3.1.0.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
var url = _spPageContextInfo.webAbsoluteUrl + "/_api/web/siteusers?$select=Id,Title,Email";
$.ajax({
url: url,
method: "GET",
async: false,
headers: { "Accept": "application/json; odata=verbose" },
success: function (data) {
var items=data.d.results;
var options="<option>--select a user--</option>";
for(var i=0;i<items.length;i++){
if(items[i].Email!=""){
options+="<option value='"+items[i].Email+"'>"+items[i].Title+"</option>";
}
}
$("#SiteUsers").html(options);
},
error: function (data) {
}
});
$("#SiteUsers").change(function(){
var html="";
if($(this).val()!=null&&$(this).val()!=""){
html+="<img src='/_layouts/15/userphoto.aspx?size=L&username=" + $(this).val() + "'/>";
}
if($(this).children(':selected').text()!=""){
html+="<p><span>Name:"+ $(this).children(':selected').text()+"</span></p>";
}
$("#UserInfomation").html(html);
});
});
</script>
<select id="SiteUsers"><option>--select a user--</option></select>
<div id="UserInfomation"></div>

jquery ajax form submit with edit values

I have a datatable where I have the detail column with an edit button. When the user clicks on the edit am passing the id as a parameter. I am fetching all the values for that id and displaying in the form. Now when I edit the values and submit the form using PUT method it is getting inserted in the table, the values are passing as a parameter and it shows the empty form. How to solve this issue.
HTML:
<form class="container" id="myform" name="myform" novalidate>
<div class="form-group row">
<label for="position" class="col-sm-2 col-form-label fw-6">Position</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="position" name="position" placeholder="Position" required>
</div>
</div>
<div class="form-group row">
<label for="location" class="col-sm-2 col-form-label fw-6">Location</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="location" name="location" placeholder="Location" required>
</div>
</div>
<div class="form-group row">
<div class="col-sm-10">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</div>
</form>
PUT Method Script:
<script type='text/javascript'>
$(document).ready(function(){
$("#myform").submit(function(e) {
var parms = {
position : $("#position").val(),
location : $("#location").val()
};
var par_val;
var param_id = new window.URLSearchParams(window.location.search);
par_val = param_id.get('id');
console.log(par_val);
var par_url = par_val;
$.ajax({
url: "http://localhost:3000/joblists/"+par_val,
method: 'PUT',
async: false,
dataType : "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(parms),
success: function(data){
console.log('Submission was successful.');
console.log(data);
},
error: function (data) {
console.log('An error occurred.');
console.log(data);
},
})
});
});
</script>
GET method script:
<script type="text/javascript">
$(document).ready(function(){
var id_val;
var params = new window.URLSearchParams(window.location.search);
id_val = params.get('id');
console.log(id_val);
var url1=id_val;
$.ajax({
url: "http://localhost:3000/joblists/"+id_val,
type: "GET",
dataType: "json",
success: function (data) {
// alert(JSON.stringify(data));
console.log(typeof(data));
$("#position").val(data.position);
$("#location").val(data.location);
},
error: function(data) {
console.log(data);
}
});
});
</script>
After submitting the form the page should remain the same with edit form values. only the edited values should be inserted. How to achieve this.
$('#myform').on('submit', function (e) {
e.preventDefault();
..........
I have checked your code in my editor. There are some changes which i made in ajax request, and it now works for me. here is the code. Try it
<script type='text/javascript'>
$(document).ready(function(){
$("#myform").submit(function(e) {
e.preventDefault();
var parms = {
position : $("#position").val(),
location : $("#location").val()
};
var par_val;
var param_id = new window.URLSearchParams(window.location.search);
par_val = param_id.get('id');
console.log(par_val);
var par_url = par_val;
$.ajax({
url: "http://localhost:3000/joblists/"+id_val,
method: 'POST', //or you can use GET
dataType : "json", //REMOVED CONTENT TYPE AND ASYNC
data: {send_obj:JSON.stringify(parms)}, //ADDED OBJECT FOR DATA
success: function(data){
console.log('Submission was successful.');
console.log(data);
},
error: function (data) {
console.log('An error occurred.');
console.log(data);
},
})
});
});
</script>
Adding prevent default in form submit handle is enough. You're handling the post request by ajax call.
e.preventDefault();
There are 2 changes in your code.
This code will prevent your page from reloading and also you are not sending the data in proper format.
$("#myform").submit(function(e) {
e.preventDefault(); // 1. Dont reload the page
var parms = {
position : $("#position").val(),
location : $("#location").val()
};
var par_val;
var param_id = new window.URLSearchParams(window.location.search);
par_val = param_id.get('id');
console.log(par_val);
var par_url = par_val;
$.ajax({
url: "http://localhost:3000/joblists/"+par_val,
method: 'PUT',
async: false,
dataType : "json",
contentType: "application/json; charset=utf-8",
data: parms, // 2. Just send the parms object bcoz you already defined the dataType as json so it will automatically convert it into string.
success: function(data){
console.log('Submission was successful.');
console.log(data);
},
error: function (data) {
console.log('An error occurred.');
console.log(data);
},
})
});

Jquery Ajax Call to send data to the method when the a href clicked

I am trying to send the language type clicked from my master page into the surfacecontroller in the App_code folder. My HTML is like this below:
<div class="navbar-topbar clearfix">
<div class="h5 pull-right">
<span class="linkCA">
<strong>CA</strong>
<a class="lang=en-CA" href="#NewUrlLink">EN</a> |
<a class="lang=fr-CA" href="#NewUrlLink">FR</a>
</span>
<span class="linkUS">
<strong>US</strong>
<a class="lang=en-US" href="#NewUrlLink">EN</a>
</span>
</div>
</div>
So what I am thinking is getting the class name and send it via AJAX call when the a is clicked. I have this method which I want to pass the type of language clicked to:
public string GetDictionaryItemByCulture(string key, string language)
{
var currentLang = System.Threading.Thread.CurrentThread.CurrentCulture.ToString();
var otherLang = myCulture(language);
System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo(otherLang);
System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo(otherLang);
// String noLastSegment = Request.Url.AbsolutePath;
string x = new UmbracoHelper().GetDictionaryValue(key);
System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo(currentLang);
System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo(currentLang);
return x;
}
I saw this AJAX method online which looks like what I need but I don't know how to wire it to work with my need .
$(document).ready(function() {
// Add the page method call as an onclick handler for the div.
$("#Result").click(function() {
$.ajax({
type: "POST",
url: "Default.aspx/GetDate",
data: { someParameter: "some value" },
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
// Replace the div's content with the page method's return.
$("#Result").text(msg.d);
}
});
});
});
Firstly it would be better practice to place the locale value in a data-* attribute in your HTML, with each a given a common class which the event handler can be attached to:
<div class="navbar-topbar clearfix">
<div class="h5 pull-right">
<span class="linkCA">
<strong>CA</strong>
<a data-lang="en-CA" class="lang-trigger" href="#NewUrlLink">EN</a> |
<a data-lang="fr-CA" class="lang-trigger" href="#NewUrlLink">FR</a>
</span>
<span class="linkUS">
<strong>US</strong>
<a data-lang="en-US" class="lang-trigger" href="#NewUrlLink">EN</a>
</span>
</div>
</div>
From there you can hook to the click of the a, read the data-lang attribute and send the information:
$('.lang-trigger').click(function() {
var $a = $(this);
$.ajax({
type: "POST",
url: "GetDictionaryItemByCulture/",
data: {
key: 'whatever this value should be...',
lang: $a.data('lang')
},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
console.log(msg);
}
});
});

AJAX Delete Not Working Entity Framework

I wonder why its not working, here is the code
View
<input type="button" value="Delete" onclick="deletefunction(#item.PhotoId)"/>
Controller
[HttpPost]
public ActionResult Delete(int photoid)
{
var imgDelete = db.Photos.Where(x => x.PhotoId == photoid).FirstOrDefault();
if (imgDelete == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
db.Photos.Remove(imgDelete);
db.SaveChanges();
System.IO.File.Delete(AppDomain.CurrentDomain.BaseDirectory + imgDelete.ImagePath);
System.IO.File.Delete(AppDomain.CurrentDomain.BaseDirectory + imgDelete.ThumbPath);
return null;
}
JQUERY/AJAX
<script type="text/javascript">
$(document).ready(function () {
function deletefunction(photoid) {
$.ajax({
url: '#Url.Action("Delete")',
type: 'POST',
data: { photoid: photoid },
success: function (result) {
alert: ("Success")
},
error: {
alert: ("Error")
}
});
};
});
</script>
im new to jquery and ajax, im trying to delete the photo without refreshing the page, am i in the correct path?
I would suggest to attach click event to your button instead of writing javascript in markup. Consider the below markup:
<input type="button" class="delete" value="Delete" data-picid="#item.photoId"/>
Now attach a click event to .delete as below:
$('.delete').on('click',function(){
var photoId=$(this).attr('data-picid');//gets your photoid
$.ajax({
url: '#Url.Action("Delete")',
type: 'POST',
data: JSON.stringify({ photoid: photoId }),
contentType: "application/json; charset=utf-8",
dataType: "json", //return type you are expecting from server
success: function (result) {
//access message from server as result.message and display proper message to user
alert: ("Success")
},
error: {
alert: ("Error")
}
});
});
Your Controller then:
[HttpPost]
public ActionResult Delete(int photoid)
{
var imgDelete = db.Photos.Where(x => x.PhotoId == photoid).FirstOrDefault();
if (imgDelete == null)
{
return Json(new{ message=false},JsonRequestBehavior.AllowGet);//return false in message variable
}
db.Photos.Remove(imgDelete);
db.SaveChanges();
System.IO.File.Delete(AppDomain.CurrentDomain.BaseDirectory + imgDelete.ImagePath);
System.IO.File.Delete(AppDomain.CurrentDomain.BaseDirectory + imgDelete.ThumbPath);
return Json(new{ message=false},JsonRequestBehavior.AllowGet); //return true if everything is fine
}
Once photo is deleted based on the success or failure your can do it as below in success of ajax, but before that store a reference to yourbutton` as below:
$('.delete').on('click',function(){
var photoId=$(this).attr('data-picid');//gets your photoid
var $this=$(this);
$.ajax({
url: '#Url.Action("Delete")',
type: 'POST',
data: JSON.stringify({ photoid: photoId }),
contentType: "application/json; charset=utf-8",
dataType: "json", //return type you are expecting from server
success: function (result) {
if(result.message)
{
$this.closest('yourrootparentselector').remove();
//here yourrootparentselector will be the element which holds all
//your photo and delete button too
}
},
error: {
alert: ("Error")
}
});
});
UPDATE
Based on your given mark up you I suggest to add one more root parent for your each image and delete button as below:
<div style="margin-top: 17px;">
<div id="links">
#foreach (var item in Model.Content)
{
<div class="rootparent"> <!--rootparent here, you can give any classname-->
<a href="#item.ImagePath" title="#item.Description" data-gallery>
<img src="#item.ThumbPath" alt="#item.Description" class="img-rounded" style="margin-bottom:7px;" />
</a>
<input type="button" class="delete" value="Delete" data-picid="#item.PhotoId" />
</div>
}
</div>
</div>
Now you can write this in success
$this.closest('.rootparent').remove()
Try this.
<script type="text/javascript">
$(document).ready(function () {
});
function deletefunction(photoid) {
$.ajax({
url: '#Url.Action("Delete")',
type: 'POST',
contentType: "application/json; charset=utf-8",
dataType: "json",
data: { photoid: photoid },
success: function (result) {
alert: ("Success")
},
error: {
alert: ("Error")
}
});
}
</script>

Can not seem to pass more than one variable with jquery to mysql

I have seen several examples and can't seem to get the hang of passing more than one variable to mysql using jquery. Here is my situation:
I have a page with 2 cascading drop downs,( they work great using jquery to update second drop down based on the first drop down.)
when the first drop down is selected jquery updates the second drop down AND passes the customer id to a php script that creates a new record in the tblinvoice table (this also works great no problems.)
when the second drop down is selected I need to pass that value along with the invoice number to my php script so I can update the record with the instid.(this is the part that don't work)
If I only pass the instid and manually put the invoice number in the where clause of the query all works fine. If I omit the where clause all records are updated as expected. I need to know what I am doing wrong or what is missing.
I will try to post the code here
jquery code
$(document).ready(function() {
$("select#cust").change(function() {
var cust_id = $("select#cust option:selected").attr(
'value');
var test = $("#test").val();
var din = $("#idate").val();
$("#inst").html("");
if (cust_id.length > 0) {
$.ajax({
type: "POST",
url: "fetch_inst.php",
data: "cust_id=" + cust_id,
cache: false,
beforeSend: function() {
$('#inst').html(
'<img src="loader.gif" alt="" width="24" height="24">'
);
},
success: function(html) {
$("#inst").html(html);
}
});
if (test == 0) {
$.ajax({
type: "POST",
url: "wo_start.php",
data: "cust_id=" + cust_id,
cache: false,
beforeSend: function() {
},
success: function(html) {
$("#invoice").html(html);
$("#test").val(1);
var inum = $("#inv").val();
$("#invnum").val(din +
"-" + inum);
}
});
}
}
});
$("select#inst").change(function() {
var inst_id = $("select#inst option:selected").attr(
'value');
var custid = $("select#cust option:selected").attr(
'value');
var invid = # ("#inv").val()
if (inst_id.length > 0) {
$.ajax({
type: "POST",
url: "wo_start.php",
data: {
inst_id: inst_id,
}
cache: false,
beforeSend: function() {
},
success: function() {
}
});
}
});
});
I have tried using data: {inst_id:inst_id,custid:custid,invid:invid,} (no update to the table like this)
I also tried data: "inst_id="+inst_id+"&custid="+custid+"&invid="+invid,(this also gives no results.)
Can someone PLEASE look at this jquery and see if I am making a simple error?
Try this format:
data: { inst_id: inst_id, custid: custid, invid: invid },
You can post a JSON object to the server so long as you serialize it and then let the server know the data type.
First you need to define your JSON object:
var postData = { inst_id: inst_id, custid: custid, invid: invid };
Then update your ajax to use the serialized version of that object and let the server know the data type:
$.ajax({
type: "POST",
url: "fetch_inst.php",
data: JSON.stringify(postData),
contentType: "application/json",
..continue the rest of your ajax....

Categories