Ajax post response coming back successfully - can't log/print to screen - javascript

I'm successfully posting data to the server via $.post(). When I attempt to do anything with the response, I get nothing. No console log. Can't replace text or HTML with the data. Nothing.
Here's the post:
$.post(myUrl, {myVar: myVar}, function(data) {
console.log(data);
});
And here's the response:

It may not be able to "guess" the data type as the default 4th parameter not set implies. set dataType parameter
$.post(myUrl, {myVar: myVar}, function(data) {
console.log(data);
}, 'text');
Also be sure that it returns a 200 OK response from the server or else success won't run.

You need to modify the response (probably) into a JSON format so that you can catch it. PHP's header for JSON is:
header("Content-Type: application/json"); //Set header for outputing the JSON information
You will need to include that in your PHP file that you are sending a request to. You may also need to specify the headers content in the post request, as I mainly use Angular, I'm a bit unsure of what the AJAX header for this case, but try something like:
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }

Related

Javascript fetch api payload not delivered

console.log("data ", data); // returns an object in JSON format {propertyName: propertyValue}
dataString = JSON.stringify(dataString); //correctly stringified json
let response = await fetch('updateRecevingEntry.php',
{
method:'POST',
headers: {'Content-Type':'application/json'},
body: dataString
}).then(response=>response.json());
however I get back an undefined index on the php side.
where the php is:
$matkey = $_POST['materialKey'];
returns
<b>Notice</b>: Undefined index: materialKey in <b>path/updateRecevingEntry.php</b> on line <b>3</b><br />
for all the data... none of it is getting caught.
so why is the _POST['propertyName'] not catching the stringData from the body?
I've tried a few variations, such as sending the data instead of the string data messing with the header, but I can't seem to figure out how to send the payload such that _POST['propertyName'] catches the data in the body.
I was using $.ajax from jquery before, and it was working: but I'm in the process of refactoring that out.
the Fetch api is new to me. where am I going wrong. I also don't want to parse a json object on the php side.
after reading one of the answers, I got it to work in one case,
but
let response = await fetch('updateRecevingEntry.php',
{
method:'POST',
headers: {'Content-Type':'application/json'},
body: sendData
}).then(response=>response.json());
and the php
$postData = json_decode(file_get_contents("php://input"), true);
var_dump($postData);
just returns a big fat NULL.
Edit two: turns out it just needs to actually be encoded via JSON.stringify(sendData). Since the. It works as expected.
The first thing I've noticed is that you're not using the right variable (you're using stringData instead of dataString):
dataString = JSON.stringify(dataString); //correctly stringified json
let response = await fetch('updateRecevingEntry.php', {
method:'POST',
headers: {'Content-Type':'application/json'},
body: dataString
}).then(response=>response.json());
Though you shouldn't need to stringify it as you're sending it with json headers.
Additionally, have you tried instead of $_POST, using php://input?
From PHP.net:
php://input is a read-only stream that allows you to read raw data from the request body. In the case of POST requests, it is preferable to use php://input instead of $HTTP_RAW_POST_DATA as it does not depend on special php.ini directives. Moreover, for those cases where $HTTP_RAW_POST_DATA is not populated by default, it is a potentially less memory intensive alternative to activating always_populate_raw_post_data. php://input is not available with enctype="multipart/form-data".
So you would use it like so:
$postData = json_decode(file_get_contents("php://input"), true);
$matkey = $postData['materialKey'];
This reads the body of the POST request as a JSON string then converts it to a PHP array.

How can i do cross domain query using ajax & jsonp?

I send ajax to url , but i get error.
Here is my code:
$.ajax({
url: "http://webrates.truefx.com/rates/connect.html?q=ozrates&c=EUR/USD&f=csv&s=n",
dataType : 'jsonp',
success: function (data) {
alert(data);
}
})
Maybe i doing something wrong?
In order to access data using JSONP, the server you are requesting the data from must format its response as JSONP.
You are getting an error because the response is not JSONP (it is CSV, which you asked for explicitly when you put t=csv in the query string).
Either:
Use a different method to get the data
Change the server so it responds with JSONP formatted data

Issue about getting response in $.get()

$('#requestButton').click(function() {
$.get('ajax.php', function(data) {
alert(data);
});
});
alert() doesn't showing. What's the problem?
The problem is that your server is claiming:
content-type: application/javascript
But you are sending back a JSON document. jQuery won't populate data when it gets (what it thinks is) a JavaScript program back from the server.
You need to send the correct content type, which is application/json.
Using getJSON or specifying "json" are hacks to tell jQuery to disbelieve the content type and parse in a different data format, but you should fix the server so it tells the truth about the content instead.
Instead of :
$.get
use :
$.getJSON
As you mentioned in the comment section about returned data is json.
Or add a dataType in the $.get() call:
$.get( "ajax.php", function( data ) {
console.log(data);
}, "json" ); //<-----------add dataType here

How do I extract the response content (only body) without headers? using Jquery

How do I extract the response content (only body) without headers?
$.ajax({
type: "GET",
url: "http://myRestservice.domain.com",
success: function(data, textStatus, request){
alert(data); //This prints the response with the header.
},
error: function(){
alert('fail');
}
});
The above code prints
HTTP/1.1 200 OK
Cache-Control: private, max-age=0
Content-Type: text/xml; charset=utf-8
Server: Microsoft-IIS/7.5
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Fri, 12 Jul 2013 20:24:06 GMT
Content-Length: 232
<?xml version="1.0" encoding="utf-8"?>
<string xmlns="http://tempuri.org/">{"UserID":3,"RoleID":8,"ActivityID":3,"RoleIName":"E",,"Duration":10,"ValidationMsg":"Passed"}</string>
I need to extract the value of ValidationMsg. This is a rest service call.
How do I get the response without header informations?
I think your server is delivering a content type that you aren't expecting.
Steps to resolve:
Open up the network tab in chrome's developer tools, watch the request occur and read what content type it is being delivered as. I bet, it is something like text/plain or text/html.
For JSON your server should be delivering it as application/json.
Your ajax request should specify dataType as 'json'. Normally $.ajax guesses appropriately; however, since your server is claiming it is text of some sort you are getting headers in your response.
I suspect there is something wrong with your server code if you are getting back headers in the data parameter. The code you have provided works fine for me connecting to a test server returning valid XML - the data parameter ends up containing an XML document object.
I'd suggest you try opening that url in a browser and see what it returns. Also, if the XML is being generated programatically on the server, you could try just creating a static XML file instead and see if that works any better.
Once you have the server returning valid XML, you can extract the string content from the XML object in the data parameter like this:
var stringContent = $(data).text();
Then you can parse the JSON from that string content with:
var json = $.parseJSON(stringContent);
And finally extract the validationMessage key with:
var validationMessage = json.ValidationMsg;
This is assuming the JSON in that string element is valid json. However in the example you have given, there is a double comma between "RoleIName" and "Duration" which makes it invalid.
If you can't fix that on the server side, you could possibly fix it on the client side with a simple string replace like this:
stringContent = stringContent.replace(',,', ',');
This isn't a particularly safe thing to do in general, but if you're not worried about having commas in the json content that could be corrupted by such a call, it shouldn't be an issue.
Putting that all together, the final success function should look something like this:
success: function(data, textStatus, request){
var stringContent = $(data).text();
stringContent = stringContent.replace(',,', ',');
var json = $.parseJSON(stringContent);
var validationMessage = json.ValidationMsg;
/* do whatever you need with the validationMessage here */
},
Here's a codepen link demonstrating the working script: http://codepen.io/anon/pen/LeDlg
My idea is to try using contentType in your ajax call:
$.ajax({
type: "GET",
url: "http://myRestservice.domain.com",
**contentType: "application/json",**
success: function(data, textStatus, request){
alert(data); //This prints the response with the header.
},
error: function(){
alert('fail');
}
});
and then try to catch the json object

GET ajax request

I'm sending GET request (which returns JSON).
The code looks like:
$.ajax({
url: "http://www.new.marketprice.ru/retrieveRegions.html",
dataType: "jsonp",
data: {
searchStr: request.term
},
error: function() {
console.log('epic fail');
},
success: function( data ) {
console.log(data);
}
});
It returns (into console);
Resource interpreted as Other but transferred with MIME type undefined.
epic fail
But in Network tab I see GET request with returned data:
[
{ "region":"Московская область","countryId":1,
"cityId":23,"regionId":12345,"city":"Москва","country":"Россия"},
{"region":"Ленинградская область","countryId":1,"cityId":453,
"regionId":54321,"city":"Санкт Петербург","country":"Россия"}
]
Why does error callback is called?
UPD
Okay, I set json and now no warning but error:
XMLHttpRequest cannot load http://www.new.marketprice.ru/retrieveRegions.html?searchStr=test. Origin http://new.marketprice.ru is not allowed by Access-Control-Allow-Origin
It's so strange because running script is located at same domain :(
It is only a json response not JSONP. Generally for JSONP the request will have callback method and response will be wrapped in that function name
Your headers don't specify the correct mime-type (application/json-p) and jQuery(?) is confused because it's not sure if it should process it as json or not.
See if you can get your server to respond with the correct type. The appropriate header is called Content-Type.
EDIT: whoops, and the OP is right, its not even JSON-P. Try changing what jquery is expecing to just 'json' first.
i was also in problem like this just try by using one more argument callback=? or json=jsonp

Categories