Ajax get request failing on json - ajax

I'm trying to get a products title via json in an ajax get request. This is my code:
$.ajax({
type: 'GET',
url: '/products/test-product.js',
success: function(result) {
var obj2 = JSON.parse(result2);
console.log(obj2);
var test2= obj2.title ;
},
error: function(status) {
console.warn('ERROR', status);
}
})
However, this keeps failing. The error status looks something like this:
abort: ƒ (a)
always: ƒ ()
complete: ƒ ()
done: ƒ ()
error: ƒ ()
fail: ƒ ()
getAllResponseHeaders: ƒ ()
getResponseHeader: ƒ (a)
overrideMimeType: ƒ (a)
pipe: ƒ ()
progress: ƒ ()
promise: ƒ (a)
readyState: 4
responseText: "{"id":96086,"title":"Test Product"
setRequestHeader: ƒ (a,b)
state: ƒ ()
status: 200
statusCode: ƒ (a)
statusText: "OK"
success: ƒ ()
then: ƒ ()
__proto__: Object
Anybody got any ideas what I'm doing wrong?

Related

How to invoke another function using a parameter fetched JSON result of API call from AJAX

I Have to get ParentId from this function using JSON result and then invoke another function given below after this function:
public fetchLibraryDatafromSharePointList(clientID:string) {
debugger;
const reactHandler = this;
jquery.ajax({
url: `${this.props.siteurl}/_api/web/lists/getbytitle('MSAs')/items?$filter=ClientID eq '${clientID}'&$orderby=Modified desc`,
type: "GET",
headers:{'Accept': 'application/json; odata=verbose;'},
success: function(resultData2) {
reactHandler.setState({
items: resultData2.d.results
});
},
error : function(jqXHR, textStatus, errorThrown) {
}
});
}
Below is the function which has to be invoked on the success of above API and the parameter is coming in the JSON result of the previous call made:-
SetState is done by reactHandler variable
public fetchDatafromSharePointList(ParentID) {
debugger;
const reactHandler = this;
jquery.ajax({
url:`${this.props.siteurl}/_api/web/lists/getbytitle('MSASummaries')/items?
$filter=Parent eq ${ParentID}$top=1&$orderby=Modified desc`,
type: "GET",
headers:{'Accept': 'application/json; odata=verbose;'},
success: function(resultData) {
/*resultData.d.results;*/
reactHandler.setState({
items: resultData.d.results
});
},
error : function(jqXHR, textStatus, errorThrown) {
}
});
}
You can invoke another function in the success response of fetchLibraryDatafromSharePointList(clientID:string) after updating state. i.e:
reactHandler.setState({
items: resultData2.d.results
}, ()=>{
fetchDatafromSharePointList(your_parent_id_goes_here);
});

Ajax error response too late?

Ajax function error response (Network error occurs) waiting for 1 min.
If any function to quickly get for error response?
var $this=$(form);
$.ajax({
url: 'http://www.example.com/post.php',
dataType: 'text',
cache : false,
crossDomain : true,
type: 'post',
contentType: 'application/x-www-form-urlencoded',
data: $this.serialize(),
async:false,
success: function( data, textStatus, jQxhr ){
alert(textStatus);
},
error: function( jqXhr, textStatus, errorThrown ){
alert(errorThrown);
}
});
return false;

Ajax Post integer not posting error

<script>
$(document).ready(function () {
$("#MyForm").click(function () {
var dd = JSON.stringify({
Id: $("#CustomerId").val(),
name: $("#Name").val(),
gender: $("input:checked").val(),
mobile: $("#Mobile").val(),
adress: $("#Adress").val()
});
alert("hi");
$.ajax({
url: '/Cust/Create',
type: 'POST',
contentType: "application/json",
dataType: 'json',
data: JSON.stringify(dd),
success: function (data) {
alert("Data sent to store:" + data);
},
error: function () {
alert("failed in posting");
}
})
});
});
</script>
Iam not able to get the values of the CustomerId and Mobile where as iam getting null values over to the controller can anybody give some suggestion
Thanks in advance.

Issues passing json data to build morris.js plot dynamically

