PHP POST: Setting data variables dynamically from an array - javascript

Hi all I'm pretty new to PHP and AJAX and all that good stuff and I'm a little stumped on how to proceed from here in my code.
I have a form that is getting sent and I have an array (subcategories) which contains the form labels to retrieve the values of the fields. The fields and values are getting created dynamically based on a textfile that the user uploads so I don't have any way of knowing what they are.
var arrayLength = subcategories.length;
for (var i = 0; i < arrayLength; i++) {
var eachfield = subcategories[i];
//Do something
//#C: selector is working fine, cleaning input
var eachfield = $('#' + eachfield).val().trim();
//push the appropriate values with the fixed stuff to a new array
values.push(eachfield);
}
What I'm trying to do is now to set these variables to some name and send them through $data using AJAX and POST.
Something like the following if I was setting everything statically.
var data = {
dimitypedata: dimitype,
densitydata: density,
velocitydata: velocity,
temperaturedata: temperature,
submitbtnclicked: "submitted"
};
//using the data and sending it through a post with promise handling
$.ajax({
type: 'POST',
url: "controller.php",
data: data,
success: function(response) {
//alert("worked");
//console.log(response);
alert(response);
},
error: function() {
alert("There was an error submitting the information");
}
});
I'm not quite sure how to mix these two and it may be partially because of getting a confused and not yet being that great with POST and AJAX calls.
EDIT: It looks like my question was a bit unclear (sorry first post lol) I'm trying to dynamically push values that I take out of an HTML form field. The problem is that the form is generated depending on what the user chooses to upload to the site (so both the fields and the forms. My ultimate goal is to enable the user to edit the dynamically generated form based on a text file that they upload and be able to generate a new text file after editing it on the GUI after clicking on the submit button. I can do this if its static but I'm having trouble figuring out how to do the same if I don't know what the form will contain.
I'm trying to to my data object so I can use it in my AJAX call. Here's a little bit of the PHP code that I would use in the next step if the variables were static:
if(isset($_POST['submitbtnclicked']) && $_POST['submitbtnclicked'] == 'submitted') {
//new instance of model for use
$model = new model();
$dimitypedata = $_POST['dimitypedata'];
$densitydata = $_POST['densitydata'];
$velocitydata = $_POST['velocitydata'];
$temperaturedata = $_POST['temperaturedata'];

For an exact answer, we need to see what the "subcategories" array look like.
If I understood correctly, you would like to put the values in an object instead of an array (values). So the first part would look like:
var data = {};
var arrayLength = subcategories.length;
for (var i = 0; i < arrayLength; i++) {
//notice that now field name and field value go in separate variables
var fieldName = subcategories[i];
//#C: selector is working fine, cleaning input
var fieldValue = $('#'+eachfield).val().trim();
//push the appropriate values with the fixed stuff to a data object
data[fieldName] = fieldValue;
}
//and then you send your gathered data
//using the data and sending it through a post with promise handling
$.ajax({
type: 'POST',
url: "controller.php",
data: data,
success: function(response) {
//alert("worked");
//console.log(response);
alert(response);
},
error: function() {
alert("There was an error submitting the information");
}
});

If you want to generate your 'data' object using 'values' variable, you can do the next:
values = []; // here your values collected previously
var data = {};
for (var key in values){
data[key] = values[key];
}
//now you can use your data in AJAX

Related

Pass html div to ajax call

So I have my server-side code which executes multiple bigquery queries and arranges the results in a table,and this server-side code is called by an ajax call from the client.
I want to be able to send the table/div from my server-side code to client-side and have it render there. Is that possible??
I don't want to be able to create the tables on the client by first getting the JSON results through the call, since I will not know which query will run first and all the results are different. (multiple ajax calls are also out of the question for each query)
Server code (app.js)
function printResult(rows, queryNumber) {
console.log('Query No. '+queryNumber+' Results:____');
var keys = [];
if (queryNumber == 1) {
var table = document.createElement('table');
var td = [];
var tr = document.createElement('tr');
for (var i = 0; i < rows[0].length; i++) {
var tn1 = document.createTextNode(rows[i].Content_title);
var tn2 = document.createTextNode(rows[i].Audience_Size);
td[i] = document.createElement('td');
td[i].appendChild(tn1);
td[i + 1] = document.createElement('td').appendChild(tn2);
tr.appendChild(td[i]);
tr.appendChild(td[i + 1]);
table.appendChild(tr);
res.send(table);
}
}
}
Ajax call
$.ajax({
url: 'http://localhost:3000/example',
type: 'POST',
data: {showname: show, counter: uniquesOverallShowsCounter},
dataType: 'text',
contentType: 'application/x-www-form-urlencoded',
success: function (data) {
document.getElementById('outputTables').appendChild(data);
},
error: function() {
console.log("error");
}
});
Yes you can, but as you pointed out in the comments, there is a problem with the data returned.
Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'.
This is an error which is thrown when you try to append a child node with JavaScript, which is not a documentElement (i.e. document.createElement('div')). Since you're already using jQuery, you could easily change your code.
In the success function for the AJAX call, change
document.getElementById('outputTables').appendChild(data);
to
$('#outputTables').append(data);
If you want to be able to do multiple AJAX calls from one page and change the table every time (like replace the old table with the new one), you should use html(data) instead of append(data).
So can you simply increase one more parameter in your response json based on the query which is hit for example "queryProcessed"?
And add that additional check on client side and render the mark up based on that "queryProcessed"

Using AJAX to do a set of sequential tasks on PHP server

I'm having an issue with the inherent asynchronous-ness of AJAX with what I'm trying to accomplish...
Using a file upload form, I'm trying to send a set of data to my LAMP server which then loops through each subset of the data and generates a PDF for each subset. This takes a good 2 minutes or so to process all of the PDFs since there are so many (like 100) being generated for each subset of data.
I am hoping to use JavaScript/jQuery to segment the data into subsets that I will post to the server one at a time, and as each PDF is generated, get a response from the server and increment a progress bar, then send the next request.
How would you accomplish this in a loop? What's below doesn't work because jQuery doesn't care about the state of the server and sends all requests asynchronously.
var i = 0;
$.each(data_stuff, function(key, value) {
$.post( window.location.href, {
stuff: key,
data: value
}).done(function( data ) {
if (data == 1) {
$('div#counter').text(i);
}
});
$i++;
});
Thanks!
Assuming data_stuff is an Object, you can try this:
var i = 0;
// We need an array (not object) to loop trough all the posts.
// This saves all keys that are in the object:
var keys = Object.keys(data_stuff);
function postNext() {
// For every POST request, we want to get the key and the value:
var key = keys[i];
var value = data_stuff[key];
$.post( window.location.href, {
stuff: key,
data: value
}).done(function( data ) {
if (data == 1) {
$('div#counter').text(i);
}
// Increment i for the next post
i++;
// If it's the last post, run postsDone
if(i == keys.length) {
postsDone();
}
// Else, run the function again:
else {
postNext();
}
});
});
postNext();
function postsDone() {
// All data was posted
}
This will only post the next bit of data_stuff after the previous $.post was done.

