Dojo - request.post on button click - syntax error - javascript

Three questions:
1) Is there any way to make this code more neater? Mainly to avoid so much nesting and quotes within quotes issues?
2) Any advice on parsing error below. I tested some code separately to mke sure it works. (see second code box below).
3) I'm getting "undefined" when I look at request.body in the NodeJS server program that handles this request. From what I read, I didn't need a body parser if the content-type was set to application/json.
<button id="updateStudentButton" data-dojo-type="dijit/form/Button"
data-dojo-props="iconClass:'dijitIconTask',
onClick:function(){
var url = '../student/' + dom.byId('studentId').value;
var studId = dojo.byId('studentId').value;
dom.byId('studentFeedback').value +=
'updateStudentButton clicked studentID=' + studId + '\n';
var firstname = dom.byId('studentFirstname').value;
var lastname = dom.byId('studentLastname').value;
var postBody = JSON.parse(
'{ \"data\": {' +
' \"firstname\": "' + firstname + '\",' +
' \"lastname\": "'+ lastname + '\"' +
'},' +
'\"headers\": { ' +
' \"Content-Type\": \"application/json\" ' +
'}}'
);
dom.byId('studentFeedback').value += 'postBody=' + postBody + '\n';
require(['dojo/request'], function(request){
// AJAX Post the data to the server
request.post(url, postBody
).then(function(response){
dom.byId('studentFeedback').value += response + '\n';
// parse and return data in text boxes
var respJSON = JSON.parse(response);
var rowsAffected = respJSON.rowsAffected;
dom.byId('studentFeedback').value += 'rowsAffected=' + rowsAffected + '\n';
},
function(error){
dom.byId('studentFeedback').value += response;
});
})
}
">
Update
</button>
I tested separatley in NodeJS to make sure quotes all work and saw the correct console.log:
var firstname = 'John';
var lastname = 'Doe';
var postBody = JSON.parse(
'{ \"data\": {' +
' \"firstname\": "' + firstname + '\",' +
' \"lastname\": "'+ lastname + '\"' +
'},' +
'\"headers\": { ' +
' \"Content-Type\": \"application/json\" ' +
'}}'
);
console.log ("postBody=");
console.dir (postBody);
Getting parsing error:
dojo/parser::parse() error Error: SyntaxError: Invalid or unexpected token in data-dojo-props='iconClass:'dijitIconTask',
onClick:function(){
var url = '../student/' + dom.byId('studentId').value;
var firstname = dom.byId('studentFirstname').value;
var lastname = dom.byId('studentLastname').value;
var postBody = JSON.parse(
'{ \'
at Object.construct (parser.js.uncompressed.js:401)
at Object.<anonymous> (parser.js.uncompressed.js:190)
at Object.map (dojo.js:8)
at Object._instantiate (parser.js.uncompressed.js:184)
at parser.js.uncompressed.js:893
at _2f8 (dojo.js:8)
at Promise.then._305.then (dojo.js:8)
at Object.parse (parser.js.uncompressed.js:890)
at Object._parse (html.js.uncompressed.js:301)
at Object.onEnd (html.js.uncompressed

The way to avoid quotes within quotes issue is to have your onClick javascript code inside <script></script> tags.
Below a modified version of your code that works Ok in my environment. The request activates the error callback as I don't have the server handling side.
See the documentation here for the declarative details (use of data-dojo-event), and here for the request details.
For the request, I have stringified the data, as this is what I do in my application (php on the server side). The documentation says it can be a string or object, you may want to try sending the data object, depending on what your server environment expects.
Rgds,
jc
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Neal Walters stask overflow test</title>
<link rel="stylesheet" href="dojo-release-1.12.2-src/dijit/themes/claro/claro.css" media="screen">
</head>
<body class="claro">
<button type="button" id="updateStudentButton" data-dojo-type="dijit/form/Button" data-dojo-props="iconClass:'dijitIconTask'">
<span>update</span>
<script type='dojo/on' data-dojo-event='click'>
var dom = require('dojo/dom');
var url = '../student/' + dom.byId('studentId').value;
var studId = dom.byId('studentId').value;
dom.byId('studentFeedback').value += 'updateStudentButton clicked studentID=' + studId + '\n';
var firstname = dom.byId('studentFirstname').value;
var lastname = dom.byId('studentLastname').value;
var data = {firstname: firstname, lastname: lastname};
//dom.byId('studentFeedback').value += 'postBody=' + postBody + '\n';
require(['dojo/request'], function(request){
// AJAX Post the data to the server
request.post(url, {data: JSON.stringify(data), method: 'POST', handleAs: 'json'}).then(
function(response){
dom.byId('studentFeedback').value += JSON.stringify(response) + '\n';
// parse and return data in text boxes
var rowsAffected = response.rowsAffected;
dom.byId('studentFeedback').value += 'rowsAffected=' + rowsAffected + '\n';
},
function(error){
dom.byId('studentFeedback').value += error;
}
);
});
</script>
</button><p>
<form>
Student feedback: <input id="studentFeedback"><p>
Student first name: <input id="studentFirstname"><p>
Student last name: <input id="studentLastname"><p>
Student id: <input id="studentId"><p>
</form>
<script src="dojo-release-1.12.2-src/dojo/dojo.js" data-dojo-config="async:true"></script>
<script type="text/javascript">
require(["dojo/parser", "dijit/form/Button", "dojo/domReady!"],
function(parser){
parser.parse();
});
</script>
</body>
</html>

data-dojo-props="iconClass:'dijitIconTask'
don't you need to end with "?
data-dojo-props="iconClass:'dijitIconTask'"
You can better the way you are creating JSON ex:
var json={};
json.name="Test";
json.age="23"
when you print json (JSON.stringify(json)), you will see
{
"name":"Test",
"age":"23"
}

Related

passing Flask list to HTML

I am trying to pass Flask list to HTML, but for some reason the output is a blank HTML page. below are my HTML and Javascript code where I am sending list to Python:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="/static/script.js"></script>
<script type="text/javascript"></script>
<title>Vodafone Comms Checker</title>
</head>
<body>
<form name="ResultPage" action="passFails.html" onsubmit="return validateTestPage()" method="post">
Number of Hosts/Ports:<br><input type="text" id="Number"><br/><br/>
Enter Comms Details
<div id="container"/>
</form>
</body>
</html>
and here is the javascript code:
function validateLoginPage() {
var x = document.forms["loginPage"]["sourcehost"].value;
var y = document.forms["loginPage"]["username"].value;
var z = document.forms["loginPage"]["psw"].value;
if(x=="" ||y=="" || z==""){
alert("Please fill empty fields");
return false;
}
else{
return true;
}
}
function validateTestPage() {
var a = document.forms["ResultPage"]["DestinationHost"].value;
var b = document.forms["ResultPage"]["port"].value;
if(a=="" ||b==""){
alert("Please fill empty fields");
return false;
}
else{
return true;
}
}
function addFields(){
// Number of inputs to create
var number = document.getElementById("Number").value;
// Container <div> where dynamic content will be placed
var container = document.getElementById("container");
// Clear previous contents of the container
while (container.hasChildNodes()) {
container.removeChild(container.lastChild);
}
for (var i=1;i<=number;i++){
container.appendChild(document.createTextNode("Host: " + i));
var host = document.createElement("input");
host.type = "text";
host.id = "Host " + i;
container.appendChild(host);
container.appendChild(document.createTextNode("Port: " + i));
var port = document.createElement("input");
port.type = "text";
port.id = "Port " + i;
container.appendChild(port);
// Append a line break
container.appendChild(document.createElement("br"));
container.appendChild(document.createElement("br"));
}
var button = document.createElement("input");
button.setAttribute("type", "button");
button.setAttribute('value', 'Check');
button.setAttribute('onclick', 'checkVal()');
container.appendChild(button);
return true;
}
function checkVal() {
var myHost=[];
var myPort=[];
// Number of inputs to create
var number = document.getElementById("Number").value;
for (var i = 1; i <= number; i++) {
//pass myHost and myPort to first.py for further processing.
myHost.push(document.getElementById('Host ' + i).value);
myPort.push(document.getElementById('Port ' + i).value);
}
for (var i=0; i<number; i++){
alert("Value of Host: " + (i+1) + " is: " + myHost[i]);
alert("Value of Port: " + (i+1) + " is: " + myPort[i]);
}
$.get(
url="/passFails",
data={'host' : myHost},
success = function () {
console.log('Data passed successfully!');
}
);
return true;
}
and here is my Python code where I am receiving the list successfully and even iterating through the values, but the script fails to send the list to my HTML page.
from flask import Flask, render_template, request
import json
import jsonify
app = Flask(__name__)
#app.route('/Results')
def results():
return render_template('Results.html')
#app.route('/passFails')
def pass_fails():
host_list = request.args.getlist('host[]')
print("Value of DATA variable in passFails Decorator is: %s" % host_list)
for val in host_list:
print("The value in VAL Variable is: %s" % val)
return render_template('passFails.html', hosts=host_list)
if __name__ == '__main__':
app.run(debug=True)
below is the HTML that should print the list sent from python, but all I get is a blank page.
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="/static/script.js"></script>
<script type="text/javascript"></script>
<title>Vodafone Comms Checker</title>
</head>
<body>
<ul>
{% for host in hosts %}
<li>In the Host text box, you entered: {{ host }}</li>
{% endfor %}
</ul>
</body>
</html>
Below is the output when I run the program:
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
127.0.0.1 - - [24/Feb/2019 13:44:44] "GET /Results HTTP/1.1" 200 -
127.0.0.1 - - [24/Feb/2019 13:44:44] "GET /static/script.js HTTP/1.1" 200 -
127.0.0.1 - - [24/Feb/2019 13:44:44] "GET /favicon.ico HTTP/1.1" 404 -
127.0.0.1 - - [24/Feb/2019 13:44:56] "GET /passFails?host%5B%5D=a&host%5B%5D=b&host%5B%5D=c HTTP/1.1" 200 -
Value of DATA variable in passFails Decorator is: ['a', 'b', 'c']
The value in VAL Variable is: a
The value in VAL Variable is: b
The value in VAL Variable is: c
Value of DATA variable in passFails Decorator is: []
127.0.0.1 - - [24/Feb/2019 13:45:03] "GET /passFails HTTP/1.1" 200 -
Can anyone tell me what is wrong with the code, and why I can't send my Python list to HTML?????
In your checkVal() function, you are attempting to submit the values to your template asynchronously (via AJAX), but you're not rendering the template with that context.
I would remove this part of your checkVal() function:
$.get(
url="/passFails",
data={'host' : myHost},
success = function () {
console.log('Data passed successfully!');
}
);
And replace it with this:
window.location.href = "/passFails?" + $.param({"host": myHost});
As #guest271314 alluded to, this sends the parameters as a query string, which can then be parsed by the template.
Update Based on Comments
If you have to submit the processed data using a "non-AJAX" POST request, the below should work. This is probably not the best way to do this, but without refactoring your entire code, it's the quickest I can think of to make your code work.
Step 1: Modify the form tag in Results.html
Change your form tag to: <form name="ResultPage" method="" action="">. In other words, remove the values for method and action.
Step 2: Modify the checkVal() function in script.js
Change your checkVal() function to look like this:
function checkVal() {
var myHost = [];
var myPort = [];
// Number of inputs to create
var number = document.getElementById("Number").value;
for (var i = 1; i <= number; i++) {
//pass myHost and myPort to first.py for further processing.
myHost.push(document.getElementById('Host ' + i).value);
myPort.push(document.getElementById('Port ' + i).value);
}
for (var i = 0; i < number; i++) {
alert("Value of Host: " + (i + 1) + " is: " + myHost[i]);
alert("Value of Port: " + (i + 1) + " is: " + myPort[i]);
}
$(document.body).append('<form id="hiddenForm" action="/passFails" method="POST">' +
'<input type="hidden" name="host" value="' + myHost + '">' +
'<input type="hidden" name="port" value="' + myPort + '">' +
'</form>');
$("#hiddenForm").submit();
}
This basically processes the form that the user is entering their data into, puts that data into a separate hidden form, and submits that hidden form as a POST to the server.
Step 3: Modify pass_fails() in app.py to access the data.
In your pass_fails() method, change the value of your host_list variable to be host_list = list(request.form["host"].split(",")). This will read the tuple value for "host" and convert it from a CSV string to a list.
Here's the full version of the modified method:
#app.route('/passFails', methods=["POST", "GET"])
def pass_fails():
host_list = list(request.form["host"].split(","))
port_list = list(request.form["port"].split(","))
print("Value of DATA variable in passFails Decorator is: %s" % host_list)
for val in host_list:
print("The value in VAL Variable is: %s" % val)
return render_template('passFails.html', hosts=host_list)

Why is my json get request not working?

I am working on building a movie search app. It is my first time using json. I cannot figure out why my code is not working. I have it running on localhost using xampp.
On submit
$('.search-form').submit(function (evt) {
// body...
evt.preventDefault();
var $searchBar = $('#search');
var omdbApi = 'http://www.omdbapi.com/?';
var movieSearchTerm = $searchBar.val();
var searchData = {
s:movieSearchTerm,
r:json
}
Here is the callback function
function displayMovies(data) {
// for each search result
$.each(data.items,function(i,movie) {
movieHTML += '<li class="desc">';
//movie title
movieHTML += '<a href="' + movie.Title + '" class="movie-title">';
//release year
movieHTML += '<a href="' + movie.Year + '" class="movie-year">';
//poster
movieHTML += '<img src="' + movie.Poster + '" class="movie-poster"></li>';
$('#movies').html(movieHTML);
}); // end each
// movieHTML += '</li>';
}
$.getJSON(omdbApi, searchData, displayMovies);
});//end submit
r:json
You made a typo.
You haven't created a variable called json and the service expects the value of r to be json.
String literals need to be surrounded with a pair of " or '.
data.items
And the JSON returned doesn't have items, it has Search.

Error in line of javascript 'missing ) after argument list"

I am trying to pass variables to a javascript function but i have the Javascript Error: 'missing ) after argument list"
html = html + '' + 'Lugar: ' +name.name +' Coordenadas: Lat '+ name.lat +' Lng'+ name.lng+ '<br>';
It doesn't look like I am missing any ')'s.
I see you have found your solution, but here's an alternative anyway, which reduces your string concatenation a little. There's still a far better way of achieving this, but this may help you start to see the benefit of moving away from building HMTL via string concatenation.
<meta charset="UTF-8">
<span id="spanTest"></span>
<script>
// Or whatever your initMap2 function does...
function initMap2(lat, lng, name) {
console.log('Lat: ' + lat);
console.log('Lng: ' + lng);
console.log('Name: ' + name);
}
var spanTest = document.getElementById('spanTest');
var worldLocation = { name:"test", lat:98.5, lng:-88.45 };
var anchor = document.createElement('a');
anchor.href = 'javascript:initMap2(' + worldLocation.lat +', ' + worldLocation.lng + ', \'' + worldLocation.name + '\');';
anchor.innerHTML = 'Name: ' + worldLocation.name + ', Lat: ' + worldLocation.lat + ' Lng: ' + worldLocation.lng;
spanTest.appendChild(anchor);
</script>
I'm assuming your last argument is expected to be a string, but it's resolved to look like a variable. Try this instead:
html = html + '<a href="javascript:initMap2(' + name.lat +','+ name.lng +',\''+ name.name +'\');">' // etc.
When name.name resolves to a string, it'll be wrapped in single quotes as expected. It'll look something like javascript:initMap2(1, 2, 'someString').

What is wrong with my foursquare api call?

The live example is here
http://kenziejoy.github.io/frontend-nanodegree-map/
I'm trying to pull data about locations that I have hard coded in an array - either by their foursquare id (didn't seem to be working) or their lat and lng. (client ID and secret are variables I just haven't shown them here)
I don't need any other functionality than just pulling data from their database to display on a map so I thought it would fall under the userless access but it is giving me an error that the request are bad because I don't have the proper authentication.
Thanks in advance
From the foursquare site
"Userless access
Some of our endpoints that don’t pertain to specific user information, such as venues search are enabled for userless access (meaning you don’t need to have a user auth your app for access). To make a userless request, specify your consumer key's Client ID and Secret instead of an auth token in the request URL.
https://api.foursquare.com/v2/venues/search?ll=40.7,-74&client_id=CLIENT_ID&client_secret=CLIENT_SECRET&v=YYYYMMDD
To see what level of permissions each endpoint needs, check out the filters at the top of our endpoints page."
/**********FourSquare***************/
$.ajax({
url:'https://api.foursquare.com/v2/venues/search',
dataType: 'json',
data: 'limit=1' +
'&ll='+ placeItem.lat() +','+ placeItem.lng() +
'&?client_id='+ CLIENT_ID +
'&client_secret='+ CLIENT_SECRET +
'&v=20140806' +
'&m=foursquare',
async: true,
success: function (data) {
var result = data.response.venue;
var contact = result.hasOwnProperty('contact') ? result.contact : '';
if (contact.hasOwnProperty('formattedPhone')) {
placeItem.phone(contact.formattedPhone || '');
}
var location = result.hasOwnProperty('location') ? result.location : '';
if (location.hasOwnProperty('address')) {
placeItem.address(location.address || '');
}
var bestPhoto = result.hasOwnProperty('bestPhoto') ? result.bestPhoto : '';
if (bestPhoto.hasOwnProperty('prefix')) {
placeItem.photoPrefix(bestPhoto.prefix || '');
}
if (bestPhoto.hasOwnProperty('suffix')) {
placeItem.photoSuffix(bestPhoto.suffix || '');
}
var description = result.hasOwnProperty('description') ? result.description : '';
placeItem.description(description || '');
var rating = result.hasOwnProperty('rating') ? result.rating : '';
placeItem.rating(rating || 'none');
var url = result.hasOwnProperty('url') ? result.url : '';
placeItem.url(url || '');
placeItem.canonicalUrl(result.canonicalUrl);
// Infowindow code is in the success function so that the error message
// Content of the infowindow
var contentString = '<div id="iWindow"><h4>' + placeItem.name() + '</h4><div id="pic"><img src="' +
placeItem.photoPrefix() + '110x110' + placeItem.photoSuffix() +
'" alt="Image Location"></div><p>Information from Foursquare:</p><p>' +
placeItem.phone() + '</p><p>' + placeItem.address() + '</p><p>' +
placeItem.description() + '</p><p>Rating: ' + placeItem.rating() +
'</p><p><a href=' + placeItem.url() + '>' + placeItem.url() +
'</a></p><p><a target="_blank" href=' + placeItem.canonicalUrl() +
'>Foursquare Page</a></p><p><a target="_blank" href=https://www.google.com/maps/dir/Current+Location/' +
placeItem.lat() + ',' + placeItem.lng() + '>Directions</a></p></div>';
// Add infowindows
google.maps.event.addListener(placeItem.marker, 'click', function () {
infowindow.open(map, this);
// Bounce animation
placeItem.marker.setAnimation(google.maps.Animation.BOUNCE);
setTimeout(function () {
placeItem.marker.setAnimation(null);
}, 800);
infowindow.setContent(contentString);
});
},
// Alert the user on error.
error: function (e) {
infowindow.setContent('<h5>Foursquare data is unavailable.</h5>');
document.getElementById("error").innerHTML = "<h4>Foursquare data is unavailable. Please try refreshing.</h4>";
}
});
I took a look at the live example URL and you were getting a lot of bad request errors in the JavaScript console in Chrome.
Looking at these, you had a bad URL, you were using:
https://api.foursquare.com/v2/venues/search?limit=1&ll=45.5589522,-122.6517163&?client_id=YOUR_CLIENT_ID&client_secret=YOUR_CLIENT_SECRET&v=20140806&m=foursquare
The problem seems to be that you have:
&?client_id
which makes the URL invalid.
Changing this to
&client_id
fixes this and I then see data coming back from Foursquare.

Bring from a PHP file data sent by $.ajax using Json

As I need to bring separate data from a php file, and create an HTML piece to be injected with jQuery, I've choosen Json.
I send it from my PHP main file (between script tags) like this:
$.ajax({dataType: "json", url:'course_generator.php', data:{co_subj_co:editedCourseId}}).done(function(newCourse){
var newCourseStructure = '<div class="tableRow dynamicRow noHeight injectedRow" data-isMultisubjectValue="'+isMultisubjectValue+'" data-subjectsNum="'+subjectsNum+'" data-id="'+courseId+'" id="'+courseId+'" data-abbrev="'+newCourseAbbrev+'" data-courseTypeId="'+newCourseTypeId+'" title="'+newCourseName+'"><div class="contentColumn40"><span class="tableContentText">'+newCourseName+' ('+newCourseTypeName+')</span></div><div class="contentColumn40">'+subjectList+'</div><div class="contentColumn10"><div class="tableIconLink"><div class="editIcon" data-id="'+courseId+'" title="Editar '+newCourseName+'"></div></div></div><div class="contentColumn10"><div class="tableIconLink"><div data-id="'+courseId+'" class="discontinueIcon" title="Discontinuar '+newCourseName+'"></div></div></div></div>';}
This sends properly editedCourseId value. And what's inside course_generator.php is:
$courseId = $_POST['co_subj_co'];
$select_co = mysql_query("SELECT * FROM course_conf JOIN course_type ON co_fk_ct_id=ct_id JOIN co_rel_subj ON co_subj_co='$courseId' JOIN subject_conf ON su_id=co_subj_subj WHERE co_id='$courseId'");
$result_co = mysql_fetch_array($select_co);
$newCourseId = $result_co['co_id'];
$newCourseName = $result_co['co_name'];
$newCourseAbbrev = $result_co['co_abbrev'];
$newCourseTypeId = $result_co['co_fk_ct_id'];
$newCourseTypeName = $result_co['ct_name'];
$isMultisubjectValue = $result_co['co_multisubject'];
$newCourseValues = '{"newCourseId":'.$newCourseId.',"newCourseName":'.$newCourseName.',"newCourseAbbrev":'.$newCourseAbbrev.',"newCourseTypeId":'.$newCourseTypeId.',"newCourseTypeName":'.$newCourseTypeName.',"isMultisubjectValue":'.$isMultisubjectValue.'}';
I am afraid Im not receiving it properly by $courseId = $_POST['co_subj_co'];, and neither $newCourseValues are being received properly on my main PHP file as my newCourseStructure is not generating anything. Could you please identify the several errors I am sure I'm making? Thank you.
UPDATE:
After changing my PHP main file to:
$.ajax({type : 'POST', dataType: "json", url:'config/forms/course_conf/course_generator.php', data:{co_subj_co:editedCourseId}}).done(function(newCourse){
var courseId = newCourse.newCourseId;
var newcourseName = newCourse.newCourseName;
var isMultisubjectValue = newCourse.isMultisubjectValue;
var subjectsNum = newCourse.subjectsNum;
var newCourseAbbrev = newCourse.newCourseAbbrev;
var newCourseTypeId = newCourse.newCourseTypeId;
var newCourseTypeName = newCourse.newCourseTypeName;
var newCourseStructure = '<div class="tableRow dynamicRow noHeight injectedRow" data-isMultisubjectValue="'+isMultisubjectValue+'" data-subjectsNum="'+subjectsNum+'" data-id="'+courseId+'" id="'+courseId+'" data-abbrev="'+newCourseAbbrev+'" data-courseTypeId="'+newCourseTypeId+'" title="'+newCourseName+'"><div class="contentColumn40"><span class="tableContentText">'+newCourseName+' ('+newCourseTypeName+')</span></div><div class="contentColumn40">'+subjectList+'</div><div class="contentColumn10"><div class="tableIconLink"><div class="editIcon" data-id="'+courseId+'" title="Editar '+newCourseName+'"></div></div></div><div class="contentColumn10"><div class="tableIconLink"><div data-id="'+courseId+'" class="discontinueIcon" title="Discontinuar '+newCourseName+'"></div></div></div></div>';}
And my course_generator.php file to:
$courseId = intval($_POST['co_subj_co']);
$subjectList = "";
$data ="";
$select_co = mysql_query("SELECT * FROM course_conf JOIN course_type ON co_fk_ct_id=ct_id JOIN co_rel_subj ON co_subj_co='$courseId' JOIN subject_conf ON su_id=co_subj_subj WHERE co_id='$courseId'");
$result_co = mysql_fetch_array($select_co);
$outArr['newCourseId'] = $result_co['co_id'];
$outArr['newCourseName'] = $result_co['co_name'];
$outArr['newCourseAbbrev'] = $result_co['co_abbrev'];
$outArr['newCourseTypeId'] = $result_co['co_fk_ct_id'];
$outArr['newCourseTypeName'] = $result_co['ct_name'];
$outArr['isMultisubjectValue'] = $result_co['co_multisubject'];
$subjectsNum=mysql_num_rows(mysql_query("SELECT * FROM co_rel_subj WHERE co_subj_co = '$courseId'"));
$outArr['subjectsNum'] = $subjectsNum;
echo json_encode($outArr);
Instead of showing the HTML piece structured, this is what $newCourseStructure results:
{"newCourseId":"243","newCourseName":"a","newCourseAbbrev":"ae","newCourseTypeId":"1","newCourseTypeName":"M\u00e1ster","isMultisubjectValue":"1","subjectList":"
Edici\u00f3n y Acabado de Imagen Digital<\/div>
","subjectsNum":1}
Your JSON string is not valid JSON because you don't use quotes around the string values. Instead of manually creating JSON, create an array or object and then json_encode() it.
You don't apper to output the JSON string. Use echo or print.
Add dataType : 'json' to your ajax request so that jQuery will parse the JSON, returning the native JavaScript object. All of the variables you use in the success function are undefined. After parsing the JSON you should use
var courseId = newCourse.newCourseId; // and so on
Your ajax request doesn't have a type and so will default to GET. add type : 'POST' if you want to use POST.
Try $_GET['co_subj_co']; instead of POST.
As long as you don't specify the method to jQuery's ajax call, it's made by GET, not POST.
I have annotated two things in the code:
$.ajax({
type : 'POST',
dataType: "json",
url:'config/forms/course_conf/course_generator.php',
data:{
co_subj_co:editedCourseId
}})
.done(function(newCourse){
var courseId = newCourse.newCourseId;
var newcourseName = newCourse.newCourseName;
var isMultisubjectValue = newCourse.isMultisubjectValue;
var subjectsNum = newCourse.subjectsNum;
var newCourseAbbrev = newCourse.newCourseAbbrev;
var newCourseTypeId = newCourse.newCourseTypeId;
var newCourseTypeName = newCourse.newCourseTypeName;
var newCourseStructure = '<div class="tableRow dynamicRow noHeight injectedRow"'
+ ' data-isMultisubjectValue="' + isMultisubjectValue + '"'
+ ' data-subjectsNum="' + subjectsNum + '"'
+ ' data-id="' + courseId + '"'
+ ' id="' + courseId + '"'
+ ' data-abbrev="' + newCourseAbbrev + '"'
+ ' data-courseTypeId="' + newCourseTypeId + '"'
+ ' title="' + newCourseName + '">'
+ '<div class="contentColumn40"><span class="tableContentText">'
+ newCourseName + ' (' + newCourseTypeName + ')</span></div>'
// WHERE IS subjectList DEFINED?
+ '<div class="contentColumn40">' + subjectList
+ '</div>'
+ '<div class="contentColumn10"><div class="tableIconLink">'
+ '<a href="#"><div class="editIcon" data-id="' + courseId + '"'
+ ' title="Editar ' + newCourseName + '"></div>'
+ '</a></div></div><div class="contentColumn10"><div class="tableIconLink">'
+ '<a href="#"><div data-id="'+courseId+'" class="discontinueIcon" '
+ 'title="Discontinuar '+newCourseName+'"></div></a></div></div></div>';
/*
* your HTML is generated, but you never put it in the DOM
*/
$('#idOutputWrapper').empty().html(newCourseStructure);
}
When you use subjectList from the json response, please notice that it comes with a closing </div> tag for some reason, maybe you should change that, too.
btw: Your code formatting is horrible, sorry to say so. You can compress your js before uploading it to the server, but while working on it, it NEEDS to be readable. I just edited it to fit better in the codeblock here.
Are you actually using POST, or are you firing off a GET request (your browser's developer tools should tell you this easily). You should also make sure that $courseId is an integer by $courseId = intval($_POST['co_cubj_co']);. In addition, you should add a condition for the event that the requested ID is not found.
As MueR suggests, the reason to make sure that courseID is an integer is to prevent SQL injection (unless you want people to do things like delete your entire DB at will). This, of course, assumes that courseID is something like an autoincrement int.
However, you've got a number of other problems. Your JSON is invalid since you're ostensibly writing out unquoted strings... you should just use json_encode:
$outArr = array();
$outArr['newCourseId'] = $result_co['co_id'];
$outArr['newCourseName'] = $result_co['co_name'];
...
echo json_encode($outArr);
Personally, I prefer to just use $_REQUEST, which concatenates both $_POST and $_GET. Makes it easier.

Categories

Resources