jQuery-form and Json problems - javascript

Good day guys, I'm using jQuery-form to submit a multipart form.
This is my PHP code:
foreach($addedData as $key => $value)
$result[$key] = $value;
echo json_encode($result);
Javascript:
function showResponse(responseText){
alert(responseText);
}
$('button').click(function(){
$("form").ajaxForm({
success: showResponse,
clearForm: true,
dataType: "json",
contentType: "application/json; charset=utf-8"
});
});
With this, the response was [object Object]. But when I removed these two lines:
dataType: "json",
contentType: "application/json; charset=utf-8"
The response became:
{"key1":"val1","key2":"va2","key3":"val3"}
My questions are: Do I really have to remove those two lines? And how can I get the values of the responseText using Json?

By having the dataType:"json", .. you are telling the request that you want the returned item to be an object (like $.parseJSON(responseText);). Without it you will be given plain text.
To print the object you will need something like this:
function showResponse(responseObj){
$.each(responseObj,function(i,v) {
alert(i+' = '+v);
});
}

If you specify dataType: 'json' then your success callback function will be passed the object the JSON represents, rather than a JSON string. jQuery implicitly handles converting the responseText to the object for you, so you don't have to do JSON.parse(responseText) for yourself. If the response isn't valid JSON, the success callback won't be executed; even if the AJAX request returned successfully.
To get the values out, just use responseText like any other Javascript object; though you may want to give it a different name to make it clearer what it actually is.

No you don't, but the alert-box can't display the JSON-object. Try doing Console.log(responseText) instead, and inspecting the result in the developertools in your browser. [object Object] is a object literal

If you remove the lines then you get string ('{"key1":"val1","key2":"va2","key3":"val3"}') in JavaScript (because it use respone as file with text/text mime tipe), if you don't then you get Object ({"key1":"val1","key2":"va2","key3":"val3"}), so I think you should not remove them, if you want loop though this for example. By the way, when you alert an object JavaScript convert object to string (always '[Object object]').

don't remove the below code from your script and add the below code you will get the alert correctly
dataType: "json",
contentType: "application/json; charset=utf-8"
var htmlstr;
for(var i in responsetext)
{
htmlstr += i +"="+responsetext[i]+"\n";
}
alert(htmlstr);

Related

Javascript Convert JSONP data from string to Json object

So i am not sure if i am doing this right.
I want to send markup over HTML (i am trying to create a widget)
Here is the mocky response that i am expecting
so I create a simple jquery get like this
var jsonp_url = "http://www.mocky.io/v2/5c9e901a3000004a00ee98a1?callback=myfunction";
$.ajax({
url: jsonp_url,
type: 'GET',
jsonp: "callback",
contentType: "application/json",
success: function (data) {
$('#example-widget-container').html(data.html)
},
error: function (data) {
alert('woops!'); //or whatever
}
});
then created myFunction
function myfunction(data) {
console.log(data);
}
The problem being that while, i get the response it comes as a string instead of a json or function. i am not sure how to extract the json from this (unless i do string manupulation).
Any pointers would be helpful.
JSFiddle here
P.S. Per https://www.mocky.io/ ,
Jsonp Support - Add
?callback=myfunction to your mocky URL to enable jsonp.
Delete function myfunction.
In the URL, replace callback=myfunction with callback=?.
jQuery will generate a function (your success function) and a function name for you.

Why error function is always fired on my ajax call? [duplicate]

