Velvet Star Monitor

Standout celebrity highlights with iconic style.

general

jQuery Ajax simple call

Writer Andrew Henderson

I'm trying a basic ajax call. So I'm hosting the following test php on a test server: This web page is my own test that is already integrated to the VoiceBunny API .

Now I need to get the data printed by that web page in some other web page using jQuery. As you can see the web page echo's some JSON. How can I get this JSON from another web page?

This is the code I have:

 $.ajax({ 'url' : ' 'type' : 'GET', 'data' : { 'numberOfWords' : 10 }, 'success' : function(data) { alert('Data: '+data); }, 'error' : function(request,error) { alert("Request: "+JSON.stringify(request)); } });

I have tried many other variations but I always get an error and never the JSON. Thank you

4

2 Answers

please set the value of dataType property to json in the settings parameter of your ajax call and give it another try!

another point is you are using ajax call setup setting properties as string and it is wrong as reference site

$.ajax({ url : ' type : 'GET', data : { 'numberOfWords' : 10 }, dataType:'json', success : function(data) { alert('Data: '+data); }, error : function(request,error) { alert("Request: "+JSON.stringify(request)); }
});

I hope this is helpful!

1

You could also make the ajax call more generic, reusable, so you can call it from different CRUD(create, read, update, delete) tasks for example and treat the success cases from those calls.

makePostCall = function (url, data) { // here the data and url are not hardcoded anymore var json_data = JSON.stringify(data); return $.ajax({ type: "POST", url: url, data: json_data, dataType: "json", contentType: "application/json;charset=utf-8" });
}
// and here a call example
makePostCall("index.php?action=READUSERS", {'city' : 'Tokio'}) .success(function(data){ // treat the READUSERS data returned }) .fail(function(sender, message, details){ alert("Sorry, something went wrong!"); });
3

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy