does anyone know how to append a top level json to an existing object?
this is what I have:
var url = "http://domain.com/gettxt";
$.ajax({
url: url,
dataType: "json",
success: function (data, textStatus, jqXHR) {
rootData = data;
renderView();
},
error: function (jqXHR, textStatus, errorThrown) {
alert("error" + errorThrown)
}
});
At this point, data contains the following:
[{"id":1,"title":"Johnson"}]
And I need it to be like this:
{ "record": [ {"id":1}, {"title":"Johnson"} ] }
In other words:
rootData = "{ "record":" + data + "}";
Does anyone know how can I do the above? Unfortunately adding the top level before it comes to Javascript is not an option, thanks.
You can directly add object type like this,
rootData = { record: data };
Your final code will be
var url = "http://domain.com/gettxt";
$.ajax({
url: url,
dataType: "json",
success: function (data, textStatus, jqXHR) {
rootData = { record: data };
renderView();
},
error: function (jqXHR, textStatus, errorThrown) {
alert("error" + errorThrown)
}
});
You can just use an object literal to do this:
rootData = { record: data };
So your code would look like this:
success: function (data, textStatus, jqXHR) {
rootData = { record: data };
renderView();
},
try this
var arr = [{"id":1,"title":"Johnson"}];
var obj ={};
obj.record = arr;
console.log(obj);
a = [{"id":1,"title":"Johnson"}]
root = {record: a}
Related
I want to know which way is the best way to execute a function when a function with the ajax call has completed.
My code:
jQuery.when(AjaxCallToBokningar()).done(function () {
console.log("AjaxCallComplete");
});
function AjaxCallToBokningar() {
var url = `${_spPageContextInfo.webAbsoluteUrl}/_api/web/lists/getbytitle('Bokningar')/items
var call = jQuery.ajax({
url: url,
type: "GET",
dataType: "json",
headers: {
Accept: "application/json;odata=verbose"
}
});
//Done
call.done(function (data, textStatus, jqXHR) {
//Filling globalArray
window.globalBokningsArray = data.d.results;
});
//Fail
call.fail(function (jqXHR, textStatus, errorThrown) {
console.log('Loading Bokningar content faild: ' + textStatus + jqXHR.responseText);
});
}
Am I on the right track or is there a better way?
If you want to be able to make the Ajax call and then call a function when it's complete you can use a function reference as a parameter and do it like this...
function AjaxCallToBokningar(doneCallback) {
var url = `${_spPageContextInfo.webAbsoluteUrl}/_api/web/lists/getbytitle('Bokningar')/items
var call = jQuery.ajax({
url: url,
type: "GET",
dataType: "json",
headers: {
Accept: "application/json;odata=verbose"
}
});
//Done
call.done(function (data, textStatus, jqXHR) {
//Filling globalArray
window.globalBokningsArray = data.d.results;
doneCallback();
});
//Fail
call.fail(function (jqXHR, textStatus, errorThrown) {
console.log('Loading Bokningar content faild: ' + textStatus + jqXHR.responseText);
});
}
Then you can call it like this...
function ajaxCallComplete1() {
// this is executed after the 1st call is done - do something here
}
function ajaxCallComplete2() {
// this is executed after the 2nd call is done - do something here
}
AjaxCallToBokningar(ajaxCallComplete1);
AjaxCallToBokningar(ajaxCallComplete2);
or...
AjaxCallToBokningar(function() {
// this is executed after the call is done - do something here
});
You can also try something like this: (not tested)
function ajaxCallToBokningar() {
var url = `${_spPageContextInfo.webAbsoluteUrl}/_api/web/lists/getbytitle('Bokningar')/items`;
var options = {
url: url,
type: "GET",
dataType: "json",
headers: {
Accept: "application/json;odata=verbose"
}
};
return jQuery.ajax(options);
}
function updateBoknigarArray(data) {
window.globalBokningsArray = data.d.results;
}
function showError(jqXHR, textStatus, errorThrown) {
console.log('Loading Bokningar content faild: ' + textStatus + jqXHR.responseText);
}
ajaxCallToBoknigar()
.done(updateBoknigarArray)
.fail(showError)
Sorry about this answer, i found a lot of results but anything works on my code.
I want to get the selected item and call another function to work with this. The script is:
<script type="text/javascript">
$(document).ready(function() {
$("input#autoText").autocomplete({
source: function(request, response) {
$.ajax({
url: "UserControllerServlet?action=Autocompletar",
dataType: "json",
data: request,
success: function(data, textStatus, jqXHR) {
console.log(data);
var items = data;
response(items);
alert($("#autoText").val(ui.item.id));
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus);
}
});
}
});
});
</script>
The alert not works, and i try to use select and nothing.
Thx.
Use the select event
$(document).ready(function () {
$("input#autoText").autocomplete({
source: function (request, response) {
$.ajax({
url: "UserControllerServlet?action=Autocompletar",
dataType: "json",
data: request,
success: function (data, textStatus, jqXHR) {
console.log(data);
var items = data;
response(items);
alert($("#autoText").val(ui.item.id));
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(textStatus);
}
});
},
select: function (e, ui) {
console.log('s', ui.item);
//here ui.item will refer to the selected object
}
});
});
Demo: Fiddle
Instead of
alert($("#autoText").val(ui.item.id));
use
$("#autoText").data("autocomplete").selectedItem
This will allow you to access the selected item as an object.
I'm having a problem with converting data sended from "naloga3.php" .
How can i convert from JSON to array.
JAVASCRIPT
<script>
function shrani(){
var formData = {naslov: document.getElementById("naslov").value,
besedilo: document.getElementById("besedilo").value,
datum:0
};
$.ajax({
url : "naloga3.php",
type: "POST",
data : formData,
success: function(data, textStatus, jqXHR)
{
$('#zapisi').append('<a>'+data+'</a></br>');
var x = eval("(" + data + ")");
for(var i=0;i<x.length;i++)
{
$('#zapisi').append('<a>'+x.length+'</a></br>');
}
},
error: function (jqXHR, textStatus, errorThrown)
{
$('#zapisi').append('<a>Napaka</a></br>');
}
});
}
</script>
naloga3.php
<?php
$file="podatki.txt";
$podatki=file_get_contents($file);
$izpolje=array();
$izpolje= json_decode($podatki,true);
$polje=$_POST;
$polje['datum']=date('H:i:s');
if($izpolje!=null)
{
array_unshift($izpolje,$polje);
file_put_contents($file,json_encode($izpolje));
}else
{
$tr=array();
array_unshift($tr,$polje);
file_put_contents($file,json_encode($tr));
}
$podatki=file_get_contents($file);
echo json_encode($izpolje);
?>
My output
[{"naslov":"d","besedilo":"d","datum":"16:07:05"},{"naslov":"dddd","besedilo":"d","datum":"15:51:41"},{"naslov":"d","besedilo":"d","datum":"15:51:33"},{"naslov":"d","besedilo":"d","datum":"15:51:30"},{"naslov":"d","besedilo":"d","datum":"15:51:26"}]
What you need to do is set the dataType of your ajax response to json, then you need to iterate the returned object and append within the $.each() loop.
$.ajax({
url : "naloga3.php",
type: "POST",
data : formData,
dataType: "json", // jQuery will now parse the returned data and return an object
success: function(data, textStatus, jqXHR)
{
$.each(data, function(i,obj){
//now you can acess navlos, besedilo and datum
$('#zapisi').append(obj.naslov+'</br>');
$('#zapisi').append(obj.besedilo+'</br>');
$('#zapisi').append(obj.datum+'</br>');
});
},
error: function (jqXHR, textStatus, errorThrown)
{
$('#zapisi').append('<a>Napaka</a></br>');
}
});
How to access this json data in JavaScript.
when I alert it the result is undefined
Here is jQuery code
$.ajax({
type: "POST",
url: "frmMktHelpGridd.php",
data: {
labNo: secondElement
},
dataType: "json",
beforeSend: function () {
// Do something before sending request to server
},
error: function (jqXHR, textStatus, errorThrown) {
alert('error has occured');
alert(errorThrown);
},
success: function (data) {
//Here is the problem
alert(data[0]['Result']);
}
});
This is PHP code
$data=array($no);
for($i=0;($i<$no && ($row=mysql_fetch_array($result)));$i++)
{
$data[$i]=array();
$data[$i]['Result'] = $row['Result'];
$data[$i]['TestCode'] = $row['TestCode'];
$data[$i]['TestStatus'] = $row['TestStatus'];
$data[$i]['SrNo'] = $row['SrNo'];
}
$data1=json_encode($data);
echo $data1;
exit;
I have tested the PHP file independently,
The json data is output as follows:
[{"Result":"1","TestCode":"22","TestStatus":"0","SrNo":"1"},{"Result":"1","TestCode":"23","TestStatus":"1","SrNo":"2"}]
$.ajax({
type: "POST",
url: "frmMktHelpGridd.php",
data: {
labNo: secondElement
},
dataType: "json",
beforeSend: function () {
// Do something before sending request to server
},
error: function (jqXHR, textStatus, errorThrown) {
alert('error has occured');
alert(errorThrown);
},
success: function (data) {
//Added parse json
var data = jQuery.parseJSON(data)
alert(data[0]['Result']);
}
});
You can access to your data by doing
data[0].Result
It's an Object, not an array.
so data[0]['Result'] it's not the proper way
EDIT:
Since you have more objects, you have to do a loop this way:
$.each(data, function(key, val){
console.log(val.Result);
console.log(val.TestCode);
//...
});
When you see something like
{
"foo":"bar",
...
}
you can access to it the same way as above:
name_of_the_object.foo
that will have the value "bar"
Try to add parse JSON. I have added. Now it may be work.
$.ajax({
type: "POST",
url: "frmMktHelpGridd.php",
data: {
labNo: secondElement
},
dataType: "json",
beforeSend: function () {
// Do something before sending request to server
},
error: function (jqXHR, textStatus, errorThrown) {
alert('error has occured');
alert(errorThrown);
},
success: function (data) {
//Added parse json
var data = $.parseJSON(data)
alert(data[0]['Result']);
}
});
Is there a way that I can see the URL that was requested when I do an Ajax request with jQuery?
e.g.,
var some_data_object = { ...all sorts of junk... }
$.get('/someurl.php',some_data_object, function(data, textStatus, jqXHR) {
var real_url = ? # <-- How do I get this
})
How can I access the URL that jQuery actually used to make the request? Perhaps some method/property of jqHXR? I couldn't find it in the documentation.
Thanks.
Set a break point in success method, then watch
this.url
is the real url for the request.
Here is a possible solution:
Catch the ajax call before it is sent to the server by implementing the beforeSend callback function.
Save the url and the data
Report it in the error message you generate.
var url = "";
$.ajax({
url: "/Product/AddInventoryCount",
data: { productId: productId, trxDate: trxDate, description: description, reference: reference, qtyInCount: qtyInCount }, //encodeURIComponent(productName)
type: 'POST',
cache: false,
beforeSend: function (jqXHR, settings) {
url = settings.url + "?" + settings.data;
},
success: function (r) {
//Whatever
},
error: function (jqXHR, textStatus, errorThrown) {
handleError(jqXHR, textStatus, errorThrown, url);
}
});
function handleError(jqXHR, textStatus, errorThrown, url) {
//Whatever
}
Using $.ajaxPrefilter:
// Make sure we can access the original request URL from any jqXHR objects
$.ajaxPrefilter(function(options, originalOptions, jqXHR) {
jqXHR.originalRequestOptions = originalOptions;
});
$.get(
'http://www.asdf.asdf'
).fail(function(jqXHR){
console.log(jqXHR.originalRequestOptions);
// -> Object {url: "http://www.asdf.asdf", type: "get", dataType: undefined, data: undefined, success: undefined}
});
http://api.jquery.com/jQuery.ajaxPrefilter/
It seems like the ajaxSend global handler (http://api.jquery.com/ajaxSend/) provides the url in its settings parameter. You could store a mapping from the xhr object to the url in your ajaxSend callback, then in your success callback look it up given the xhr object that it provides you with.
var mappings = {};
$.ajaxSend(function(event, xhr, settings) {
mappings[xhr] = settings.url;
});
$.ajax({
url: "http://test.com",
success: function(data, textStatus, xhr) {
console.log("url = ", mappings[xhr]);
delete mappings[xhr];
}
});
This has the advantage of not having to modify each $.ajax() object.
FYI, as an addition to airbai's comment -I cannot comment inside his answer,- you can add your own data to the call and retrieve it inside the callbacks. This way you don't have to parse the URL.
In this example JSONP request I have added the variable user_id (tested with jQuery 3.2):
var request = $.ajax({
dataType: "json",
url: "http://example.com/user/" + id + "/tasks?callback=?",
user_id: id,
success: function(data) {
console.log('Success!');
console.log("User ID: " + this.user_id);
},
timeout: 2000
}).fail(function() {
console.log('Fail!');
console.log("User ID: " + this.user_id);
});
I couldn't find it in the docs either. Maybe just add it to the jqXHR object through a "proxy" wrapper like...
I haven't tested this, so you may need to call
$.param() and concat to the url. See http://api.jquery.com/jQuery.param/
var myGet = function(url, data, success) {
$.get(url, data, function(data, textStatus, jqXHR) {
jqXHR.origUrl = url; // may need to concat $.param(data) here
success(data, textStatus, jqXHR);
});
}
usage:
var some_data_object = { ...all sorts of junk... }
myGet('/someurl.php',some_data_object, function(data, textStatus, jqXHR) {
var real_url = jqXHR.origUrl;
})