Trying to pass variable state to server - javascript

So I'm trying to pass a variable Boolean "state" (true/false) to a server from an HTML file.
<script>
$("#aaa").click(function () {
$(this).hide('slow');
$("#bam").html(shay + " arrived ").hide().show(700);
childName = true;
counter++;
if (counter > 12) {
$("#bam").html("All have arrived").hide().show(700);
}
});
</script>
I have multiple instances of this function for each kid arriving to school. The name of the kid's variable equals to true upon clicking his name. What I'd like to do is send these variables' Boolean state to a server, so I'll be able to remotely know what's each kid's "state". Is there a way to do it with jQuery's Post method? If not, what is the most simple way? Thanks!

Yes you can do
<script>
$("#aaa").click(function () {
$(this).hide('slow');
$("#bam").html(shay + " arrived ").hide().show(700);
childName = true;
$.post("url",
{
childStatus: childName,
},
function(status){ // return from server
});
counter++;
if (counter > 12) {
$("#bam").html("All have arrived").hide().show(700);
}
});
</script>

You can post any thing to server with jquery post method like bellow example:
$("#aaa").click(function () {
$(this).hide('slow');
$("#bam").html(shay + " arrived ").hide().show(700);
childName = true;
counter++;
$.post("destination.asp", {childStatus: childName}, function(result){
// do any thing
});
if (counter > 12) {
$("#bam").html("All have arrived").hide().show(700);
}
});

You can have an id for each child. And add an event listener which sends data to server. For example,
HTML:
<button id="id_001" class="childBtn">Arrived</div>
<button id="id_002" class="childBtn">Arrived</div>
<button id="id_003" class="childBtn">Arrived</div>
jQuery:
$(".childBtn").click(function(){
$.post('http://yourserver.com/api', { childId : $(this).attr('id')},
function(data, status) {
//alert("Data: " + data + "\nStatus: " + status);
}
});
I hope that helps :)

Yes, please check out the documentation for .ajax(): official documentation
Could look something like this:
$.ajax({
type: 'POST',
url: 'your-endpoint-url', // the endpoint for the call
data: childName,
success: function(response){
console.log('AJAX success: ' + response);
// maybe do something else here ...
},
error: function(error, status, xhr){
console.log('AJAX error: ' + error);
console.log('STATUS: ' + status + ', XHR: ' + xhr);
}
});
Side note: you say you have multiple instances of this function; then why assign the click function to a DOM element ('#aaa'), rather than doing this through a (e.g.) class selector (give your schookid-rows a css class '.schoolkid' and assign the click function via the class selector)

Related

AJAX call fails with SyntaxError: Unexpected end of JSON input