I have implemented an Ajax request on my website, and I am calling the endpoint from a webpage. It always returns 200 OK, but jQuery executes the error event.
I tried a lot of things, but I could not figure out the problem. I am adding my code below:
jQuery Code
var row = "1";
var json = "{'TwitterId':'" + row + "'}";
$.ajax({
type: 'POST',
url: 'Jqueryoperation.aspx?Operation=DeleteRow',
contentType: 'application/json; charset=utf-8',
data: json,
dataType: 'json',
cache: false,
success: AjaxSucceeded,
error: AjaxFailed
});
function AjaxSucceeded(result) {
alert("hello");
alert(result.d);
}
function AjaxFailed(result) {
alert("hello1");
alert(result.status + ' ' + result.statusText);
}
C# code for JqueryOpeartion.aspx
protected void Page_Load(object sender, EventArgs e) {
test();
}
private void test() {
Response.Write("<script language='javascript'>alert('Record Deleted');</script>");
}
I need the ("Record deleted") string after successful deletion. I am able to delete the content, but I am not getting this message. Is this correct or am I doing anything wrong? What is the correct way to solve this issue?
jQuery.ajax attempts to convert the response body depending on the specified dataType parameter or the Content-Type header sent by the server. If the conversion fails (e.g. if the JSON/XML is invalid), the error callback is fired.
Your AJAX code contains:
dataType: "json"
In this case jQuery:
Evaluates the response as JSON and returns a JavaScript object. […]
The JSON data is parsed in a strict manner; any malformed JSON is
rejected and a parse error is thrown. […] an empty response is also
rejected; the server should return a response of null or {} instead.
Your server-side code returns HTML snippet with 200 OK status. jQuery was expecting valid JSON and therefore fires the error callback complaining about parseerror.
The solution is to remove the dataType parameter from your jQuery code and make the server-side code return:
Content-Type: application/javascript
alert("Record Deleted");
But I would rather suggest returning a JSON response and display the message inside the success callback:
Content-Type: application/json
{"message": "Record deleted"}
You simply have to remove the dataType: "json" in your AJAX call
$.ajax({
type: 'POST',
url: 'Jqueryoperation.aspx?Operation=DeleteRow',
contentType: 'application/json; charset=utf-8',
data: json,
dataType: 'json', //**** REMOVE THIS LINE ****//
cache: false,
success: AjaxSucceeded,
error: AjaxFailed
});
I've had some good luck with using multiple, space-separated dataTypes (jQuery 1.5+). As in:
$.ajax({
type: 'POST',
url: 'Jqueryoperation.aspx?Operation=DeleteRow',
contentType: 'application/json; charset=utf-8',
data: json,
dataType: 'text json',
cache: false,
success: AjaxSucceeded,
error: AjaxFailed
});
This is just for the record since I bumped into this post when looking for a solution to my problem which was similar to the OP's.
In my case my jQuery Ajax request was prevented from succeeding due to same-origin policy in Chrome. All was resolved when I modified my server (Node.js) to do:
response.writeHead(200,
{
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "http://localhost:8080"
});
It literally cost me an hour of banging my head against the wall. I am feeling stupid...
I reckon your aspx page doesn't return a JSON object.
Your page should do something like this (page_load)
var jSon = new JavaScriptSerializer();
var OutPut = jSon.Serialize(<your object>);
Response.Write(OutPut);
Also, try to change your AjaxFailed:
function AjaxFailed (XMLHttpRequest, textStatus) {
}
textStatus should give you the type of error you're getting.
I have faced this issue with an updated jQuery library. If the service method is not returning anything it means that the return type is void.
Then in your Ajax call please mention dataType='text'.
It will resolve the problem.
You just have to remove dataType: 'json' from your header if your implemented Web service method is void.
In this case, the Ajax call don't expect to have a JSON return datatype.
See this. It's also a similar problem. Working I tried.
Dont remove dataType: 'JSON',
Note: Your response data should be in json format
Use the following code to ensure the response is in JSON format (PHP version)...
header('Content-Type: application/json');
echo json_encode($return_vars);
exit;
I had the same issue. My problem was my controller was returning a status code instead of JSON. Make sure that your controller returns something like:
public JsonResult ActionName(){
// Your code
return Json(new { });
}
Another thing that messed things up for me was using localhost instead of 127.0.0.1 or vice versa. Apparently, JavaScript can't handle requests from one to the other.
If you always return JSON from the server (no empty responses), dataType: 'json' should work and contentType is not needed. However make sure the JSON output...
is valid (JSONLint)
is serialized (JSONMinify)
jQuery AJAX will throw a 'parseerror' on valid but unserialized JSON!
I had the same problem. It was because my JSON response contains some special characters and the server file was not encoded with UTF-8, so the Ajax call considered that this was not a valid JSON response.
Your script demands a return in JSON data type.
Try this:
private string test() {
JavaScriptSerializer js = new JavaScriptSerializer();
return js.Serialize("hello world");
}

Extract object from JS script loaded with synchronous jQuery ajax call

