Ajax request what? - ajax

So I have a stupid question about this:
$.ajax({
type: "GET",
url: `URL`,
data: DO STUFF WITH WHAT I GOT FROM THE REQUEST???,
});
In ajax, when I make a get request from a URL, with the data: parameter am I giving a response that is data or is data the data I received from the request?

You can do something with the data in the success part of the ajax call:
$.ajax({
dataType: 'json',
url: url,
data: data,
success: success
});
In this case, a potential success callback would look like this:
function success(data) {
// do something with data, which is an object
}
or if there is no data to send:
function testAjax(handleData) {
$.ajax({
url:"getvalue.php",
success:function(data) {
handleData(data);
}
});
}

The main thing to understand here is that any AJAX call (any web request really) has two components: A request and a response. The actual $.ajax() function call is sending the request, and a callback function is provided to handle the response.
To illustrate:
$.ajax({
type: "GET", // request type
url: "http://www.example.com/someResource", // destination URL
data: { name: "David", location: "Boston" } // data to send
});
This would make a GET request to the specified URL, sending it the specified data. The response in this case is ignored, since no callback is provided. But you can provide one:
$.ajax({
type: "GET",
url: "http://www.example.com/someResource",
data: { name: "David", location: "Boston" }
}).done(function(response) {
// handle the response
});
The function which contains "handle the response" will be called by the system when the AJAX response is received from the server. The response variable (or whatever you want to call that variable, the name doesn't matter) will contain whatever the server sent in return. Which could be anything, really.

Related

How to show AJAX response message in alert?

I am sending username and password as request parameter to the server in AJAX and trying to show the response message. But not able to showing the response message.In fiddler it is showing the response message. But while on the browser screen it is not showing.PLEASE somebody help me out where i am wrong or need to change anything..
I have written like this-
$(document).ready(function () {
$("#btnCity").click(function () {
$.ajax({
type: "POST",
url: "http://test.xyz.com/login",
crossDomain: true,
contentType: "application/json; charset=utf-8",
data: { username: "abc", password: "1234" },
dataType: "JSONP",
jsonpCallback: 'jsonCallback',
async: false,
success: function (resdata) {
alert(resdata);
},
error: function (result, status, err) {
alert(result.responseText);
alert(status.responseText);
alert(err.Message);
}
});
});
});
TL;DR: I guess the problem is on the server side of your code (that we don't know yet).
At first: I don't know why it fails for you. I've taken your code and ran it against a public available JSONP API, that returns the current IP of your system and it worked.
Please try yourself using the URL: http://ip.jsontest.com/.
So most probably, the server doesn't return the right response to the JSONP request. Have a look at the network tab in developer tools. With your current code, the answer of the server should be something like:
jsonCallback({'someResponseKeys': 'someResponseValue'});
Note: The header should contain Content-Type:application/javascript!
BTW, even if this doesn't for now solve your problem - here are some tweaks, I'd like to advice to you:
Don't set async to false, at the documentation of jQuery.ajax() says:
Cross-domain requests and dataType: "jsonp" requests do not support synchronous
operation.
You don't need to set a jsonpCallback, because jQuery will generate and handle (using the success function a random one for you. Quote from the docs:
This value will be used instead of the random name automatically generated by jQuery. It is preferable to let jQuery generate a unique name as it'll make it easier to manage the requests and provide callbacks and error handling.
So here comes my code:
$(document).ready(function () {
$("#btnCity").click(function () {
$.ajax({
type: "POST",
url: "http://ip.jsontest.com/",
crossDomain: true,
data: { username: "abc", password: "1234" },
dataType: "JSONP",
success: function (resdata) {
console.log("success", resdata);
},
error: function (result, status, err) {
console.log("error", result.responseText);
console.log("error", status.responseText);
console.log("error", err.Message);
}
});
});
});
A working example can be found here.
Another solution, like Yonatan Ayalon suggested, can be done with a predefined function and then setting the jsonpCallback explicitly to the function that should be called.
if you see the response in Fiddler, it seems that the issue is in the callback function.
you are doing a jsonP call - which means that you need a callback function to "read" the response data.
Do you have a local function that calls "jsonCallback"?
this is a simple jsonP request, which initiates the function "gotBack()" with the response data:
function gotBack(data) {
console.log(data);
}
$.ajax({
url: 'http://test.xyz.com/login' + '?callback=?',
type: "POST",
data: formData,
dataType: "jsonp",
jsonpCallback: "gotBack"
});
You can try with the following methods and close every instance of chrome browser in task manager, then open browser in web security disable mode by the command "chrome.exe --disable-web-security"
success: function (resdata) {
alert(resdata);
alert(JSON.stringify(resdata));
},
And the better option to debug the code using "debugger;"
success: function (resdata) {
debugger;
alert(resdata);
alert(JSON.stringify(resdata));
},

jquery ajax data shows [object Object]

I have a very basic ajax call to alert the data that was reported from the server
$.ajax({
type: "POST",
url: "/someform/act", //edit utl to url
data: { changed: JSON.stringify(plainData) }, //edit to include
success: function(data) {
alert(data); //data not $data
},
error: function() {
//error condition code
}
});
According to the docs on the jquery website regarding data field on the success callback, it says that data returned is the data from the server. However for some strange reason when I alert $data, I get [object Object]
I was expecting to see something like this, since that is what the server would send back
<status>0</status>
EDIT:
data is also passed along as the POST
You need to use JSON.stringify(data) in the alert to get anything readable.
Also, $data is a completely different variable name than data.
alert() prints the string representation of the arguments - hence if you pass an object, you'll get [object Object].
To inspect data, use console.log(data) better.
If you server send a JSON, you need to put dataType: 'json' to your ajax call. Be aware there's some mistake in your ajax call.
$.ajax({
type: "POST",
url: "/someform/act", // NOT 'UTL',
data: {
key: value,
key2: value2
},
// or data: plaindata, // If 'plaindata' is an object.
dataType: 'json',
success: function(data) {
console.log(data); // As moonwave99 said
},
error: function() {
//error condition code
}
});
EDIT
When sending data, you should send an object. jQuery will handle the array to sned it to the server. So if plain data is an object, it should be like this
data: plainData,
If you're sending data via $.ajax({...}), the Network tab of your browser inspector might be showing [object Object] in the Payload (Chrome) / Request (Firefox) sub-tab, like in the following image (Firefox):
The reason for this might be in the way you're forming your AJAX call. Specifically:
$.ajax({
url: '/ajax/example-endpoint',
data: {'fooKey':fooData,'barKey':barData},
type: 'post',
cache: false,
contentType: false, // this one will turn your data into something like fooKey=fooData&barKey=barData
processData: false, // and this one will make it [object Object]:""
beforeSend: function() {
// whatever it is you need to do
},
success: function(data) {
// do stuff
},
error: function(desc, err) {
// do stuff
}
});
When combined, contentType: false and processData: false turn your data into [object Object], because you're actually telling your AJAX call to ignore the content type of whatever is being sent, and not to process it.
If it's IIS, try creating a site outside of the Default Web Site (for example localhost/ajax1). For example a new site ajax1, place it not in the DefaultAppPool, but in your pool, for example ajax1. Try http://ajax1

Sending POST request with Amplifyjs

I want to send this POST request by amplifyjs
amplify.request.define('createItem', 'ajax', {
url: baseApiUrl + '/create/?folderid={folderid}',
dataType: 'json',
type: 'POST',
contentType: 'application/json; charset=utf-8'
});
after that, the execution will be something like this:
createItem = function (callbacks, folderid, itemdata) {
return amplify.request({
resourceId: 'createItem',
data : {
folderid: folderid,
data: itemdata
},
success: callbacks.success,
error: callbacks.error
});
};
"itemData" is already a JSON string. I keep getting the Bad Request status code.
If I change the API URL to:
baseApiUrl + '/create
And after that pass:
return amplify.request({
resourceId: 'createItem',
data :data,
success: callbacks.success,
error: callbacks.error
});
It works just fine, but I need to pass the Id as well. Maybe, I'm missing something here.
You need to combine folderid and itemdata into a single data object. When Amplify reads your data object it will extract the folderid property and place it in the URL of the request. Then it will POST the remaining properties of the data object.

jQuery ajax event success handling

I have the following code multiple times:
$.ajax({
type: "POST",
cache: false,
url: "url here",
success: function (data) {
// do something here...
}
});
I'd like to turn this into a function as use it only once, somthing like:
function ajax (type, url, complete){
$.ajax({
type: type,
cache: false,
url: url,
success: function (data) {
GO TO THE METHOD SPECIFIED IN complete
}
});
How would I run a method specified in the complete variable? Is it possible? I've looked at the ajax success event for jQuery but since it would be triggered on every item that uses it, I would then have to check if it is the correct ajax request...
If complete is a reference to a function,
function ajax (type, url, complete){
$.ajax({
type: type,
cache: false,
url: url,
success: complete
});
Just make sure complete's arguments match what is given by success.
EDIT: If complete is an object, just find the function on it and use that:
success: complete.foo
Hope this is what you're asking...
If understand question correctly
function ajax (type, data, url, complete){
$.ajax({
type: type,
data:data,
cache: false,
url: url,
success: complete
});
}
var obj={ id:1}
/* example case use */
ajax ('POST', obj 'site.com', myAjaxComplete);
/* a success callback from ajax*/
function myAjaxComplete(data){
// data argument is return data from server
}
EDIT: you'll definitely want to add an argument for data to send to server

how do I get the reponse text from ajax / jquery?

Imagine I run this:
$.ajax({
type: 'POST',
url: '/ajax/watch.php',
data: {'watch':'aukcia', 'id':aukciaID},
complete: function(responseText){
alert(responseText);
}
});
Inside /ajax/watch.php, let's say I have this:
echo 'this is what I want';
And the alert(responseText) returns:
[object Object]
Instead of my text string that I need.
Any help, please?
Looks like somehow your jQuery is returning the XMLHttpRequest object, instead of your response.
If that is the case, you should ask for its responseText property, like this:
$.ajax({
type: 'POST',
url: '/ajax/watch.php',
data: {'watch':'aukcia', 'id':aukciaID},
complete: function(r){
alert(r.responseText);
}
});
However, if that does not work, you might be actually receiving a JSON response, and the [object Object] you are seeing might be your browser's representation of your JSON response.
You should be able to inspect its contents by navigating around the object properties. However, if you want, you can also tell jQuery not to parse your JSON response, by including dataType: 'text' on your call:
$.ajax({
type: 'POST',
url: '/ajax/watch.php',
data: {'watch':'aukcia', 'id':aukciaID},
dataType: 'text',
complete: function(data){
alert(data);
}
});
For more information, see: http://api.jquery.com/jQuery.ajax/
Use on your client side ajax like this
$.ajax({
type: "POST",
url: "insert-data.php",
data:
{student_name:student_name,student_roll_no:student_roll_no
,student_class:student_class},
dataType: "JSON",
success: function(data) {
$("#message").html(data);
$("p").addClass("alert alert-success");
},
error: function(err) {
alert(err);
}
});
in server side after query excecute you may use it give success when you query success false when your query has fault
if($stmt->execute())
{
$res="Data Inserted Successfully:";
echo json_encode($res);
}
else {
$error="Not Inserted,Some Probelm occur.";
echo json_encode($error);
}
I think you are receiving this in your server respones
{message:'hello world'}
if thats the case then use
JSON.parse(data.responseText).message
to convert the json string into javascript object and access your message property.

Resources