themoviedb JSON API with jQuery - javascript

I'm trying to do something that seems like it should be simple. Get the input of a text field and search the themoviedb.org database for it via the API.
I'm using jQuery and the themoviedb.org APIv3, which supports JSONP. All I get, though, is this response:
{"status_code":6,"status_message":"Invalid id - The pre-requisite id is invalid or not found"}
That doesn't really tell me a lot. ID of what?
Things I know:
I have the right API key
The search button is submitting and getting the value of the input correctly
Here's a jsfiddle, and here's the API documentation about searching movies. Also, check out this version of the API docs. I think it has to do with the query params.
Really, I have no idea what I'm doing with JSON, so I'm hoping this will be a representative example that will help me understand it.

You just need the correct number of query string parameters. The required paramaters are query and api_key. I found these requirements here http://docs.themoviedb.apiary.io/#get-%2F3%2Fsearch%2Fmovie. Give this a try instead:
$(document).ready(function() {
var url = 'http://api.themoviedb.org/3/',
mode = 'search/movie?query=',
input,
movieName,
key = '&api_key=470fd2ec8853e25d2f8d86f685d2270e';
$('button').click(function() {
var input = $('#movie').val(),
movieName = encodeURI(input);
$.ajax({
type: 'GET',
url: url + mode + input + key,
async: false,
jsonpCallback: 'testing',
contentType: 'application/json',
dataType: 'jsonp',
success: function(json) {
console.dir(json);
},
error: function(e) {
console.log(e.message);
}
});
});
});​
Working Fiddle: http://jsfiddle.net/fewds/srdHD/3/
Note: Since thats most likely your REAL api key I would suggest requesting a new one!

The URL you use is not correct, your examples generates the following request:
http://api.themoviedb.org/3/search/MOVIENAME?api_key=APIKEY
but according to the API documentation it should look like this:
http://api.themoviedb.org/3/search/movie?api_key=APIKEY&query=MOVIENAME
I have forked and updated your jsfiddle

Need the correct number of query parameters. The required paramaters are query and api_key
If you are getting error on this by urlencode or decodeing please check your url at urlencode.in or urldecode.in

Related

Ajax doesn't get to success function. Always error function. It fails to post data to another file

Please be patient. This is my first post as far as I remember.
This is a part of my calendar.js script. I'm trying to POST data that I fetch from modal window in index.php to sql.php.
function saveModal() { /*JQuery*/
var current_date_range = $(".modal-select#daterange").val();
var current_room_number = $("#mod-current-room-number").val();
var current_room_state = $("#mod-current-room-state").val();
var myData = {"post_date_range": current_date_range, "post_room_number": current_room_number, "post_room_state": current_room_state};
var myJSON = JSON.stringify(myData);
$.ajax({
type: "POST",
url: "sql.php",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
data: myJSON,
beforeSend: function() {
$("#ajax").html("<div class='loading'><img src='/images/loader.gif' alt='Loading...' /></div>");
},
success: function(result){
$("#ajax").empty();
$("#ajax").html(result);
$("#ajax").fadeIn("slow");
window.location.reload(true);
},
error: function(){
alert(myJSON);
$("#ajax").html("<p class='error'> <strong>Oops!</strong> Try that again in a few moments.</p>");
}
})
}
I get the data just fine (as you can see I have checked in the error: function() with alert(myJSON);). It looks like this: {"post_date_range":"12/19/2018 - 12/28/2018","post_room_number":"118","post_room_state":"3"}. Nevermind that the daterangepicker.js returns dates in the hideous MM/DD/YYYY format, which I would very much like to change to YYYY-MM-DD. The real problem is, the code never gets to success: function().
Now my sql.php is in the same folder as calendar.js and index.php.
In sql.php I try to retrieve those values with:
$currentDateRange = $_REQUEST['post_date_range'];
$currentRoomNumber = intval($_REQUEST['post_room_number']);
$currentRoomState = intval($_REQUEST['post_room_state']);
I have checked many other SO Q&As and none have helped me solve my problem. I don't see any spelling errors. It's not disobeying same origin policy rule. I don't want to use jQuery $.post function. Anyone sees the obvious solution?
You want to send array in post rather than the string so directly send myData to get array value in your PHP file rather converting to JSON string It would work with your current PHP file as you require.
You should specify a POST key for the JSON data string you are sending:
var myJSON = JSON.stringify(myData);
(...)
$.ajax({
(...)
data: 'data=' + myJSON,
You need to parse (decode) this string in your PHP file to be able to use it as an array/object again:
$data = json_decode($_REQUEST['data']);
$currentDateRange = $data['post_date_range'];
$currentRoomNumber = intval($data['post_room_number']);
$currentRoomState = intval($data['post_room_state']);
Also, dataType in jQuery.ajax function is specified as "The type of data that you're expecting back from the server." according to jQuery documentation. As far as I can tell from your code, you might rather expect something else as your response, so try excluding this line.
I am sorry to have burdened you all. It's my third week programming so my lack of knowledge is at fault.
I did not know how dataflow works between AJAX and PHP in the URL...
While I was searching for other errors, I printed or echoed out many different things. The PHP file should echo only 1 thing, although it can be an array with multiple values.
Like this for example:
$return_arr = array("sql"=>$sql1, "result"=>$result, "out"=>$out);
echo json_encode($return_arr);
I appologize again.

How to get a site's URL by its title in Sharepoint 2013?

I need to link to a given site's Documents Library, I know I simply need to append the /Shared%20Documents/Forms/AllItems.aspx to the site URL, however how can I get that site URL with just its title?
I've tried using _api/Web/Lists/getByTitle('<Page Title>')/ but I get an error saying that the list does not exist in the site even though I can veryify in the site configuration that is indeed the title.
I wasn't completely sure what you were trying to do based on your question; but after reading the answer you provided, you need use the OData $filter query option:
function setDepartmentLink(department){
$.ajax({
url: "_api/web/webs?$select=Url&$filter=Title eq '" + department + "'",
type: "GET",
headers: { "accept": "application/json;odata=verbose" },
success: function (data) {
if(data.d.results.length > 0){
$("#SPDDeptFolderLink").text(department).prop("href", encodeURI(data.d.results[0].Url + "/Shared Files/Forms/AllItems.aspx"));
}
}
});
}
Try with the correct name of the list
/_api/Web/Lists/GetByTitle('listname')/Items
The above api will result the all items in a list.
OR try with GUID of the list
/_api/Web/Lists(guid'guid id of your list')
If you are looking for list guid,
1.Go to the list in the site
2.Click the LIST or LIBRARY tab and click LIST/LIBRARY Settings
3.Look in the browser’s address bar and you will see something like this:
http://yourserver/sites/training/_layouts/listedit.aspx?List=%7B81588B61%2D860D%2D4487%2DB81F%2DA1846A37954B%7D
4.Copy everything after the “List=” and paste into Notepad
You should now have something like this in Notepad:
%7B81588B61%2D860D%2D4487%2DB81F%2DA1846A37954B%7D
5.The GUID you copied is encoded. You now need to clean this up
1.Delete the “%7B” at the beginning
2.Delete the “%7D” at the end
3.Do a search and replace and change “%2D” to “-“ (a dash)
Managed to do it with the following method:
function setDepartmentLink(department){
$.ajax({
url: "_api/web/webs",
type: "GET",
headers: { "accept": "application/json;odata=verbose" },
success: function (data) {
data.d.results.forEach(function (site) {
if(site.Title === department){
$("#SPDDeptFolderLink").text(department).prop("href", encodeURI(site.Url + "/Shared Files/Forms/AllItems.aspx"));
}
})
}
}
Since I wasn't able to find a method that returned a site's URL given its title I decided to iterate over all the sites and simply look for the title.

Ajax request not passing parameter to ASP.NET MVC controller

Tried looking in stackoverflow because this looked so trivial. Found many similar questions and read through them. Found no solution using these examples. Here is my code, can anyone help?
function testAjax() {
return $.ajax({
type: "GET",
url: '#Url.Action("Nodes","Competence", new { userId = Sven });',
contentType: "application/json;charset=utf-8",
dataType: "json"
});
}
var promise = testAjax();
promise.success(function (data) {
var dataConverted = JSON.stringify(data);
$('#tree').treeview({ data: dataConverted, multiSelect: true });
});
ASP.NET MVC method
public JsonResult Nodes(string userId)
{
var temp = userId;
var list = new List<Node>();
list.Add(new Node("Test1"));
list.Add(new Node("Test2"));
list.Add(new Node("Test3"));
return Json(list, JsonRequestBehavior.AllowGet);
}
EDIT:
Just before I was about to turn crazy on Halloween night, i figured out to try in a new session. Turns out it was just a caching problem..Thanks for the help everyone
Since your server may not expecting a request with JSON content, try removing the contentType parameter on your ajax call. Its default value is "application/x-www-form-urlencoded; charset=UTF-8" and is fine for most cases.
It's type should be "POST"
return $.ajax({
type: "POST",
url: '#Url.Action("Nodes","Competence")',
data: { userId: "Test" },
contentType: "application/json;charset=utf-8",
dataType: "json"
});
As it's a GET verb, it'll be easiest to pass this in as a querystring value. This also conforms better with a RESTful design.
For example replace #Url.Action("Nodes","Competence")
with
#Url.Action("Nodes","Competence", new { userId = id });
Then you can delete the data property. This will append ?userId=valueOfId into your url and then it should be mapped correctly to your action with the userId correctly populated.
Update
As #freedomn-m stated:
This will generate the url when the view is built server-side. If the
parameters never change, then fine - but it's relatively unlikely that
the parameters won't change, in which case you should add the url
parameters at runtime if you want them on querystring.
This is completely accurate. Without knowing your exact implementation I can only make assumptions. But technically you could wrap your ajax call in a function and then you could either pass in the userId and generate the url within that function or pass in the url, performing the url generation outside of the function.
This would mean that you only need one function that performs the ajax request and you can have another function that gets the userId (and possibly generates the url) and then passes that into the ajax function. How you store the userId is entirely up to you, but one thing I would suggest is investigating data attributes which is a fairly well defined way for storing data on html elements.

Passing a string array to mvc controllers using ajax

I need to pass list of strings from multiple select to the controller. Though the requirement looked very simple to me, I was breaking my head for the past hour in this. I have did a fair research on this, but unable to succeed.
Below is my Javascript code. Please ignore the comments. I was successfully able to fetch the list of items in the multiple select. While i do the ajax call, I get the error "Object reference not set an instance of an object.
function submitForm() {
var selected = $('#selectedTasks option').map(function(){
return this.value
}).get()
var postData = { selectedTasks : selected } //corrected as suggested
//selectedTasks = JSON.stringify({ 'selectedTasks': selected });
alert(postData);
$.ajax({
type: "POST",
//contentType: 'application/json; charset=utf-8',
url: '#Url.Action("AssignTasks", "MonthEndApp")',
dataType: 'json',
data: postData,
traditional: true,
success: function (data) {
alert("Success");
},
error: function (xhr) {
alert(xhr.responseText);
}
});
}
MonthEndAppController.cs
[HttpPost]
public void AssignTasks(List<String> selectedTasks)
{
//do something
}
Can someone guide me where exactly I have gone wrong? Can someone suggest me what is wrong?
EDIT : As suggested by Mr. Rory I have made the java script changes. Now the Java script part works absolutely fine. But the Controller is not getting called when the ajax request is made. Can someone help me out if something wrong in the call made to controller ?
Have you tried with string[] instead of List<String> ?
The parameter your AssignTasks action is expecting is called selectedTasks, not values:
var postData = { selectedTasks: selected };
Also note that when debugging anything in JS you should always use console.log() over alert(), as the latter coerces all types to a string, which means you're not seeing a true representation of the actual value.

Jquery POST unicode string to codeigniter php

I'm trying to implement a custom suggestion engine using jquery.
I take the user input, call my codeigniter v2 php code in order to get matches from a pre-built synonyms table.
My javascript looks like this:
var user_str = $("#some-id").val();
$.ajax({
type: "POST",
url: "http://localhost/my-app/app/suggestions/",
data: {"doc": user_str},
processData: false
})
.done(function (data)
{
// Show suggestions...
});
My PHP code (controller) looks like this:
function suggestions()
{
$user_input = trim($_POST['doc']);
die("[$user_input]");
}
But the data is NOT posted to my PHP :( All I get as echo is an empty [] (with no 500 error or anything)
I've spent 2 days looking for an answer, what I've read in SO / on google didn't help. I was able to make this work using GET, but then again, this wouldn't work with unicode strings, so I figured I should use POST instead (only this won't work either :()
Anyone can tell me how to fix this? Also, this has to work with unicode strings, it's an important requirement in this project.
I'm using PHP 5.3.8
Try using the $.post method, then debug. Do it like this:
JS
var user_str = $("#some-id").val();
var url = "http://localhost/my-app/app/suggestions";
var postdata = {doc:user_str};
$.post(url, postdata, function(result){
console.log(result);
});
PHP
function suggestions(){
$user_input = $this->input->post('doc');
return "MESSAGE FROM CONTROLLER. USER INPUT: ".$user_input;
}
This should output the message to your console. Let me know if it works.
For those interested, this works for me, even with csrf_protection being set to true
var cct = $.cookie('csrf_the_cookie_whatever_name');
$.ajax({
url: the_url,
type: 'POST',
async: false,
dataType: 'json',
data: {'doc': user_str, 'csrf_test_your_name': cct}
})
.done(function(result) {
console.log(result);
});

Categories

Resources