I want to build a morris.js plot dynamically by using ajax, php, and mysql.
i have been searching with no success how to achieve this.
I get the array data successfully with ajax but now i can't pass these data to build the plot.
From the PHP script i get the following json array:
[{"concurso":"2736","R1":"7","R2":"24","R3":"27","R4":"39","R5":"45","R6":"52","R7":"12"},{"concurso":"2737","R1":"16","R2":"19","R3":"23","R4":"29","R5":"33","R6":"49","R7":"36"},{"concurso":"2738","R1":"4","R2":"6","R3":"20","R4":"21","R5":"45","R6":"55","R7":"38"},{"concurso":"2739","R1":"5","R2":"16","R3":"17","R4":"24","R5":"41","R6":"47","R7":"36"},{"concurso":"2745","R1":"1","R2":"13","R3":"19","R4":"29","R5":"41","R6":"46","R7":"50"}]
Where morris.js y is the value after 'concurso', and ykeys are the values after R1, R2, R3, ... R7.
My jQuery looks like this so far:
$.ajax({
url: "ajax/default_chart_numbers.php",
cache: false,
dataType: "json",
timeout:3000,
success : function (data) {
new Morris.Line({
// ID of the element in which to draw the chart.
element: 'revancha',
data: $.parseJSON(data),
xkey: 'concurso',
ykeys: ['R1', 'R2', 'R3', 'R4', 'R5', 'R6', 'R7'],
labels: ['n1', 'n2', 'n3', 'n4', 'n5', 'n6', 'n7'],
hideHover: 'auto',
resize: true
});
},
error : function (xmlHttpRequest, textStatus, errorThrown) {
alert("Error " + errorThrown);
if(textStatus==='timeout')
alert("request timed out");
}
});
I can't see the plot. There's nothing. What am i missing?
Well, fortunately i could fix it myself. Here is my working jQuery ☺:
$.ajax({
url: "ajax/some_handler.php",
cache: false,
type: "POST",
data: {anyVar: 'specialValue4PHPScriptAndDataBaseFilter'},
dataType: "json",
timeout:3000,
success : function (data) {
//console.log(data); alert(JSON.stringify(data));
Morris.Line({
element: 'TheElementName',
data: data,
xkey: 'someID',
ykeys: ['R1', 'R2', 'R3', 'R4', 'R5', 'R6'],
labels: ['n1', 'n2', 'n3', 'n4', 'n5', 'n6'],
hideHover: 'auto',
resize: true
});
},
error : function (xmlHttpRequest, textStatus, errorThrown) {
alert("Error " + errorThrown);
if(textStatus==='timeout')
alert("request timed out");
} /*References: http://stackoverflow.com/questions/22746646/ajax-i-cant-get-data-from-php-by-using-json-encode*/
});
You can use the setData() function on the Morris.Line returned object to update data. Here is a snippet from the morris examples which I've commented. (https://github.com/morrisjs/morris.js/blob/master/examples/updating.html)
// build array filled with placeholder data
var nReloads = 0;
function data(offset) {
var ret = [];
for (var x = 0; x <= 360; x += 10) {
var v = (offset + x) % 360;
ret.push({
x: x,
y: Math.sin(Math.PI * v / 180).toFixed(4),
z: Math.cos(Math.PI * v / 180).toFixed(4)
});
}
return ret;
}
// create the morris chart.
var graph = Morris.Line({
element: 'graph',
data: data(0),
xkey: 'x',
ykeys: ['y', 'z'],
labels: ['sin()', 'cos()'],
parseTime: false,
ymin: -1.0,
ymax: 1.0,
hideHover: true
});
// update the chart with the new data.
function update() {
nReloads++;
// called on the returned Morris.Line object.
graph.setData(data(5 * nReloads));
$('#reloadStatus').text(nReloads + ' reloads');
}
setInterval(update, 100);

Simple jQuery / Ajax error

I have this code:
var custID = 1;
$.ajax({
url: 'php/viewCustomer.php',
type: 'GET',
data: '{custID: ' + custID + '}',
dataType: 'json',
cache: false,
beforeSend: function () {
$('#display').append('<div id="loader"> Lodaing ... </div>');
},
complete: function () {
$('#loader').remove();
},
success: function (data) {
//do something
},
error: function () {
alert('could not process');
}
});
there is an error and alerts the error message could not process, so I tried to debug it like this:
var custID = 1;
$.ajax({
url: 'php/viewCustomer.php',
type: 'GET',
data: '{custID: ' + custID + '}',
dataType: 'json',
cache: false,
beforeSend: function () {
$('#display').append('<div id="loader"> Lodaing ... </div>');
},
complete: function () {
$('#loader').remove();
},
success: function (data) {
//do something
},
error: function (jqXHR) {
alert('Error: ' + jqXHR.status + jqXHR.statusText);
}
});
which outputs:
200 OK
so if it is ok, why on earth is it executing the error: function. Confused, please help.
Your data string is incorrectly formatted, if you are intending it to be a JSON object. There was a previous question about this: Jquery passing data to ajax function
Instead, try:
data: JSON.stringify({custID: custID}),
The format is (key):(variable). My previous answer have placed quotes around the variable, which is not necessary.

Resources