sending multiple ajax requests not getting expected repsonse - javascript

so i have a javascript function that submits individual submissions from a form to a phpfile (processFeedback.php) that adds each submission to an array. then once the array is filled the array is passed back to the ajax callback (i think that's the proper terminology). if the array is passed back then the array gets passed to another php file (insertFeedback.php) that will insert the data into the database accordingly.
the entire site and all the scripts work perfectly, as in the array is getting filled and passed back to the ajax call correctly. but i'm getting an error message on the (insertFeedback.php) file call. as of right now the insertFeedback.php file does nothing but insert my database connect file. there is no return or anything being done on this page. i have tried several options, setting various arrays and json_encoding them with the same response every time. but i can't get a set answer as to why as the jqxhr.error sends me to a jquery fuction that i do not as of yet understand, and there is no jqxhr.responseText (both of which i use regularly for debugging.
here's my function:
function prepareData(cont, sect) {
var sentData = {'choice': cont, 'section': sect};
var addSession = $.post('processFeedback.php', sentData, null, 'json');
addSession.done(function (fbData) {
console.log('success: ' + fbData);
action = fbData.action;
if (fbData.status) {
receivedData = fbData.data;
console.log('receivedData.age: ' + receivedData.age);
var insertData = $.post('insertFeedback.php', receivedData);
insertData.done(function(insertData) {
console.log('from insert page: ' + insertData);
});
insertData.fail(function(noInsertData) {
console.log('failed at insert page: ' + noInsertData);
})
}
if (!fbData.status) {
console.log('form not complete yet');
}
eval(action);
});
addSession.fail(function (a, b, c) {
console.log('failure: ' + a.reponseText);
});
}
i have been starting at this code for hours, so i know this is going to be a painstakingly simple answer. most likely just messing up my variables somewhere along the way. but any help with why the insertData function keeps failing.

Related

How to continue executing code after return

I'm writing a short program using Google Apps Script that understands certain answers that a user inputs into a form then executes a few things.
At the moment my code takes too long to execute and the form response page is just an error - but it does actually do everything in the background.
What I really want to do is return the response for the function earlier, then continue executing the rest of the code - but I know that is impossible. Any ideas?
function doPost(e) {
//get details from form
var json = e.postData.contents;
var obj = JSON.parse(json)
var answers = getAnswers(obj);
//do a few things...
var parentID = createParent(answers);
import(answers);
textOutput = ContentService.createTextOutput('Form Success! you can log
in with ' + answers.username + ' and password Test1234')
return textOutput
}

Two different ajax urls return the same data

I am using jQuery ajax calls on my django site to populate the options in a select box which gets presented in a modal window that pops up (bootstrap) to the user. Specifically, it provides a list of available schemas in a particular database. The ajax url is dynamic which means it includes a db_host and a db_name in the URL. I have a site with clients and each client has to point to a different host/db.
The db_host and db_name passed via the URL are used in the django view to execute the necessary sql statement on the relevant host/db.
So, the URL should be unique for each db_host/db_name combination.
I am running into a problem where I am on client A's page, I click the button to display the modal. The ajax call is made. I get the data I expect. Everything is fine. Let's say the ajax URL is "/ajax/db_host/server_a/db_name/client_a_db/schema_dropdown".
Now, I got to client B's page and click the same button to display the modal. The ajax call is made. Let's say this time, the ajax URL is
"/ajax/db_host/server_b/db_name/client_b_db/schema_dropdown."
However, the data returned is the actually the data that was returned for the previous ajax call I made ("/ajax/db_host/server_a/db_name/client_a_db/schema_dropdown") and not for the URL (specifically host/db) that I just passed.
I have double/triple checked that my URL is, in fact different, each time. Any help would be appreciated.
Here is my javascript function that gets called just before displaying the modal that populates my select.
function populate_schema_dropdown(db_host, db_name) {
var ajax_url = "/ajax/db_host/" + db_host + "/db_name/" + db_name + "/schema_dropdown"
$.ajax({
url: ajax_url,
success: function (data) {
$("#select-element").empty()
$.each(data, function (i, v) {
$("#schema-element").append("<option value='" + v[0] + "'>" + v[1] + "</option>")
})
}
});
};
Below is my django view.
def ajax_schema_dropdown(request, db_host, db_name):
cursor = get_temporary_db_connection(db_host, db_name).cursor()
cursor.execute("""
SELECT
NAME
FROM [sys].[schemas]
""")
data = [(each[0], each[0]) for each in cursor.fetchall()]
cursor.close()
return HttpResponse(json.dumps(data), content_type="application/json")
Below is get_temporary_db_connection function...
def get_temporary_db_connection(db_host, db_name):
temporary_name = str(uuid.uuid4)
connections.databases[temporary_name] = {
'ENGINE': 'sqlserver_ado',
'NAME': db_name,
'HOST': db_host,
'USER': '',
'PASSWORD': '',
'OPTIONS': {
'provider': 'SQLNCLI11'
}
}
return connections[temporary_name]
Likely the problem in the way of setting temporary_name variable. It's not dynamic like it suppose to be ( I guess ), that's same database as first one are being used for all proceeding ajax calls, to fix it you have to replace line:
temporary_name = str(uuid.uuid4)
to
temporary_name = str(uuid.uuid4()) # note i've changed uuid.uuid4 -> uuid.uuid4()
________________________________^^____
Note: Likely it's make sense close connection to database after working with it, otherwise you will end up with a lot of connections in connections dict. As an option you can keep connection to db in connections dict after it was created and reconnect ( if some condition occured) or simply return existed connection without performing new connection.

Javascript scope of array and converting js array to a php array

Edit/Clarification: I have a php page, call it displayPhotos.php, in which I set up an Ajax call to a different php page, call it getPhotos.php, which queries a database and returns photo information (caption, file name etc) to displayPhotos.php where they are displayed. I use php in displayPhotos to manipulate the data returned from getPhotos. The returned data from the Ajax call is a javascript 2-dimensional array. I need to turn the javascript array into a php array so I can do they display and other stuff. How do I do that?
Hope this helps.
My eyes hurt from reading all of the docs.
I want to use ajax to query a database, return the data then use php to continue with the web page.
All of the examples I've looked at start with creating the json in php. I need to start with the json object in javascript.
<script>
var photoarray = [];
var ajaxRequest = $.ajax
({
url : "fhs_get_photos.php",
type: "POST",
dataType: "json",
success: function(photo_array)
{
photoarray = photo_array;
//line below works. the file name is correct but disappears
//outside of this function
console.log("photoarray[0][file_name] is: " + photoarray[0]['file_name']);
},
error: function(request, status, error)
{
alert('An error occurred: ' );
}
});
In this instance I'm not passing anything to the php file that query's the db. The console log shows that the file name in photoarray is correct but once outside of this function it disappears even though it's declared as global, I think it is anyway. Why and what do I need to do to fix this.
The php file just does a SELECT * FROM..... and returns everything.
// in fhs_get_photos.php
// SELECT * FROM table......
echo $json = json_encode($result);
return $json;
So I now have the array back but it's in javascript. Once I figure out the scope problem, how can I convert this javascript array to a php array?
<h3>Welcome to the Historical Society's historical photo archive
</h3>
</header>
<figure id="photo_figure">
<script>
//line below gets me: SCRIPT5007: Unable to get property 'thumb' of
//undefined or null reference
console.log("photoarray thumb: ") + photoarray[0]['thumb'];
</script>
Am I explaining this properly?
First of all AJAX is async. This means it sends the request when you ask it to, but receives the response sometime later in the future. And it works after php has rendered and sent the page. So. When you get an update via AJAX, you have to use javascript to make that update matter. The most simple solution is to process the response right there in the success callback. That way you don't need to mess with the global scope (which is a bad practice).
Supposedly, your HTML is like this:
<header>
<h3>Welcome to the Historical Society's historical photo archive
</h3>
</header>
<div id="figures"></div>
You can do it by declaring a function that handles the processing:
function updateDom(photoArr) {
var $figures = $('#figures');
$.each(photoArr, function() {
console.log(this);
$figures.append('<img src="' + this.thumb +'">');
});
}
Code below is placed in the success callback
And execute that function in the success callback and pass it the array from json, that was parsed and became a valid js object.
var photoArray = JSON.parse(photo_array);
updateDom(photoArray);
here's the fiddle, but it's for the DOM part only

Javascript code running fine until put into a function

I have taken some source code from here to submit a form using AJAX. The form is basically taking some information from a user and putting it into a database via PHP. The code I have works, but given that what I am working on has many forms all doing the same thing, I - obviously - want to make sure my code is lean and mean. So, making sure that each of my form field names have the same as my database with some matching IDs for various parts of the form for user feedback, have changed it to the following:
<script type="text/javascript">
$(document).ready(function() {
// process the form
$('#formId').submit(function(event) { // for the specified form:
// completeForm('#formId'); // WHERE I CALL THE FUNCTION
// FUNCTION STARTS HERE WHEN IT IS ONE
var formData = {}; formId = '#formId';
$(formId + ' input, ' + formId + ' select, ' + formId + ' textarea').each(
function(index){ // for each item (input, select, textarea in the specified form
var input = $(this);
// First, clear any existing formatting that has been added by previous form inputs
$('#' + input.attr('id') + '-group').removeClass('has-info has-error has-success bg-error bg-info bg-success');
// Next, add data to the array of data to pass to the PHP script
Array.prototype.push.call(formData, input.val());
}
); // End of loop through each item.
// Now the data is collected, call the requested PHP script via AJAX.
$.ajax({
type : 'POST', // define the type of HTTP verb we want to use (POST for our form)
url : $(this).attr('action'), // '/processing/general_settings_processing.php', // the url where we want to POST
data : formData, // our data object
dataType : 'html' // 'json' // what type of data do we expect back from the server
})
// using the done promise callback
.done(function(data) {
// log data to the console so we can see
console.log(data);
// Return success and error messages to the user
// Code to come once the basics have been sorted out!
});
// FUNCTION WOULD END HERE WHEN IT IS ONE.
event.preventDefault();
});
});
</script>
The code as above works absolutely fine; the relevant PHP file is called and - although I have no processing done in this particular file yet - does its stuff (I have it echoing the $_POST array to a file and returning to view in the console log atm).
However, when I try and make it a function, it doesn't - the console log simply echoes out the source code for this document instead of the PHP array that it supposed to be doing. The function is placed above the $(document).ready line; specified as function completeForm(formID) { . . . } , contains the section of code as noted in the comments and called in the commented out line as shown. So, logically (to me) it should work.
The ultimate idea is to have the function to do this in a file that can be called by all the forms that call it, while the code to call the function is in the relevant part of the page. Some pages will have more than one form using it. (I mention that should even if what I am doing here works, it wouldn't when I come to reuse the code!)
(I'm relatively new to JS and JQuery, although have a fairly good grasp of some programming techniques, mainly these days just in PHP.)
The issue you are having with making that a function is you forget to include the "thisBinding". As a result, when you tried to use the form's action target in your ajax call with this code:
url : $(this).attr('action')
it does not find an "action" attribute - basically the issue is that this is actually window and as a result there is no action attribute. Simply bind this to your function call and your code will work as written.
completeForm.call(this,'#formId');
.call MDN

Passing url in async xhttp request not hitting server (although does it first time) - getting syntax error

In my html5 template (also using GAE and datastore/python), I'm making an async js call to server and coming back with some more categories FROM WHICH results/data choices are then given for the user to trigger another selection which shoots off the same async call method. It works the first time, but in the second, it comes back with a syntax error. The call doesn't even seem to make it to the method (no logs!), what gives??? The only difference between the 2 calls to the async js method is in the data passed through the url. There are 3 parameters passed with 1 parameter being used to form the url routing for the server. In both calls, an object key is part of the url. In the first one, the url is derived from the original template rendering through a jinja object {{item.key()}}. In the second one, the key is derived from the key which is stored as a value in the json dictionary passed back from the first one. Perhaps there is something going on here because it does not seem to even hit the server in the second?
The first time the catkey is populated with jinja object key----:
var html_output = "";
{% for item in cat_profession %}
var nameString = "{{item.name}}";
html_output += "" + nameString + "<br />";
{% endfor %}
which works BUT the second time, I'm using the results from the first one to generate categories to call json again to get more
for (var key in cat_JSON)
{
html_output += "" + key + "";
the cat_JSON[key] is a string --- there is something funky going on - but the console logs for the url seem to be ok and I don't see any evidence it is actually reaching server method. The JSON above has the name stored in the key, and the object key stored as the value.
Here's the js function:
function getNextLevel(catkey,catname) {
url = "/api/filter/" + catkey;
subjectAPI.open("GET", url, true);
console.log("url is ", url);
subjectAPI.onload = function() {
var cat_JSON = JSON.parse(this.responseText);
var html_output = "";
for (var key in cat_JSON)
{
html_output += "" + key + "<br />";
}
$(#col).append(html_output);
}
subjectAPI.send();
}
I think you should provide more code how you make the first ajax and the second ajax so that we know more about your issue. With the current information provided, I guess you perform 2 ajax requests in succession and that could be the problem, since ajax request is asyn. When you perform the second request, the response from the first request may not arrive yet.
Updated based on updated question:
The problem is this line, there is a redundant , character at the end
"javascript:getNextLevel(\'" + cat_JSON[key] + "\',\'" + key + "\'," + ")\">"
It should be:
"javascript:getNextLevel(\'" + cat_JSON[key] + "\',\'" + key + "\')\">"

Categories