AJAX does not return anticipated response [duplicate] - javascript

This question already has answers here:
How do I catch an Ajax query post error?
(8 answers)
Closed 1 year ago.
I'm trying to start to use AJAX to
send a Javascript variable from one PHP file to another
that will enqueue it to a queue function I have created
and then peek that ID in the queue by changing the < p > tag in my main file
EDIT:
I get an error now that I have added an error parameter; either [Object Object] or Undefined and console.log(data) the error is a POST 500 jquery.js
I have tried solutions to add .d after data, altering the dataType to match the response from the Networks panel in Dev Tools, json_encode in the PHP file, but no luck.
Javascript:
var log = document.getElementById("log"); //ID of the <p> tag to change to ID number
document.getElementById("scanButton".addEventListener("click", async () => {
try{
/*functions to obtain ID number*/
var IDnumber = 0000; //functions will change this value after every click
$.ajax({
type: "POST",
url: "savetodb.php",
data: { idNumber : IDnumber },
success: function(data){
log.innerHTML = data;
},
error: function(error) {
log.innerHTML = error;
}
});
} catch (error){
log.innerHTML = error;
});
PHP:
$idNumber = $_POST['idNumber'];
/*queue methods and functions*/
public function peek() {
return $this->queue[$this->front];
}
$queue = new CircularQueue(15);
$queue->enqueue($idNumber);
echo $queue->peek();

Try to catch error through parameter "error" instead of using try catch.
$.ajax({
type: "POST",
url: "savetodb.php",
data: { idNumber : IDnumber},
success: function(){
log.innerHTML = ("ID : " + IDnumber + " logged successfully!");}
},
error: function(error) {
log.innerHTML = error.responseText;
}
);
https://api.jquery.com/jquery.ajax/

Related

Fetching a single record is outputting more than the records contents and json.parse not logging the correct data

I set up a new table called triggers. What I am doing is setting up a simple binary system that triggers things from showing or not showing. The code below is from an attempt I just made at doing this.
I'm running into two issues with the code below.
The echo json_encode is actually echoing onto the file's page. I have never had this happen before, so I'm unsure why it is doing so.
The echoed result is this:
{"specialPopStatus":{"setting":"1","0":"1"}}
The only number that should be showing up is 1. I don't understand where the trailing 0 and 1 are coming from.
The console.log results from the JSON.parse is [object Object]. I don't understand why, if at the very least, the 1, 0 and 1 isn't outputting.
Ultimately, all I am wanting is the setting result from the db for the single record I indicate by the name. Then I want to fetch this record via my ajax function. It will always be either 0 or 1.
What am I doing wrong?
PHP
try {
$con = getConfig('pdo');
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$special_pop_sql = "
SELECT setting
FROM triggers
WHERE trigger_name = 'Special Pop'
LIMIT 1
";
if ($special_pop_stmt = $con->prepare($special_pop_sql)) {
$special_pop_stmt->execute();
$special_pop_row = $special_pop_stmt->fetch();
}
}
catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
echo json_encode(['specialPopStatus' => $special_pop_row]);
JS
var status2 = 0;
function ajaxSpecialPopTrigger() {
$.ajax({
url: '/php/triggers.php',
datatype: 'json',
success: function (data) {
obj = JSON.parse(data);
specialPopStatus = obj.specialPopStatus;
status2 = specialPopStatus;
console.log(status2 + ' This is the status');
}
});
}
ajaxSpecialPopTrigger();
EDIT - New JS:
var status2 = 0;
function ajaxSpecialPopTrigger() {
$.ajax({
url: '/php/triggers.php',
datatype: 'json',
success: function (data) {
//obj = JSON.parse(data);
//Catalog Requests
specialPopStatus = data.specialPopStatus;
status2 = specialPopStatus;
console.log(status2 + ' This is the status');
}
});
}
ajaxSpecialPopTrigger();
The reason for the extra data in the json string is that you use
$special_pop_row = $special_pop_stmt->fetch();
the default of which is to return an assoc array AND a numeric array, notice the data value is 1 in both cases.
So fix that by doing this small mod
$special_pop_row = $special_pop_stmt->fetch(PDO::FETCH_ASSOC);
Also in the javascript because you have given
datatype: 'json',
as the paramter, you dont have to parse the json as jQuery will do that for you
So the javascript code be written
var status2 = 0;
function ajaxSpecialPopTrigger() {
$.ajax({
url: '/php/triggers.php',
datatype: 'json',
success: function (data) {
//obj = JSON.parse(data);
specialPopStatus = data.specialPopStatus;
//status2 = specialPopStatus;
console.log(specialPopStatus + ' This is the status');
}
});
}
ajaxSpecialPopTrigger();

can't return a varable inside a second function [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 4 years ago.
I'm having an issue with this code for pulling usernames from sharepoint.
The function GetuserName() works fine if i change return loginName to alert(loginName); and then i just call the function.
but i'm trying to pull back the value and add it to the arrVal array.
however it's not working, while testing with alerts if I alert(GetUserName()); I get an undefined alertbox. i'm guessing i'm calling the return back wrong but i'm not sure.
Any help would be really useful
(document).on('click', '.genbutt', function() {
var $row = jQuery(this).closest('tr');
var $columns = $row.find('td');
$columns.addClass('row-highlight');
var values = "";
var arrVal = [];
jQuery.each($columns, function(i, item) {
values = values + item.innerHTML + " ";
arrVal = values.split(" ");
});
alert(GetUserName());
});
function GetUserName() {
var userid = _spPageContextInfo.userId;
var requestUri = _spPageContextInfo.webAbsoluteUrl + "/_api/web/getuserbyid(" + userid + ")";
var requestHeaders = {
"accept": "application/json;odata=verbose"
};
$.ajax({
url: requestUri,
contentType: "application/json;odata=verbose",
headers: requestHeaders,
success: onSuccess,
error: onError
});
function onSuccess(data, request) {
var loginName = data.d.Title;
var emailName = _spPageContextInfo.userLoginName;
return loginName;
}
function onError(error) {
alert("error");
}
}
The AJAX call is asynchronous, that's why the alert doesn't immediately receive a value back and therefore it displays undefined. You could use a callback:
GetUserName((val) => {alert(val)})
And change your GetUserName to
GetUserName(cb) {
... cb(loginName) ... //Instead of return
}
Your problem, is that ajax is async, and getUserName() has no return statement. Your return statement is for function onSuccess.

Jquery wait for return of JSON object before executeSQL

In the following function, how can I tell JS to wait for the return of my ajax call before proceeding with sql transaction.
The following sample code currently get the data properly, but the sql transaction is executed before the AJAX call populate my employees []
I try to place sql operation after succes but I got the following error
Uncaught DOMException: Failed to execute 'executeSql' on 'SQLTransaction': SQL execution is disallowed.
Here is part of the code
var addSampleData = function (tx, employees) {
var employees = [];
$.ajax({
url: 'my-path-to-my-json-answer',
success: function (value, status) {
employees.push(value);
},
error: function (XMLHttpRequest, textStatus, exception) {
console.log("Connection with the server fail.\n" + textStatus + 'status is: ' + exception);
}
});
var l = employees.length;
var sql = "INSERT OR REPLACE INTO leaderboard " +
"(id, uFname, uLname, uRegion, uCountry, uScore) " +
"VALUES (?,?,?,?,?,?)";
var e;
for (var i = 0; i < l; i = i + 1) {
e = employees[i];
tx.executeSql(sql, [e.id, e.uFname, e.uLname, e.uRegion, e.uCountry, e.uScore],
function () {
console.log('INSERT success');
},
function (tx, error) {
console.log('INSERT error: ' + error.message);
});
}
}
Any suggestion to improve that code are welcome.
It is because Ajax calls are asynchronous and browser starts a separate thread for the ajax call. In order to execute your SQL query after ajax call completion, put the code you want to SQL query code in success method of ajax as below...
jQuery.ajax({
type:"post",
dataType:"json",
url: myAjax.ajaxurl,
data: {action: 'submit_data', info: info},
success: function(data) {
//do your SQL work here...
console.log('doing SQL work');
},
error: function(data) {
console.log('boo...boo...');
},
});

AJAX is not receiving data on success, it shows the result as "undefined"

This is jQuery code snippet is not getting valid data through AJAX and keeps updating data in divs as undefined. I don't know what the problem is.
function success(data) {
alert(data.amount);
$('#summary').html(data.count + "|" + data.amount);
};
$(document).ready(function () {
$("#button1").click(function (evt) {
evt.preventDefault();
var $form = $("#form1");
$.ajax({
type: $form.prop('method'),
url: $form.prop('action'),
data: $form.serialize() ,
datatype: "json",
tradition: true,
success: function(data) {
success(data);
}
});
});
});
If I modify following success function to simply load a new page that shows the correct results that Action returns
function success(data) {
$('#summary').html(data);
};
This is the controller action code snippet that receives the form fields data (id and quantity) from the view and returns count and amount:
public JsonResult AddtoCartDt(string id,string quantity)
{
int id2 = int.Parse(id);
Product pro = Data.Products.Single(c => c.Id == id2);
var cart = ShoppingCart_BusinessLayer.GetCart(this.HttpContext);
int l = int.Parse(quantity);
for (int i = 0; i < l; i++)
{
cart.AddToCart(pro);
}
var Cart = ShoppingCart_BusinessLayer.GetCart(this.HttpContext);
cartSummary summ = new cartSummary()
{
amount = Cart.GetTotal(),
count = Cart.GetCount()
};
return Json(summ, JsonRequestBehavior.AllowGet);
}
Your code looks fine, but you should add some debug statements to check the response.
For starters, you could pass the success method directly as your ajax success handler, and add an error handler to log out any error:
$.ajax({
type: $form.prop('method'),
url: $form.prop('action'),
data: $form.serialize() ,
datatype: "json",
traditional: true,
// no need for the function()...
success: success,
error: console.log
});
// Alternatively, you could chain it:
$.ajax(/*...*/).done(success).fail(console.log);
That will call pass the JSON response as your success method parameter.
Then, try to add a console.log() statement to debug the response in the console:
function success(data) {
console.log(data);
$('#summary').html(data.count + "|" + data.amount);
};
Edit
Check the tradition parameters in your ajax call. In the doc it's called traditional.
Also, check the route name and http method in your controler.
You may want to add something like this in your controller:
[Route("~/myroute"), HttpPost]
public JsonResult AddtoCartDt(string id,string quantity)
{
/*
*/
}

Sending Query String and Session information using Ajax

I am using Ajax to create comments and its not working , and i am not sure where the problem is. I am thinking it might be in the way i am reading UserID and VideoID
I have UserID saved in a session, and the videoID is saved in Query String.
am i reading them wrong?! if yes how can i read them?
here is my js code:
<script type="text/javascript">
$(document).ready(function () {
$('#btnPost').click(function (e) {
$.ajax({
url: "Ajax/ProcessAddComment.aspx",
data: {
commenttext: $('.txtcomment').val(),
videoid: Request.QueryString["d"],
userid: $.session.get('UserID')
},
success: function (data) {
alert(data);
},
error: function () {
}
});
});
$.ajax({
url: "Ajax/ProcessFindComment.aspx",
data: { videoid: Request.QueryString["id"] },
success: function (data) {
// Append to the bottom
// of list while prepend
// to the top of list
$('.postlist').html(data);
},
error: function () {
alert('Error');
}
});
});
I assume you're using this plugin to get and set your session.
I think your problem is: Request.QueryString
Try using the following JS function to get a value from the querystring rather than that:
function (key) {
if (!key) return '';
key = key.replace(/[*+?^$.\[\]{}()|\\\/]/g, "\\$&"); // escape RegEx meta chars
var match = location.search.match(new RegExp("[?&]" + key + "=([^&]+)(&|$)"));
return (match && decodeURIComponent(match[1].replace(/\+/g, " "))) || '';
};
Note: you can use the network tab in your developer window (F12 in most browsers) to see the Ajax data. The error console in there should tell you if there's a JavaScript error, and the network tab should tell you what was in the Ajax request and response.

Categories

Resources