I am confused because I have two functions, one using ajax to get the data and the other getting it from a string.
function loadMenuData() {
$.ajax({
url: "./shoulders.json",
success: function(data) {
dataObj = $.parseJSON(data);
$.each(dataObj, function( key, value) {
$(document).find("#dropDownDest").append($('<option></option>').val(value.id).html(value.name));
});
}
});
}
function loadMenuDataX() {
var str = '[{"id":"A","name":"Bart"},{"id":"B", "name":"Joe"},{"id":"C", "name":"Gomer"}]';
dataObj = $.parseJSON(str);
$.each(dataObj, function( key, value) {
$(document).find("#dropDownDest").append($('<option></option>').val(value.id).html(value.name));
});
}
I created the file shoulders.json buy pasting the str between the single quotes ' into the file. If I call loadMenuX, it fills in the <select></select> correctly. If I call loadMenu, it doesn't fill anything in.
I have tried JSON.parse instead of the above and get the same behavior.
I was unable to use $("#dropDownDest") and had to use $(document).find. Why?
Hitting the DOM each loop seems to be excessive. What would be a better way to do the ajax version THAT WOULD WORK and be better?
What would be a better way to do the ajax version THAT WOULD WORK and be better?
Because you're trying to get JSON file the better way is using jQuery.getJSON(), so you will be sure that the returned result is in json format :
$.getJSON( "./shoulders.json", function( json ) {
$.each(json, function( key, value) {
$("#dropDownDest").append('<option value="+value.id+">'+value.name+'</option>');
});
});
Hope this helps.
Related
So basically what I'm doing is auto filling a textbox using AJAX to grab information from a PHP script that calls a C function.
This is what I've found in theory: (Assuming receiving only one value)
$(document).ready(function(){
window.setInterval(function(){
var ajaxurl = 'php/portserverclient.php',
$.post(ajaxurl, NULL, function (response) {
$('#v1').val(response);
});
}, 5000);
});
Now, if this works, which I believe it will. If I receive an array of values, then the input inside of function cannot be response, correct? So what would I have to change it to make it an array?
Just to be clear, my PHP script is using echo to output its information. I'd rather output in such a more "standard" manner as in V1 = 120, V2 = 120, etc. but PHP is new to me and that I am currently researching. Thank you.
EDIT:
Just to make it clearer
Would something like this work?
$(document).ready(function(){
window.setInterval(function(){
var ajaxurl = 'php/portserverclient.php',
$.post(ajaxurl, NULL, function (response[]) {
$('#v1').val(response[0]);
$('#v2').val(response[1]);
$('#v3').val(response[2]);
});
}, 5000);
});
Since you echo on PHP side, the response just can be a string.
But if that string if formed as a valid JSON, you will be able to use it like you wish.
So on PHP side, make sure the json format is valid:
$array = [120,340,800];
echo json_encode($array);
Then in JS... You received a string... You have to parse it to make it an array.
$(document).ready(function(){
window.setInterval(function(){
var ajaxurl = 'php/portserverclient.php',
$.post(ajaxurl, NULL, function (response[]) {
var responseArray = JSON.parse(response);
$('#v1').val(responseArray[0]);
$('#v2').val(responseArray[1]);
$('#v3').val(responseArray[2]);
});
}, 5000);
});
Per the OP update, you could try something like this to map each item of the array up to its corresponding text box you could do.
$.post(ajaxurl, NULL, function (response) {
for (var i = 0; i < response.length; i++) {
$("#v" + (i + 1)).val(response[i]);
}
});
This would map each index of the array returned from the JSON endpoint, to a corresponding text box.
If the JSON being returned from your endpoint is a valid JSON array, your response variable should already be an array!
Send your array as json:
echo json_encode(array($value1, $value2, $value3));
JS
$.post(ajaxurl, NULL, function (response) {
// selectors in same index order as response array
$('#v1, #v2, #v3').val(function(i){
return response[i];
});
},'json');
The easiest way (for me) to communicate between javascript and PHP is JSON.
So your PHP script have to generate an answer in this format.
PHP code
// At the top of your PHP script add this
// that will tell to your browser to read the response as JSON
header('Content-Type : application/json', true);
// Do your logic to generate a PHP array
echo json_encode($yourArray);
HTML code
<div class="someClass"></div>
Javascript code
var container = $('.someClass');
$.post(ajaxurl, NULL, function (response) {
console.log(response); // for debuging
for (let i = 0; i <= response.length; i++) {
let myItem = response[i];
container.append('<p>' + item + '</p>');
}
});
It's cleanest to generate dynamically the p elements because you don't know how many results your PHP file will return you.
I'm not sure of the javascript code, you maybe will received a json string that you have to transform to a Javascript Array
Before link you javascript to php script, try some call with postman (or others http client) to ensure that your 'webservice' is working as excepted
this is my first question here! New to using Ajax, and have hit an issue that maybe someone could catch what I am doing wrong.
var featuredList;
$.ajax({
url: "myurl",
type: 'GET',
success: function(result){
featuredList = JSON.stringify(result);
alert(result);
$.each( result, function( key, value ) {
alert('not working');
});
},
error: function(){alert('error');}
});
I have gone this path before with no issues, this time around I cannot get inside the loop. The alert(result) is returning my data just fine.
Thanks!
Hi,
Hope this might help you to process JSON data received from AJAX request, try below code:
jQuery.ajax({
url:'myurl',
dataType: "json",
data:{
classId:'C001'
},
type: "GET",
success: function(data) {
for (var j=0; j < data.length; j++) {
//syntax to get value for given key
//data[j].yourKey
var userId = data[j].userId;
var name = data[j].name;
var address = data[j].address;
}
}
});
Thanks,
~Chandan
As per your code try doing this:it should work
var data = JSON.parse(result);//here result should be json encoded data
$.each( data, function( key, value ) {
alert(value);
});
Use jQuery promises, gives you more semantic and readable code
var featuredList;
$.getJSON("myurl", {"optional": "data"})
.done(function(data){
// successful ajax query
$.each( data, function( key, value ) {
// do whatever you want with your iterated data.
});
});
.fail(function(){
// catch errors on ajax query
});
I do it this way
$.getJSON('url',
function(dataList) { // on server side I do the json_encode of the response data
if(dataList !== null) {
$.each(dataList, function(index, objList ) {
// rest of code here
});
}
});
Hope this works for you as well.
function getArray(){
return $.getJSON('url');
}
var gdata = [];
getArray().then(function(json) {
$.each(json, function(key, val) {
gdata[key] = val ;
});
console.log(gdata);
I had the Same Problem It took 2 days to got the solution.
You have to resolve the promise and return the json object to access the value.
You could easily do this using the open source project http://www.jinqJs.com
/* For Async Call */
var result = null;
jinqJs().from('http://.....', function(self){
result = self.select();
});
/* For Sync Call */
var result = jinqJs().from('http://....').select();
You can also use $.Json to get your solution , here is an example
$.getJSON('questions.json', function (data) {
$.each(data,function(index,item){
console.log(item.yourItem); // here you can get your data
}
}
You can use or print Index if you want it. Its show the data index.
Hope it may help you, I am exactly not sure its your requirement or not, But i have tried my best to solve it.
This will work as the result from ajax call is a string.
$.each($.parseJSON(result), function( key, value ) {
alert('This will work');
});
I have application.php page where json array is echoed with php. On the client i want to get the json array with $.getJSON() on button click when form is submitted(submitHandler). The problem is that if I run alert() or console.log() in $.getJSON() nothing happens(i only see GET execution in console).
Code:
$.getJSON('../views/application.php', function(data) {
alert('alert1');
if(data) {
document.write(data.resp);
alert('alert2');
}
else {
alert('error');
}
});
GET http://localhost/app/views/application.php
you can use var temp in your script and store your data inside that variable.
var x;
<script type="text/javascript">
x='<?php echo $comparisonResult; ?>';
</script>
Sounds like a use case for sessionStorage or cookies.
Use sessionstorage if you don't need to support IE7.
I think the best way is to return the needed server data in the response of your first post request, just like this :
$.post( "/first.php", function( serverData ) {
var param = serverData.something;
...
$.post( "/second.php", param, function( data ) {
...
});
});
If you are using the two request in two different pages, you can store serverData in localStorage.
Edit after your clarification:
If you need to get data before ajax post when you click on a button, you can do this way :
$("#second-button").click(function() {
$.getJSON("/data.php", function (serverData) {
var param = serverData.something;
$.post("/second.php", param, function(data) {
...
});
}
});
Edit 2
For some reason (wrong url, invalid json, and so on) your $.getJSON fail.
Try this for debug:
$.getJSON("/data.php", function (serverData) {
console.log(serverData);
}).fail(function(j, t, e) {
console.error(e);
});
This issue is with jquery.
I have the the following function
$('#admin_id').html(getPartnerName(i, data.admin_id));
And the function getPartnerName is below
function getPartnerName(i, partner_id) {
$.getJSON( '../index.php', 'r=someName&id=1', function(data) {
return data.admin_name;
});
}
I want to print the admin_name returned by json and display it in td with id #admin_id
My code is working fine by not able to display the names.
please help me out to know where am i going wrong.
$.getJSON( '../index.php', 'r=someName&id=1', function(data) {
$('#admin_id').html(data.admin_name);
});
Because the ajax call is asynchronous, you need to provide a callback that is in control of the result parsing; you cannot just return it like from a normal function.
you can assign a variable to the function and call the variable inside html()
Ex:
var output = function getPartnerName(i, partner_id) {
$.getJSON( '../index.php', 'r=someName&id=1', function(data) {
return data.admin_name;
});
}
$('#admin_id').html(output);
hope this is what you were looking for... :)
Been getting a "parsererror" from jquery for an Ajax request, I have tried changing the POST to a GET, returning the data in a few different ways (creating classes, etc.) but I cant seem to figure out what the problem is.
My project is in MVC3 and I'm using jQuery 1.5
I have a Dropdown and on the onchange event I fire off a call to get some data based on what was selected.
Dropdown: (this loads the "Views" from the list in the Viewbag and firing the event works fine)
#{
var viewHtmls = new Dictionary<string, object>();
viewHtmls.Add("data-bind", "value: ViewID");
viewHtmls.Add("onchange", "javascript:PageModel.LoadViewContentNames()");
}
#Html.DropDownList("view", (List<SelectListItem>)ViewBag.Views, viewHtmls)
Javascript:
this.LoadViewContentNames = function () {
$.ajax({
url: '/Admin/Ajax/GetViewContentNames',
type: 'POST',
dataType: 'json',
data: { viewID: $("#view").val() },
success: function (data) {
alert(data);
},
error: function (data) {
debugger;
alert("Error");
}
});
};
The above code successfully calls the MVC method and returns:
[{"ViewContentID":1,"Name":"TopContent","Note":"Content on the top"},
{"ViewContentID":2,"Name":"BottomContent","Note":"Content on the bottom"}]
But jquery fires the error event for the $.ajax() method saying "parsererror".
I recently encountered this problem and stumbled upon this question.
I resolved it with a much easier way.
Method One
You can either remove the dataType: 'json' property from the object literal...
Method Two
Or you can do what #Sagiv was saying by returning your data as Json.
The reason why this parsererror message occurs is that when you simply return a string or another value, it is not really Json, so the parser fails when parsing it.
So if you remove the dataType: json property, it will not try to parse it as Json.
With the other method if you make sure to return your data as Json, the parser will know how to handle it properly.
See the answer by #david-east for the correct way to handle the issue
This answer is only relevant to a bug with jQuery 1.5 when using the file: protocol.
I had a similar problem recently when upgrading to jQuery 1.5. Despite getting a correct response the error handler fired. I resolved it by using the complete event and then checking the status value. e.g:
complete: function (xhr, status) {
if (status === 'error' || !xhr.responseText) {
handleError();
}
else {
var data = xhr.responseText;
//...
}
}
You have specified the ajax call response dataType as:
'json'
where as the actual ajax response is not a valid JSON and as a result the JSON parser is throwing an error.
The best approach that I would recommend is to change the dataType to:
'text'
and within the success callback validate whether a valid JSON is being returned or not, and if JSON validation fails, alert it on the screen so that its obvious for what purpose the ajax call is actually failing. Have a look at this:
$.ajax({
url: '/Admin/Ajax/GetViewContentNames',
type: 'POST',
dataType: 'text',
data: {viewID: $("#view").val()},
success: function (data) {
try {
var output = JSON.parse(data);
alert(output);
} catch (e) {
alert("Output is not valid JSON: " + data);
}
}, error: function (request, error) {
alert("AJAX Call Error: " + error);
}
});
the problem is that your controller returning string or other object that can't be parsed.
the ajax call expected to get Json in return. try to return JsonResult in the controller like that:
public JsonResult YourAction()
{
...return Json(YourReturnObject);
}
hope it helps :)
There are lots of suggestions to remove
dataType: "json"
While I grant that this works it's ignoring the underlying issue. If you're confident the return string really is JSON then look for errant whitespace at the start of the response. Consider having a look at it in fiddler. Mine looked like this:
Connection: Keep-Alive
Content-Type: application/json; charset=utf-8
{"type":"scan","data":{"image":".\/output\/ou...
In my case this was a problem with PHP spewing out unwanted characters (in this case UTF file BOMs). Once I removed these it fixed the problem while also keeping
dataType: json
Your JSON data might be wrong. http://jsonformatter.curiousconcept.com/ to validate it.
Make sure that you remove any debug code or anything else that might be outputting unintended information. Somewhat obvious, but easy to forgot in the moment.
I don't know if this is still actual but problem was with Encoding. Changing to ANSI resolved the problem for me.
If you get this problem using HTTP GET in IE I solved this issue by setting the cache: false.
As I used the same url for both HTML and json requests it hit the cache instead of doing a json call.
$.ajax({
url: '/Test/Something/',
type: 'GET',
dataType: 'json',
cache: false,
data: { viewID: $("#view").val() },
success: function (data) {
alert(data);
},
error: function (data) {
debugger;
alert("Error");
}
});
you should remove the dataType: "json". Then see the magic... the reason of doing such thing is that you are converting json object to simple string.. so json parser is not able to parse that string due to not being a json object.
this.LoadViewContentNames = function () {
$.ajax({
url: '/Admin/Ajax/GetViewContentNames',
type: 'POST',
data: { viewID: $("#view").val() },
success: function (data) {
alert(data);
},
error: function (data) {
debugger;
alert("Error");
}
});
};
incase of Get operation from web .net mvc/api, make sure you are allow get
return Json(data,JsonRequestBehavior.AllowGet);
If you don't want to remove/change dataType: json, you can override jQuery's strict parsing by defining a custom converter:
$.ajax({
// We're expecting a JSON response...
dataType: 'json',
// ...but we need to override jQuery's strict JSON parsing
converters: {
'text json': function(result) {
try {
// First try to use native browser parsing
if (typeof JSON === 'object' && typeof JSON.parse === 'function') {
return JSON.parse(result);
} else {
// Fallback to jQuery's parser
return $.parseJSON(result);
}
} catch (e) {
// Whatever you want as your alternative behavior, goes here.
// In this example, we send a warning to the console and return
// an empty JS object.
console.log("Warning: Could not parse expected JSON response.");
return {};
}
}
},
...
Using this, you can customize the behavior when the response cannot be parsed as JSON (even if you get an empty response body!)
With this custom converter, .done()/success will be triggered as long as the request was otherwise successful (1xx or 2xx response code).
I was also getting "Request return with error:parsererror." in the javascript console.
In my case it wasn´t a matter of Json, but I had to pass to the view text area a valid encoding.
String encodedString = getEncodedString(text, encoding);
view.setTextAreaContent(encodedString);
I have encountered such error but after modifying my response before sending it to the client it worked fine.
//Server side
response = JSON.stringify('{"status": {"code": 200},"result": '+ JSON.stringify(result)+'}');
res.send(response); // Sending to client
//Client side
success: function(res, status) {
response = JSON.parse(res); // Getting as expected
//Do something
}
I had the same problem, turned out my web.config was not the same with my teammates.
So please check your web.config.
Hope this helps someone.
I ran into the same issue. What I found to solve my issue was to make sure to use double quotes instead of single quotes.
echo "{'error':'Sorry, your file is too large. (Keep it under 2MB)'}";
-to-
echo '{"error":"Sorry, your file is too large. (Keep it under 2MB)"}';
The problem
window.JSON.parse raises an error in $.parseJSON function.
<pre>
$.parseJSON: function( data ) {
...
// Attempt to parse using the native JSON parser first
if ( window.JSON && window.JSON.parse ) {
return window.JSON.parse( data );
}
...
</pre>
My solution
Overloading JQuery using requirejs tool.
<pre>
define(['jquery', 'jquery.overload'], function() {
//Loading jquery.overload
});
</pre>
jquery.overload.js file content
<pre>
define(['jquery'],function ($) {
$.parseJSON: function( data ) {
// Attempt to parse using the native JSON parser first
/** THIS RAISES Parsing ERROR
if ( window.JSON && window.JSON.parse ) {
return window.JSON.parse( data );
}
**/
if ( data === null ) {
return data;
}
if ( typeof data === "string" ) {
// Make sure leading/trailing whitespace is removed (IE can't handle it)
data = $.trim( data );
if ( data ) {
// Make sure the incoming data is actual JSON
// Logic borrowed from http://json.org/json2.js
if ( rvalidchars.test( data.replace( rvalidescape, "#" )
.replace( rvalidtokens, "]" )
.replace( rvalidbraces, "")) ) {
return ( new Function( "return " + data ) )();
}
}
}
$.error( "Invalid JSON: " + data );
}
return $;
});
</pre>