Does anyone see anything wrong with the following:
$.ajax({
url: '/tags/ajax/post-tag/',
data: { newtaginput : $('#tag-input').val(), customerid : $('#customerid').val()},
success: function(data) {
// After posting
alert(data);
arr = data.tagsinserted.split(',');
alert(arr);
//Loop through
$.each(arr, function(n, val){
alert(n + ' ' + val)
});
}
}, "json");
tagsinserted is what's being returned, here is the full response:
{"returnmessage":"The Ajax operation was successful.","tagsinserted":"b7,b4,dog,cat","returncode":"0"}
Thanks
Anurag is right in his comment json needs to be dataType:'json'
also, unless specified, request is "GET" by default, your url suggests it is expecting post data, i.e. type:'post'
Related
I am new to using Ajax to get WordPress data.
The following code should return the server time but the response always is "400 Bad Request".
$.ajax({
url: obj + "?action=wps_get_time&format=U",
success: function(data) {
console.log(data);
}
});
Also tried it as POST and it was the same.
$.ajax({
url: obj,
method: "post",
data: { action: "wps_get_time", format: "U" },
success: function(data) {
console.log(data);
}
});
Any suggestions what's wrong please? Can't figure.
I always thought there are actions I can use always such as wps_get_time, without using a plugin. Am I wrong?
Ist there any easy way to get the server time by ajax?
Thank you all in advance.
The code below will return server time in Indochina and log it to console.
$.ajax({
type: 'GET',
cache: false,
url: location.href,
complete: function (req, textStatus) {
var dateString = req.getResponseHeader('Date');
if (dateString.indexOf('GMT') === -1) {
dateString += ' GMT';
}
var date = new Date(dateString);
console.log(date);
}
});```
Hey all here is my code i have to read an XML file from a Vimeo website:
$(document).ready(function(){
$.ajax({
type: "GET",
url: "http://vimeo.com/api/v2/video/51229736.xml",
dataType: "xml",
success: function(xml) {
$(xml).find('video').each(function(){
var thumbURL = $(this).attr('thumbnail_small');
alert(thumbURL);
$('#vidThumb').html('<img src="' + thumbURL + '">');
});
},
error: function(err) {alert('err');}
});
});
The XML looks like this:
<videos>
<script/>
<video>
<id>51229736</id>
<title>CHATT HISTORY CENTER FILMS CAVALIER</title>
<description/>
<url>http://vimeo.com/51229736</url>
<upload_date>2012-10-11 13:08:51</upload_date>
<thumbnail_small>http://b.vimeocdn.com/ts/353/072/353072229_100.jpg</thumbnail_small>
<thumbnail_medium>http://b.vimeocdn.com/ts/353/072/353072229_200.jpg</thumbnail_medium>
......
</video>
</videos>
Problem being is that it errors out. I'm sure its because of the different domain name trying to read it so how can i fix that in order to do that?
You can not do that through jQuery's ajax across different domains using XML , you can use callback=? to get jsonp response back like in the other answer , if it is possible to get json response from that url
You should have no problem getting an XML response from your server side , you should probably try that route
Achieved it by doing the following:
var vimeoVideoID = '51229736';
$.getJSON('http://www.vimeo.com/api/v2/video/' + vimeoVideoID + '.json?callback=?', {format: "json"}, function(json) {
$("#vidThumb").attr('src', json[0].thumbnail_small);
});
I think the answer is in setting the callback to "?" at least it usually is for me. This at least works with JSON. And if it were JSON, this is how I would do it:
var query = 'http://vimeo.com/api/v2/video/51229736.xml&callback=?';
$.ajax({
url: query,
type: 'GET',
dataType: 'json',
success: function(s) {
console.log('success' + s)
},
error: function(e) { console.log('something went wrong!', e)}
});
My question is when I use jQuery ajax get, I am getting data at response body however it doesn't pass into success function. How can I make it work?
I am making an ajax put but it doesn't work at ie9 (works on other browsers) so I changed it like that just for test:
$.ajax({
async : false,
type: 'PUT',
contentType: 'application/json',
url:updateUrl + "?_" + new Date().getTime(),
data: JSON.stringify(model),
cache: false,
dataType: "json",
dataFilter: function(data) {
var resp = eval('(' + data + ')');
return resp;
},
success: function(data, status, xhr) {
alert("success> " + data.property);
alert(typeof data);
r = resultResponse(data);
},
error: function(data, status, xhr) {
alert("error> " + data.responseText);
try {
r = error($.parseJSON(data.responseText));
} catch (err) {
//Handle error
}
}
});
data is alerting as undefined. My put data is sending correctly, my server side works well and send response to client however I get undefined instead of data. After some tests I realized the problem:
When I capture network communication packets at ie 9 response body is what I want. However success function can not handle it. If needed, I can give more information about my server(I could make it work when I write the data to response instead of using jackson json mapper at Java - it was working and the only difference was that was not included ta working version at response headers:
Key Value
Content-Type application/json;charset=UTF8 )
I think that the problem can be handle at client side, I think not with server side.
Any ideas?
EDIT: I tried that style:
$.ajax({url: "/url",
dataType: "text",
success: function(text) {
json = eval("(" + text + ")");
// do something with JSON
}
});
However response header is still:
Key Value
Content-Type application/json;charset=UTF8
The problem was wrong charset. It was UTF( instead of UTF-8).
I'm trying to delve into the depths of the murky world of Tumblr, and can't understand how to get over the following error:
Uncaught SyntaxError: Unexpected token :
I believe it may be because I'm getting back json, but trying to use jsonp. Here's what I'm trying to send:
$(function(){
$.ajax({
type: "GET",
url : "http://api.tumblr.com/v2/blog/MyTumblrName.tumblr.com/info",
dataType: "jsonp",
data: {
api_key : "MyTumblrApi"
},
success: function(data){
console.log(data);
},
});
});
I get a 200 OK response, and the data but still the above error (which I don't understand and would like to know more about)
Tumblr also kindly points out the following, but I'm unclear on the specifics.
All requests made with HTTP GET are JSONP-enabled. To use JSONP,
append jsonp= and the name of your callback function to the request.
JSONP requests will always return an HTTP status code of 200 but will
reflect the real status code in the meta field of the JSON response.
Any help would be awesome, thanks!
Do what Tumblr is telling you to - add a callback function name to the request
myJsonpCallback = function(data)
{
console.log(data);
}
$.ajax({
type: "GET",
url : "http://api.tumblr.com/v2/blog/MyTumblrName.tumblr.com/info",
dataType: "jsonp",
data: {
api_key : "MyTumblrApi",
jsonp : "myJsonpCallback"
}
});
========================================================
EDIT: The console.log thing is a syntax error since I didn't actually test this code.
What happens to success? I don't really know. Try and find out :) It will probably be called but data parameter likely be null or something.
The issue here is that jQuery names it's callback parameter callback, where as Tumblr is expecting jsonp. Upon 200 response jQuery likely simply eval()s the response, which is why myJsonpCallback is actually called.
In case you don't want to use jQuery:
var tumblrFeed = document.createElement('script');
tumblrFeed.setAttribute("src", "http://api.tumblr.com/v2/blog/{blog.tumblr.com}/posts?api_key={your api key}&jsonp=callback");
document.getElementsByTagName("head")[0].appendChild(tumblrFeed)
function callback(data){
console.log(data);
}
I've created simple function for this purpose:
function jsonpRequest(opt){
var params = "";
var blogName = "{your blog name}";
var api_key = "{api key}";
if("selector" in opt){params = "id=" + opt.selector;}
if(("offset" in opt) && ("limit" in opt)){params = "limit=" + opt.limit + "&offset=" + opt.offset;}
if("callback" in opt){params += "&jsonp=" + opt.callback;}else{params += "&jsonp=callback";}
params += "&api_key=" + api_key;
var tumblrFeed = document.createElement('script');
tumblrFeed.setAttribute("src", "http://api.tumblr.com/v2/blog/" + blogName + "/posts?" + params);
document.getElementsByTagName("head")[0].appendChild(tumblrFeed)
}
How to use it:
jsonpRequest({offset: 50, limit: 5});
function callback(data){do stuff here ...}
Alternative usage:
jsonpRequest({offset: 50, limit: 5, callback: "nameOfMyAmazingCallbackFunction"});
function nameOfMyAmazingCallbackFunction(data){do stuff here ...}
I´m trying to write a small ajax live search for node.js. First of all here is my Clientside code:
$('#words').bind('keyup', function(){
getMatchingWords($('#words').val(), function (data){
console.log('recieved data');
console.log(data);
$('#ajaxresults').show();
});
});
function getMatchingWords(value, callback) {
$.ajax('http://127.0.0.1:3000/matchword/' + value + '/', {
type: 'GET',
dataType: 'json',
success: function(data) { if ( callback ) callback(data); },
error : function() { if ( callback ) callback(null); }
});
}
and here ist my serverside route:
app.get('/matchword/:value', function(req, res) {
console.log(req.params.value);
res.writeHead(200, {'content-type': 'text/json' });
res.write( JSON.stringify({ test : 'test'}) );
res.end('\n');
});
it works but i don´t recieve any data. data in the callback function is always null. so what i am doing wrong? thx for the help
Change
$.ajax('http://127.0.0.1:3000/matchword/' + value + '/', {
to
$.ajax('/matchword' + value + '/', {
What's the URL that you're making the $.ajax() request from? If the page containing that client-side JS wasn't also loaded from 127.0.0.1:3000, the error you're seeing is due to the same-origin requirement on AJAX requests.
hey better late than never...
I was looking at your problem because I am also trying to put a simple live search together with an express.js back end.
first of all I put your url into a local variable. As I don't think that was your problem.
Particularly if your express / node log was showing a 200 response. then the url was fine...
It seems your function wasn't returning data (correct ?) if so try this.
var search_url = "..."// your url
function getMatchingWords(value, callback) {
$.ajax(search_url, {
type: 'GET',
dataType: 'json',
success: function (data, textStatus, jqXHR) {
var returned_data = data;
console.log("returned_data ="+returned_data);//comment out or remove this debug after test
callback(returned_data);
},
error: function( req, status, err ) {
console.log( 'something went wrong', status, err );
}
});
}
you might also need to add / modify your headers subject to the set up...
headers : { Authorization : auth },
type: 'GET',
dataType: 'json',
crossDomain:true,
the auth variable being an encoded auth pair somewhere else in your code (if your web service is requires some kind of auth...