Sorry for making a post with a generic error but I just can't figure this out! I have an ajax call that for now sends an empty object and just returns json_encode(array('status' => 'success')); while I'm debugging. The ajax call is failing with Error in ajax call. Error: SyntaxError: Unexpected end of JSON input
I've tried sending just data['pid']='csv' in case the json needed to have something in it, but still get the same error.
AJAX call
function runDataDownload() {
var data = {};
// data['rawFiles'] = $('#projectIDs').val();
// data['metadata'] = $('#getData').val();
// data['type']= $('#submitType').val();
// data['pid']='csv';
// data['command']='data/qcTest';
console.log(data);
console.log(typeof data)
var qcRunId="csv" + Date.now();
var posturl = baseURL + "manage/ajax_runBg/csv/" + qcRunId;
$.ajax({type: "POST", url: posturl, data: data, dataType: 'json'})
.done(function(result) {
console.log(result);
if (result.status==='success'){
// begin checking on progress
checkRunStatus(qcRunId, loopIndex);
}
else if (result.status==='failed'){
$('#' + errorId + ' > li').remove();
$.each(result.errors, function(key, value) {
$('#' + errorId).append( "<li>" + value + "</li>" );
});
$('#' + statusId).hide();
$('#' + errorId).show();
}
else {
$('#' + errorId + ' > li').remove();
$('#' + errorId).append( "<li>Invalid return from ajax call</li>" );
$('#' + errorId).show();
// PTODO - may not be needed
// make sure it is visible
$('#' + errorId).get(0).scrollIntoView();
}
})
.fail(function(jqXHR, status, err) {
console.log(jqXHR + status + err);
$('#' + errorId + ' > li').remove();
$('#' + errorId).append( `<li>Error in ajax call. Error: ${status} (${err.name}: ${err.message})</li>`);
$('#' + errorId).show();
});
}
And my php code:
public function ajax_runBg($qcName, $runId) {
echo json_encode(array('status' => 'success'));
}
Thank you!
Making my comment an answer in case someone else runs into this-
The reason the code was working in my controller was that my colleague's controller had authentication checks in the constructor! So there must have been an authentication error returned, that was not JSON formatted, hence the error..
Something seems to clear the PHP output buffer after ajax_runBg has been called. Check this by adding ob_flush(); flush(); to ajax_runBg after the echo statement.
Sorry for making an answer, when i don't have a full one, I don't have enough reputation to comment.
I ran this code (i removed variables that i don't have) and did not get an error (nothing wrong with "echo json_encode(array('status' => 'success'));").
Here are some possible reasons why it fails:
Your problem could be that the php does not echo anything.
I once got this problem and fixed it by first making a variable out of json_encode("stuff to encode") and then doing echo on that variable.
Is there more to the php file that you did not show? There could be a problem if there are other things being echoed.
If i remember right, than you have to specify the key and the value in data attr. .
var data = {};
data['rawFiles'] =$('#projectIDs').val();
data['metadata'] = $('#getData').val();
data['type']= $('#submitType').val();
data['pid']='csv';
data['command']='data/qcTest'
... Ajax...
Data: {dataKey: data}
....
And in the API you can catch it with dataKey name.
When sending json you must first encode it as json, so:
$.ajax({type: "POST", url: posturl, data: JSON.stringify(data), dataType: 'json'})
JSON.stringify

Identifying AJAX request

I am triggering multiple AJAX requests in a loop. They run in parallel and it is not clear which one will respond first.
If the response is successful, I can identify the request by analyzing the response.
for (kk = 0; kk < $('#style').val().length; kk++){
$.ajax({
type: "POST",
url: "/single",
data: {style: [$('#style').val()[kk]]},
success: function (results) {
if (results.status == 'success'){
$('#results').find('div').each(function(){
if ($(this).attr('id') == results.style){
$(this).empty().append(results.payload)
}
});
}
else{
$('#results').find('div').each(function(){
if ($(this).attr('id') == results.style){
$(this).empty().append('<b>' + results.style + ':</b> ' + results.payload)
}
});
}
},
error: function (error) {
console.log(error);
}
});
}
However, once in a while, the request fails and an error is triggered.
For a proper error handling, I would like to know to which of the (previously triggered) requests the error belongs.
Is there a clean method how a specific AJAX request can be identified?
I would recommend to pass in a identifier via context to the AJAX call which you can use inside the success or error methods:
for (kk = 0; kk < $('#style').val().length; kk++){
$.ajax({
type: "POST",
url: "/single",
data: {style: [$('#style').val()[kk]]},
// data inside "context" will be available as part of "this" in the success/error case.
context: {
"kk": kk
},
success: function (results) {
if (results.status == 'success'){
console.log("Element " + this.kk + " finished successfully.");
$('#results').find('div').each(function(){
if ($(this).attr('id') == results.style){
$(this).empty().append(results.payload)
}
});
}
else{
$('#results').find('div').each(function(){
if ($(this).attr('id') == results.style){
$(this).empty().append('<b>' + results.style + ':</b> ' + results.payload)
}
});
}
},
error: function (error) {
console.log("Element " + this.kk + "failed.");
console.log(error);
}
});
}
More information regarding context can be found in the jQuery documentation.
Regarding your comment about checking how many calls failed / succeeded: here is a JsFiddle demonstrating how to keep track of the call statistics.

ajax data isn't the same in chrome vs firefox

Some reason I can return data fine from a POST in Chrome. The data returned looks like this when using Chrome:
{"email":"account#bytestand.com","customer_id":20413,"credit_amount":50.0,"currency_symbol":"$"}
But then when the same POST is completed on FireFox I get the following error:
SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data
Somehow the data isn't being handled the same and I don't know why.
Here is the code that generates the ajax request
function getCustomerAndCredit() {
console.log("getCustomerAndCredit");
$(function() {
$("form[action='" + shopAddress + "/account/login']").submit(function(event){
console.log("this is past the submit event in Firefox");
var custEmail = $("form[action='" + shopAddress + "/account/login'] input[type=email]").val();
var pass = $("form[action='" + shopAddress + "/account/login'] input[type=password]").val();
sessionStorage.setItem('custEmail', custEmail);
sessionStorage.setItem('pass', pass);
sessionStorage.setItem('loggedIn', true);
debugger;
$.ajax({
url: "/apps/proxy/return_customer",
data: {email: custEmail},
type: "POST",
dataType: "js",
complete: function(data) {
debugger;
if(noCustomerInDB(data)){
if(data.responseJSON == undefined){
sessionStorage.setItem('customer_id', JSON.parse(data.responseText).customer_id);
sessionStorage.setItem('creditAmount', JSON.parse(data.responseText).credit_amount);
sessionStorage.setItem('currency', JSON.parse(data.responseText).currency_symbol);
}
else {
sessionStorage.setItem('customer_id', data.responseJSON.customer_id);
sessionStorage.setItem('creditAmount', data.responseJSON.credit_amount);
sessionStorage.setItem('currency', data.responseJSON.currency_symbol);
}
}
// console.log("What is the credit_amount here in getCustomerAndCredit " + sessionStorage.getItem('creditAmount'));
},
});
});
});
}
And then this is where the data is going:
function noCustomerInDB(data){
console.log("this is the todd variable " + data);
console.log("stringify data " + JSON.stringify(data));
console.log("what about just data?? " + JSON.parse(data));
console.log("this is the response down here in the no customer function" + data.responseText);
if(data.responseText == ""){
return false;
}
else{
if (JSON.parse(data.responseText).customer_id == "no_customer"){
sessionStorage.setItem('creditAmount', "null");
return false;
}
else{
return true;
}
}
}
I did some more digging and now its looking like the ajax isn't being called on FireFox. Because the data returned from the POST looks like this:
{"readyState":0,"status":0,"statusText":"error"}
This cannot be - dataType: "js"
Use dataType: "json" instead. Also make sure that "/apps/proxy/return_customer" has the proper header configured to deploy JSON:
"Content-Type: application/json"

How return value in specific field with same class jquery

If you have field with same class but different value I know there is a way to send value with $(this) in jquery but when returning the function result I want to update the specific field that has been clicked ? How I can do this $(this) is changing every field with the same class.
Class is auto generated in loop and I don't want to use different classes for every field.
There must be a way I am missing to achieve this
Here is my code.
$(".voteclick").click(function () {
var dynname = $(this).attr('name');
var votevalue = $(this).next().val();
$.ajax({
url:'http://localhost/wpcomnt/wp-content/themes/smart-mag-child/subrating.php',
type:"POST",
data:"dynname=" + dynname + "&" + dynname + "=" + votevalue + "&measure=" + $('#measure').val(),
dataType:'json',
success:function (mydata) {
if(votevalue == 'up') {
$(this).val('Agree: ' + mydata); // this must not change every .voteclick field it should change only the clicked one ?
}
else if(votevalue == 'down') {
$(this).val('Disagree: ' + mydata); // this must not change every .voteclick field it should change only the clicked one ?
}
//$(".voteclick").val('Agree: '+mydata);
},
error:function () {
$(".errormainbtn").slideDown();
}
});
});
Please read the comment next to this line $(this).val('Disagree: '+mydata);
there are many field's they are changed once I click it because the class is same, and auto generated please tell me a way by which I can change only the field I clicked the class is
".votelick"
As Wolff mentioned, you need to set context:this in the options for the ajax call. By default, in the success function, $(this) refers to the jqXHR object. If your ajax call is in an event handler, and you set context:this, $(this) in the success function will instead refer to the element that triggered the handler.
Here's a working example
$(".voteclick").click(function () {
var dynname = $(this).attr('name');
var votevalue ='up';//changed for example
$.ajax({
url:'test.php',//changed for example
type:"POST",
context:this, //this is the line you need to add
data:"dynname=" + dynname + "&" + dynname + "=" + votevalue + "&measure=" + $('#measure').val(),
dataType:'text', //changed from 'json' for my example
success:function (mydata) {
if(votevalue == 'up') {
$(this).val('Agree: ' + mydata);
}
else if(votevalue == 'down') {
$(this).val('Disagree: ' + mydata);
}
},
error:function () {
$(".errormainbtn").slideDown();
}
});
});

Upon querying a database, delete an item from a list obtained via getJSON

I have a list of items obtained upon querying a database. Result of the query is treated with jsonifyand finally obtained via getJson, by doing the following:
$(function() {
$.getJSON($SCRIPT_ROOT + '/appointments/', function(data) {
var output="<ul>";
for (var i in data.appts) {
output+="<li>" + data.appts[i].labo + "</li>"
}
output+="</ul>";
$("#result").html(output)
return false;
});
});
So far so good...
Now I need to give the possibility to delete each of the above listed items, by calling (for example ) the following Flaskfunction:
#app.route('/appointments/<int:appointment_id>/delete/', methods=['DELETE'])
def appointment_delete(appointment_id):
appt = db.session.query(Appointment).get(appointment_id)
db.session.delete(appt)
db.session.commit()
return jsonify({'status': 'OK'})
Unfortunately I have no clue on how it's possible to bridge these two pieces of code. Since I've being struggling on that for a while, I would appreciate any help that will allow me to get out of the mud... Thanks a lot.!
EDIT according to #dcodesmith's comment
The getJSON response:
{
"appts":[
{
"id":1,
"day":"Mardi",
"labo":"l1",
"modified":[
"21/01/2014"
],
"groups":"5",
"plage_h":"10h00",
"sem":"5",
"start":[
"28/01/2014"
]
},
{
"id":4,
"day":"Vendredi",
"labo":"l1",
"modified":[
"22/01/2014"
],
"groups":"5",
"plage_h":"10h00",
"sem":"5",
"start":[
"31/01/2014"
]
}
]
}
Changes required
Firstly, edit your output HTML to include an anchor tag which should have a data-id attribute with the appts id assigned to it.
Create a click event on the anchor tag in your list of appts
Code
$(function() {
$.getJSON($SCRIPT_ROOT + '/appointments/', function(data) {
var output = "<ul>";
for (var i in data.appts) {
var appt = data.appts[i];
output += "<li>" + appt.labo + "delete</li>"
}
output+="</ul>";
$("#result").html(output)
return false;
});
$(document).on('click', 'a.delete', deleteAppt);
function deleteAppt(e){
e.preventDefault();
var $this = $(this),
id = $this.data('id'),
url = "/appointments/" + id + "/delete/";
$.ajax({
url: url,
type: 'POST',
data: {id: id}
})
.done(function(data, textStatus, jqXHR){
if (data.status === 'OK'){
// if successful remove deleted row
$this.parent('li').remove();
}
})
.fail(function(jqXHR, textStatus, errorThrown){
//log your error here, if any is caught. This will be very helpful for debugging
})
}
});
Note: I know nothing about Flask, but this should work Ceteris Paribus

Categories