How to prevent ajax from auto quoting boolean and numbers - javascript

So what happens is that jQuery will turn something like false and 1 into "false" and "1", which kind of breaks my server code. I can kind of overcome this by using JSON.stringify but then I need to JSON.parse on the server end. Is there anyway for jQuery to not quote booleans, numbers and anything else that normally doesn't need escaping?
let test = {
truthy: false
}
let test2 = {
truthy: false
}
$.ajax({
url: "https://reqres.in/api/users",
type: "POST",
data: {
another: test
},
success: function(response){
console.log(response);
}
});
$.ajax({
url: "https://reqres.in/api/users",
type: "POST",
data: {
another: JSON.stringify(test2)
},
success: function(response){
console.log(response);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Related

Sending variable from one ajax call to the next

I have an API I'm trying to query which requires an initial request to generate the report, it returns a report ID and then in 5 seconds you can pull it from that report ID.
This is what I have which works perfectly and returns the reportID:
$(document).ready(function(){
$("#r2").click(function(){
$.ajax({
url: "report.php",
dataType: 'json',
data: {
type: 'queue',
ref: 2
},
success: function(result){
console.log(result.reportID);
}});
});
});
It returns this:
{"reportID":1876222901}
I'm trying to make it call another ajax call on the back of the first one to collect the report using the reportID as the data varaible "ref". So for example, the second ajax query should have ref: 1876222901
$(document).ready(function(){
$("#r2").click(function(){
$('#loading').show();
$.ajax({
url: "report.php",
dataType: 'json',
data: {
type: 'queue',
ref: 2
},
success: function(result){
console.log(result);
$.ajax({
url: "report.php",
dataType: 'json',
data: {
type: 'get',
ref: result.reportID
},
success: function(result){
console.log(result);
}
});
}});
});
});
What I am stuck with is the way I am passing the variable from the result of the first ajax call to the second. It doesn't seem to make it there. How should I send my report ID 1876222901 into my second ajax call please?
You can do this without jQuery just using browser built-in DOM APIs and the fetch API
const r2 = document.getElementById('r2')
const loading = document.getElementById('loading')
const handleAsJson = response => response.json()
const fetchRef = ({reportId}) =>
fetch(`report.php?type=get&ref=${reportId}`)
document.onready = () => {
r2.addEventListener('click', () => {
loading.show();
// you don't have to interpolate here, but in case these
// values are variable...
fetch(`report.php?type=${'queue'}&ref=${2}`)
.then(handleAsJson)
.then(fetchRef)
.then(handleAsJson)
.then(console.log)
})
}
The solution is instead of writing
ref: result.reportID
You have to write it like this
ref: result.reportID.reportID
Because as your said, the first time you use console.log(result.reportID) the result is {"reportID":1876222901}. Which means you have to chaining dot notation twice to be able to reach the value 1876222901 in the next ajax call.
To be clear:
$(document).ready(function(){
$("#r2").click(function(){
$('#loading').show();
$.ajax({
url: "report.php",
dataType: 'json',
data: {
type: 'queue',
ref: 2
},
success: function(result){
console.log(result); // as you said, console.log(result.reportID) return {"reportID":1876222901}
$.ajax({
url: "report.php",
dataType: 'json',
data: {
type: 'get',
ref: result.reportID //which means, this line would be => ref: {"reportID":1876222901}
// we will correct it like this => ref: result.reportID.reportID
// then we properly get => ref:1876222901
},
success: function(result){
console.log(result);
}
});
}});
});
});
Hopefully it fixes your error.
I think you can try to make another function for calling after your first ajax like
$(document).ready(function(){
$("#r2").click(function(){
$.ajax({
url: "report.php",
dataType: 'json',
data: {
type: 'queue',
ref: 2
},
success: function(result){
console.log(result.reportID);
callSecondAjax(result.reportID)
}});
});
});
now make that function like
function callSecondAjax(reportId){
// do some stuff
}

jQuery AJAX POST method not working

I am trying to execute the AJAX operation. the call is working fine but the problem I am having is that I am getting an empty string as a response. There is no error in the console. all I get is an empty string. Even when I change the dataType to JSON, I still get the same response.
JavaScript Code:
$.ajax({
url: "data/saveCart.php",
method: "POST",
data: {
cartItem:item
},
dataType: "text",
success: function(data){
console.log(data);
}
});
PHP code:
if(isset($_POST['cartItem'])) {
echo "AJAX successful";
} else {
echo "AJAX failed";
}
It seems like it was caused by not stringifying your data.
var item = {
toothbrush: {
price: 1
}
};
$.ajax({
url: "data/saveCart.php",
method: "POST",
data: {
cartItem: JSON.stringify( item )
},
dataType: "text",
success: function(data){
console.log(data);
}
});

Using JSON.stringify and can't access the JSON array

I am using php and using json_encode() function I returned/echoed JSON array. I was using jquery ajax and successfully retrieved this data:
[{"id":"1132","city":"Manila Central Post Office","province":"Manila"}]
I use this code on my Javascript btw:
var val = jQuery.parseJSON(JSON.stringify(result));
and when I tried to accessed the data on the array like:
console.info(val.city); // results to undefine
It gives me 'undefined' result. I tried doing For in loop still doesn't work. Maybe I'm doing something wrong, any help would be great. THANKS
Ajax code:
$.ajax({
type: 'POST',
url: path,
cache: false,
data: postData,
success: function (result) {
var val = jQuery.parseJSON(JSON.stringify(result, false, replacer));
var val2 = jQuery.parseJSON(val);
console.info(val2);
console.info(val2.id);
},
error: function (e) {
$("#sys_msg").html(e);
$("#myModal").modal({
show: true,
backdrop: false,
keyboard: true
});
}
});
val is an array. You need to specify index like below.
var result = [{ "id": "1132", "city": "Manila Central Post Office", "province": "Manila" }];
var val = jQuery.parseJSON(JSON.stringify(result));
alert(val[0].city);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Here val is an array of objects, so you cannot access the city value directly by calling val.city. If the data being returned is already encoded by using json_encode(), then you simply need to use $.parseJSON(data). The following code snippet shows how to do this-
var temp = '[{"id":"1132","city": "Manila Central Post Office", "province":"Manila"},{"id":"1133","city": "Another Test Post Office", "province":"Test"}]'; //Defined temp as string since the data response returned from the server should also be a json encoded string.
var val = $.parseJSON(temp);
$.each(val, function(index, item) {
var city = item.city;
$('.container').append('City: '+city+'<br/>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<div class="container"></div>
See, the issue can be easily resolved by dataType:"json". If you don't have this attached in your ajax code then the returned response will be a json string and in this case only you have to parse it with jQuery.parseJSON() or JSON.parse().
So, you can add the dataType to the ajax or instead just only parse it.
success: function(result){
var val = jQuery.parseJSON(result); // or JSON.parse(result);
console.info(val[0].city);
},
With dataType:
$.ajax({
type: 'POST',
url: path,
cache: false,
data: postData,
dataType: 'json', //<-----add this here
success: function(result) {
for (o in result) { // <----and just use this way
console.info(o.city);
}
},
error: function(e) {
$("#sys_msg").html(e);
$("#myModal").modal({
show: true,
backdrop: false,
keyboard: true
});
}
});
You don't have to stringify it then parse it to JSON again. You can just add dataType: "json" in your AJAX.
$.ajax({
type: 'POST',
url: path,
cache: false,
data: postData,
dataType: "json",
success: function (result) {
console.info(result);
console.info(result.id);
},
error: function (e) {
$("#sys_msg").html(JSON.stringify(e));
$("#myModal").modal({
show: true,
backdrop: false,
keyboard: true
});
}
});

Return the whole file with AJAX/JSON

I have one file with a long script which has a variable "period" in it. I will send the value of that variable via the front page of the site to that file. The value will be filled into the file and return it to the front page.
So I want the code <code period="x"> placed in the front page as something like <code period="1">
I want to do that multiple times with different values.
Does someone know how this can be done?
I saw this script, but it didn't work:
if($error === false) {
alert($error);
$.ajax({
url: '\get.php',
type: 'POST',
dataType: "json",
data: {
period: "1"
},
success: function(data){
alert(JSON.stringify(data));
}
});
Thanks
You have a syntax error. See the inline comment:
if($error === false) {
alert($error);
$.ajax({
url: '/get.php',
type: 'POST',
dataType: "json",
data: {
period: "1"
},
success: function(data){
alert(JSON.stringify(data));
}
});
} // << this was missing
you missed a } for the callback to success.
if($error === false) {
alert($error);
$.ajax({
url: '/get.php',
type: 'POST',
dataType: "json",
data: {
period: "1"
},
success: function(data){
alert(JSON.stringify(data));
}
});
}// **This was missing**

Jquery set HTML via ajax

I have the following span:
<span class='username'> </span>
to populate this i have to get a value from PHP therefor i use Ajax:
$('.username').html(getUsername());
function getUsername(){
$.ajax({
type: 'POST',
url: myBaseUrl + 'Profiles/ajax_getUsername',
dataType: 'json',
data: {
},
success: function(data){
document.write(data);
}
})
}
Now when i debug i see that the returned data (data) is the correct value but the html between the span tags stay the same.
What am i doing wrong?
Little update
I have tried the following:
function getUsername(){
$.ajax({
type: 'POST',
url: myBaseUrl + 'Profiles/ajax_getUsername',
dataType: 'json',
data: {
},
success: function(data){
$('.username').html('RRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRr');
}
})
}
getUsername();
Still there is no html between the tags (no text) but when i look at the console the method is completed and has been executed.
Answer to the little update
The error was in my Ajax function i forgot to print the actual response! Thank you for all of your answers, for those of you who are searching for this question here is my Ajax function:
public function ajax_getUsername(){
if ($this->RequestHandler->isAjax())
{
$this->autoLayout = false;
$this->autoRender = false;
$this->layout = 'ajax';
}
print json_encode($this->currentClient['username']);
}
Do note that i am using CakePHP which is why there are some buildin methods. All in all just remember print json_encode($this->currentClient['username']);
The logic flow of your code is not quite correct. An asynchronous function cannot return anything as execution will have moved to the next statement by the time the response is received. Instead, all processing required on the response must be done in the success handler. Try this:
function getUsername() {
$.ajax({
type: 'POST',
url: myBaseUrl + 'Profiles/ajax_getUsername',
dataType: 'json',
data: { },
success: function(data){
$('.username').html(data); // update the HTML here
}
})
}
getUsername();
Replace with this
success: function(data){
$('.username').text(data);
}
In success method you should use something like this:
$(".username").text(data);
You should set the html in callback
function getUsername() {
$.ajax({
type: 'POST',
url: myBaseUrl + 'Profiles/ajax_getUsername',
dataType: 'json',
data: {
},
success: function(data){
$('.username').html(data);
}
})
}
Add a return statement for the function getUsername
var result = "";
$('.username').html(getUsername());
function getUsername(){
$.ajax({
type: 'POST',
url: myBaseUrl + 'Profiles/ajax_getUsername',
dataType: 'json',
data: {
},
success: function(data){
document.write(data);
result = data;
}
})
return result;
}
You can use .load()
Api docs: http://api.jquery.com/load/
In your case:
$('.username').load(myBaseUrl + 'Profiles/ajax_getUsername',
{param1: value1, param2: value2});

Categories