Can I pull JSON from api url and use as json2html input?

I have working on a webpage that displays json data in a html hierarchical structure, using the jQuery plugin json2html.
Currently the json data is entered into a text area and a button is pressed to run the conversion. This is the current function that gets the json from the text area and starts the conversion.
$('#btnVisualize').click(function() {
//Get the value from the input field
var json_string = $('#inputJSON').val();
try
{
//json
//var json = JSON.parse(json_string);
eval("var json=" + json_string);
visualize(json);
}
catch (e)
{
alert("Sorry error in json string, please correct and try again: " + e.message);
}
});
The api that the data is comming from needs a lot of authentication, so I have a seperate javascript file that generates the authenticaton and creates the full url to load the api.
function generateUrl(itemkey) {
var orig = "http://explorerapi.barratthomes.co.uk/v2.0/development/getbyitemkey?ItemKey="+itemkey+"&";
Auth.Auth = createAuth();
var var_pairs = [
{name: "Auth.Utc", val: encodeURI(Auth.Auth.Utc)},
{name: "Auth.RequestId", val: Auth.Auth.RequestId},
{name: "Auth.DeviceId", val: Auth.Auth.DeviceId},
{name: "Auth.Hash", val: Auth.Auth.Hash}];
for(var i=0; i<var_pairs.length; i++) {
orig += (i==0?"":"&")+var_pairs[i].name+"="+var_pairs[i].val;
}
var var_names = ["BrandCode", "ApplicationId", "ApplicationVersion", "LanguageCode", "IsPublished", "MarketingSuiteDevelopmentId", "UserLocation", "Os", "ScreenResolution", "Hierarchical"];
for(var j=0; j<var_names.length; j++) {
orig += "&"+var_names[j]+"="+Auth[var_names[j]];
}
return orig;
}
This is the function that generates the url.
I need to take the url from that function and connect to the api and pass the data directly to the json2html function, so I no longer have to paste the json data into the text area.
I have been looking at $.getJson and $.parseJSON but having no luck, I'm not sure where to go next?
Try this Jsonp to do the fetching the data from the url
function insertIntoTextArea(content) {
document.getElementById('output').innerHTML = content;
}
// create script element
var script = document.createElement('script');
// assing src with callback name
script.src = 'your proper url?callback=insertIntoTextArea';
// insert script to document and load content
document.body.appendChild(script);
You should be able to use $.getJSON like this
$.ajax({
dataType: "json",
url: url,
data: data,
success: success
});
And then just pass the data object to json2html. However, check with the API that you're connecting to http://explorerapi.barratthomes.co.uk/v2.0/development/getbyitemkey as they might require JSONP (which pretty much just performs a callback function to get around CORS).
See http://api.jquery.com/jquery.getjson/
If the URL includes the string "callback=?" (or similar, as defined by the >server-side API), the request is treated as JSONP instead. See the discussion >of the jsonp data type in $.ajax() for more details.