I am trying to get use an object from a script loaded synchronously using Ajax via jQuery.
From this script I am trying to load an object which looks like this from a script called map_dropdowns.js which returns the object options:
{curr_cat: "RELATIONSHIP"
curr_subcat: " Population in households"
curr_total: "Total"}
My code for the script with the ajax is here:
<script>
$.ajax({
type: "GET",
url: "../scripts/map_dropdowns.js",
dataType: "script",
async: false,
success: function(data){
console.log(data);
}
});
console.log(options); //returns `Object{}` in the console, and only shows values when expanded
options["curr_cat"]; //returns undefined
console.log(Object.keys(options)); //returns an empty array []
</script>
In the original script, the keys and values within options can be accessed perfectly fine. console.log in Chrome shows its contents fully without needing to be expanded (Object {curr_cat: "RELATIONSHIP", curr_subcat: " Population in households", curr_total: "Total"}), and Object.keys() works just fine.
After it is loaded onto the page with the Ajax function, however, trying to access the values using the keys comes up undefined, Object.keys turns up an empty array [], and the key:value pairs are only shown in the console when I click on the object, with it otherwise showing only Object {}.
I am pretty sure that I need to do something in the success function of the Ajax, but I am not sure what after a lot of trial and error.
Thanks!
Loading JS code via AJAX is always a little hit and miss. It's usually a much better idea to load the data either as HTML, XML or JSON, and then deal with it as required once the AJAX request completes.
In your case, as you're attempting to load an object, JSON would be the most appropriate. If you change your map_dropdowns.js file to return data in this format:
'{"curr_cat":"RELATIONSHIP","curr_subcat":"Population in households","curr_total":"Total"}'
You can then make your async request to get this information from this file:
$.ajax({
type: "GET",
url: "../scripts/map_dropdowns.js",
dataType: "json",
success: function(data){
console.log(data.curr_cat); // = 'RELATIONSHIP'
console.log(data.curr_subcat); // = 'Population in households'
console.log(data.curr_total); // = 'Total'
}
});

Read PHP output from array with AJAX

My PHP is outputting data like this:
$data['full_feed'] = $sxml;
$data['other_stuff']= $new;
echo json_encode($data);
So, in my jQuery, I'm doing this.
$.ajax({
url: 'untitled.php',
type: 'GET',
success: function(data) {
console.log(data['full_feed']);
});
This comes back undefined. So does console.log(data.full_feed). I'm getting back from PHP a valid JSON object, but missing how I can "parse" it correctly.
Parse "data" parameter in response with jQuery.parseJSON function. Then use parsed.full_feed value. Like below:
$.ajax({
url: 'untitled.php',
type: 'GET',
success: function(data) {
data = jQuery.parseJSON(data);
console.log(data.full_feed);
});
You can do like #tilz0R said or for your example to work you need to tell the browser you are sending a json response. So need to set content type header like
header('Content-Type: application/json');
echo json_encode($data);
to see what the server is returning do console.log(typeof data). If its a string you need to parse it. if its an object, it is already parsed.
Also you can put dataType:'json' in your ajax call to let jquery know you are excepting a json response.

json_encode to send data back to js

Im creating a simple upload script. I use a simple form to let people upload a picture and then a external php script will upload the picture and return some vars to the upload page.
But I cant get the part to return some vars to work. currently im using this:
The page that also contains the form:
form_data.append('file', file_data);
$.ajax({
url: 'upload.php', // point to server-side PHP script
dataType: 'text', // what to expect back from the PHP script, if anything
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function(response){
document.getElementById("titel" + amount).innerHTML = response['naam'];
});
The upload page that should return some data:
echo json_encode(array('naam'=>$naam));
This scripts returns undefined..
If I remove the ['naam'] after response on the form page it will print out:
{"naam":"test.png"}
Hope someone know what im doing wrong.
Thanx in advance!
You said:
dataType: 'text', // what to expect back from the PHP script, if anything
… so jQuery will ignore what the server claims the data is (which seems to be HTML as you haven't changed the Content-Type header in your PHP) and process the response as if it was plain text.
response will therefore be a plain text string and not the results of parsing JSON.
Change dataType to "json".
The response you get from the server is the string. To use it as object, you need to parse it to JSON format using JSON.parse().
var obj = JSON.parse(response);
Then you can use:
obj.naam;
to get the value of naam from the object.
Please change datatype from "text" to "json" then parse that JSON using JSON.parse(//return value ").
Var jsonObject = JSON.parse("Ajax Response object");
then use it jsonObject.keyName and it will return the value.

Categories