ASP Web Pages Razor using AJAX to return array from Database

I'm working with ASP for my coursework and I am using Razor Web Pages to do an application. Now, I would like some help with retrieving information from the SQL database.
As it stands I make an ajax call like this:
$.ajax({
type: "POST",
url: "/timetabler/Includes/ajaxModulesByUserId",
data: { id: UserId },
success: function (data) {
alert(data);
if (data == "ERROR") {
alert("We are unable to store the theme you have selected, therefore the change will not be permanent.");
}
}
});
This quite simply calls ajaxModulesByUserId.cshtml passing a userID of like 1. Now this calls the file fantastically.
Now what I'm trying to do in my CSHTML is take the requested ID, then use my C# function:
public IEnumerable<dynamic> getAllQuery(string query)
{
return _db.Query(query);
}
To execute my query.
Now I call it in my Razor code like this:
string input = "";
input = Request["id"];
var arr = new List<string>();
if (!string.IsNullOrEmpty(input))
{
// Add new sheet to database
using (var repo = new initDatabase("SQLServerConnectionString"))
{
foreach (var row in repo.getAllQuery("SELECT * FROM Module WHERE userID = " + input))
{
arr.Add(""+row.moduleCode+","+row.moduleTitle+"");
}
#session.Serialize(arr);
}
}
So I return the rows from the database and put them into an array, now my problem is, getting those values to the javascript.
As it stands I'm using a trick I read from here Stackoverflow, by using a function like this:
public static string Serialize(object o)
{
JavaScriptSerializer js = new JavaScriptSerializer();
return js.Serialize(o);
}
This will actually let me see the values in Javascript, but I'm getting stuck as I end up with values like this:
How can I receive a clean array? and possibly even return ALL the rows from the database as I've had to do a messy way of passing the code and title in 1 array field but separated by a comma.
Would really appreciate it if you could help me get my output correct.
Thanks
The Web Pages framework includes a Json helper which can take your data and return it as JSON.
if (!Request["id"].IsEmpty())
{
using (var repo = new initDatabase("SQLServerConnectionString"))
{
var data = repo.getAllQuery("SELECT * FROM Module WHERE userID = #0", Request["id"])
Json.Write(data, Response.Output);
}
}

Sorting value fetched by jquery ajax call into javascript multidimensional array

I'd like to store a value that is correctly fetched via (NON ASYNC) ajax call (from facebook graph api) back to my javascript multidimensional array.
Everything works fine until the part when the data that I get from facebook api has to be stored to my previously defined 2d-array (and afterwards printed on the page via jquery append). I simply can't figure out where's the problem.
Here's the code sample:
Defining 2d array and its values:
fbpages = new Array (13);
i=0;
for (i=0;i<=12;i++) fbpages[i]=new Array(4);
fbpages[0][0] = "http://graph.facebook.com/120830347930692?callback=?";
fbpages[0][1] = "Kupi";
fbpages[0][2] = "/vijesti/tag/kupi/";
fbpages[0][3] = 0;
fbpages[1][0] = "http://graph.facebook.com/214014840762?callback=?";
fbpages[1][1] = "Kolek";
fbpages[1][2] = "/vijesti/tag/kolek/";
fbpages[1][3] = 0;
etc...
Fetch the data for every page using the URL from the array fbpages[x][0] and store it back to the same array, to the field fbpages[x][3]:
y=0;
for (y=0;y<=12;y++){
pageURL = fbpages[y][0];
fetchData(y,pageURL);
};
function fetchData (index,fbpageurl) {
$.ajax({
type: "GET",
url: fbpageurl,
dataType: "json",
async: false,
success:function(data){fbpages[index][3]=data.likes;}
});
};
Data printing works fine.
Thanks in advance!

Categories

Resources