I have a form on my website which passes its values to some JavaScript which then passes the information to a PHP page to update the database. When the form is submitted all of the values are added to the database except the two fields which are text areas.
If I remove the JavaScript and add a simple form action to directly pass the variables to the PHP page then all of the information is added to the database including the two text area fields and so it seems the problem must be in theform and the JavaScript, otherwise the two fields wouldn't get added to the database regardless.
Below is my form and my JavaScript. ( Top keep it simple I have only included the two elements of the form which have the problems as it is a long form, if this is the wrong approach then please let me know.)
<form action="" method="post" class="save">
<label class="col-sm-3 control-label">Notes</label>
<textarea name="notes" rows="10" class="form-control"></textarea>
<input type="submit" name="submit" class="save" value="Save This Job" id="blue"/>
</form>
And now the JavaScript
$(document).ready(function(){
$('form.save').submit(function () {
var ref_number = $(this).find("[name='ref_number']").val();
var job_title = $(this).find("[name='job_title']").val();
var start_date = $(this).find("[name='start_date']").val();
var closing_date = $(this).find("[name='closing_date']").val();
var category = $(this).find("[name='category']").val();
var location = $(this).find("[name='location']").val();
var salary = $(this).find("[name='salary']").val();
var client = $(this).find("[name='client']").val();
var job_description = $(this).find("[name='job_description']").val();
var license = $(this).find("[name='license']").val();
var notes = $(this).find("[name='notes']").val();
// ...
$.ajax({
type: "POST",
url: "save.php",
data: {
ref_number : ref_number,
job_title : job_title,
start_date : start_date,
closing_date : closing_date,
category : category,
location : location,
salary : salary,
client : client,
job_description : job_description,
license : license,
notes : notes,
},
success: function(){
new PNotify({
title: 'Job Posted',
text: '
type: 'success',
shadow: true
});
}
});
this.reset();
return false;
});
});
So here is a simplified version of the PHP which I keep changing, as I said above if I send the variables direct to the PHP page all of the information is added to the mysql database, no problems, but when using the JavaScript the job description and notes fields do not get added.
$ref_number = $_POST['ref_number'];
$job_title = $_POST['job_title'];
$start_date = $_POST['start_date'];
$closing_date = $_POST['closing_date'];
$category = $_POST['category'];
$location = $_POST['location'];
$salary = $_POST['salary'];
$client = $_POST['client'];
$job_description = $_POST['job_description'];
$license = $_POST['license'];
$posted_by = $_POST['posted_by'];
$site_id = $_POST['site_id'];
$notes = $_POST['notes'];
mysql_query("INSERT INTO joborders
(ref_number, job_title, start_date, closing_date, category, location, salary, client_name, job_description, license_required, site_id, posted_by, status, notes, posted_date) VALUES('$ref_number', '$job_title', '$start_date', '$closing_date', '$category', '$location', '$salary', '$client', '$job_description', '$license', '$site_id', '$posted_by', 'open', '$notes', NOW()) ")
or die(mysql_error());
So i found the problem, at the bottom of the page was this piece of code, which i hadn't noticed before even though i have looked at it a dozen times. As soon as i removed it, it worked, so now i just need to work out if i can incorporate it on to the existing code so i can still use the tnymce
tinymce.init({
selector: "textarea"
});
OK so the problem turned out to be because there was this piece of code on the page
tinymce.init({
selector: "textarea"
});
So i changed this to reference the class of the text are in the form, like this.
tinymce.init({
selector: "textarea.form-control",
});
And now all of the form fields post to the database.
Thanks for all your suggestions and comments, much appreciated.
Related
I have this posts.php where it uses a unique id to view different contents. For example: posts.php?id=1 will display all data on my table which has an id of 1, id = 2 for 2 and so on...
This id is held on a php var $post_id on each page and in order to send this php variable on my jquery/javascript, I used:
<div id = "dummy_disp" style = "display: none;">
<?php echo htmlspecialchars($post_id); ?>
</div>
<div id = "real_commentsno"></div>
( I know, not the best way to do it but it works)
It connects to my js:
var commentid = document.getElementById("dummy_disp");
var commentidreal = commentid.textContent;
$.ajax ({
type:"GET",
url:"php/post_comments.php",
data:'comid='+commentidreal,
success: function(data){
$("#real_commentsno").html(data);
}
});
I have this post_comments.php where it has:
$cc_g_postid = htmlentities($_GET['comid']);
$cc_postid = mysqli_real_escape_string($con,$cc_g_postid);
$cc_sql = "SELECT * FROM comments WHERE postuniqueid = '$cc_postid' ";
$cc_result = mysqli_query($con,$cc_sql);
$cc_count = mysqli_num_rows($cc_result);
echo $cc_count;
When I try to view the post_comments.php alongside with the attached url var: ?comid=1 the page displays 2 which is correct since post id=1 on my table has only 2 comments. But when I go to my posts.php the ajax displays 0, not 2. I tried looking at the console, there were no errors.
Is there anything I missed or misdo? Also, post_comments.php is on located on mypage/php/post_comments.php whereas posts.php is located on mypage/posts.php ( i dunno if this is necessary info but maybe the url is jamming it or something? )
The problem is that the DIV has newlines and spaces around the ID number. You need to remove all this whitespace.
var commentidreal = commentid.textContent.trim();
I've had some trouble getting this to work in the new user registration form, what I want is to have the email field automatically filled with a dummy email generated based on the username.
For example, if the user inputs user1 the generated email should be user1#test.com
I want it to be done in the new user form in case a user has a real email it can be specified instead of the dummy one.
What I've tried was some javascript and jQuery, but I can't get it to work, you can see the code below.
jQuery('#user_login').on('input propertychange paste', function()
{
var x = $('#user_login').val();
$($email).val( x + '#test.com');
});
Current javascript
<script>
$("user_login").change(function AutoEmail() {
var x= $('#user_login').val();
$('#email').val(x+'#test.com');
});
</script>
Also, where should this code be placed?, I'm a bit lost on the way things are organized in WordPress.
Try this.
$(document).on( "input", "#user_login", function AutoEmail() {
var x= $('#user_login').val();
if( x != "" ) {
$('#email').val(x+'#test.com');
} else {
$('#email').val("");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
Username: <input type = "text" id = "user_login"><br>
Email: <input type = "text" id = "email">
I have an input tag that takes a users input that calls an AJAX dynamically outputs suggestions from my database. The issue is I want to store the primary key associated with that attribute.
I have figured out a way set it to the primary key when the user selects a value; however I would rather only have the attribute displayed on the front end. Essentially what I was thinking about doing was using the option tag and setting the value to the primary key, but after reading the documentation for it, that doesnt look like it would work.
HTML:
<input type="text" id = "zip_id" class="tftextinput2" autocomplete = "off" name="zip" placeholder="Zip Code" onkeyup = "autocompleter()">
<ul id = "zip_codes_list_id"></ul>
JS:
function autocompleter()
{
var min_length = 1; // min caracters to display the autocomplete
var keyword = $('#zip_id').val();
if (keyword.length >= min_length) {
$.ajax({
url: 'ajax_refresh.php',
type: 'POST',
data: {keyword:keyword},
success:function(data){
$('#zip_codes_list_id').show();
$('#zip_codes_list_id').html(data);
}
});
} else {
$('#zip_codes_list_id').hide();
}
}
// set_item : this function will be executed when we select an item
function set_item(item)
{
// change input value
$('#zip_id').val(item);
// hide proposition list
$('#zip_codes_list_id').hide();
}
PHP:
<?php
//connect to db here
$keyword = '%'.$_POST['keyword'].'%';
$sql = "SELECT * FROM zip_codes WHERE zip LIKE (:keyword) ORDER BY zip_codes_id ASC LIMIT 0, 10";
$query = $pdo->prepare($sql);
$query->bindParam(':keyword', $keyword, PDO::PARAM_STR);
$query->execute();
$list = $query->fetchAll();
foreach ($list as $rs)
{
// put in bold the written text
$zip = str_replace($_POST['keyword'], '<b>'.$_POST['keyword'].'</b>', $rs['zip']);
// add new option
// echo '<li onclick="set_item(\''.str_replace("'", "\'", $rs['zip']).'\')">'.$zip.'</li>'; (this one only passes the attribute)
echo '<li " onclick="set_item(\''.str_replace("'", "\'", $rs['zip_codes_id']).'\')">'.$zip.'</li>';
//this one passes the attribute but changes the displayed value to the primary key.
}
?>
As you can see from the PHP file, what I am trying to do is pass in the primary key value but keep the displayed value the attribute. I am not sure how to do that. Should I be using the UL tag?
The issue in your code is that you try to the zip_id value for the input, but this input contains the zip field value - I assume it's the textual representation. There are a few ways how you could save the zip_id on the frontend - either store it in the model (if you're using some MVC framework, but I gues it's not the case) or simply add a hidden input field:
<input type="hidden" id="actual_zip_id" name="zip_id">
And
function set_item(item)
{
// change input value
$('#actual_zip_id').val(item);
// hide proposition list
$('#zip_codes_list_id').hide();
}
UPD
Speakng about the entire idea of autocompleting zip codes, it looks pretty nasty, as pointed by Darren Gourley (check the comments).
So you'd rather validate it with regex first, and then do your db-related logic like that:
$('#zip_id').on('change', function(){
// your stuff
})
Best regards, Alexander
I have this problem on how I could automatically update my webpage without refreshing. Could someone suggest and explain to me what would be the best way to solve my problem? Thanks in advance
add.php file
In this php file, I will just ask for the name of the user.
<form id="form1" name="form1" method="post" action="save.php">
<input type="text" name="firstname" id="firstname"/>
<input type="text" name="lastname" id="lastname"/>
<input type="submit" name="add" id="add" value="add"/>
</form>
save.php In this file, I will just save the value into the database.
$firstname=isset($_POST['firstname'])? $_POST['firstname'] : '';
$lastname=isset($_POST['lastname'])? $_POST['lastname'] : '';
$sql="Insert into student (sno,firstname,lastname) values ('','$firstname','$lastname')";
$sql=$db->prepare($sql);
$sql->execute();
studentlist.php In this file, i want to display the name I enter
$sql="Select firstname, lastname from student";
$sql=$db->prepare($sql);
$sql->execute();
$output="The List of students <br></br>";
while($result=$sql->fetch(PDO::FETCH_ASSOC))
{
$output.="".$result['firstname']." ".$result['lastname']."<br></br>";
}
Problem
When the two pages is open, I need to refresh the studentlist.php before i can see the recently added data.
thanks :D
You'll want to use ajax and jquery. Something like this should work:
add.php
add to the head of the document:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function(){//loads the information when the page loads
var saveThenLoad = {
url: "save.php",//the file sending data to
type: 'POST',//sends the form data in a post to save.php
dataType: 'json',
success : function(j) {
if(j.error = 0){
$("#student_info").html(j.info);//this will update the div below with the returned information
} else {
$("#student_info").html(j.msg);//this will update the div below with the returned information
}
}
}
//grabs the save.submit call and sends to the ajaxSubmit saveThenLoad variable
$("#save").submit(function() {
$(this).ajaxSubmit(saveThenLoad);
return false;
});
//grabs the submit event from the form and tells it where to go. In this case it sends to #save.submit above to call the ajaxSubmit function
$("#add").click(function() {
$("#save").submit();
});
});
</script>
<!-- put this in the body of the page. It will wait for the jquery call to fill the data-->
<div id="student_info">
</div>
I would combine save and studentlist into one file like this:
$return['error']=0;
$return['msg']='';
$firstname=isset($_POST['firstname'])? $_POST['firstname'] : '';
$lastname=isset($_POST['lastname'])? $_POST['lastname'] : '';
$sql="Insert into student (sno,firstname,lastname) values ('','$firstname','$lastname')";
$sql=$db->prepare($sql);
if(!$sql->execute()){
$return['error']=1;
$return['msg']='Error saving data';
}
$sql="Select firstname, lastname from student";
$sql=$db->prepare($sql);
if(!$sql->execute()){
$return['error']=1;
$return['msg']='Error retrieving data';
}
$output="The List of students <br></br>";
while($result=$sql->fetch(PDO::FETCH_ASSOC))
{
$output.="".$result['firstname']." ".$result['lastname']."<br></br>";
}
$return['$output'];
echo json_encode($return);
Does this need to be in three separate files? At the very least, could you combine add.php and studentlist.php? If so, then jQuery is probably the way to go. You might also want to use some html tags that would make it easier to dynamically add elements to the DOM.
Here's the combined files:
<form id="form1" name="form1">
<input type="text" name="firstname" id="firstname"/>
<input type="text" name="lastname" id="lastname"/>
<input type="submit" name="add" id="add" value="add"/>
</form>
The List of students <br></br>
<ul id="student-list">
<?php
//I assume you're connecting to the db somehow here
$sql="Select firstname, lastname from student";
$sql=$db->prepare($sql);
$sql->execute();
while($result=$sql->fetch(PDO::FETCH_NUM)) //this might be easier to output than an associative array
{
//Returns will make your page easier to debug
print "<li>" . implode(" ", $result) . "</li>\n";
}
?>
</ul>
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script>
$(function(){
$('#form1').submit(function(event){
event.preventDefault();
//submit the form values
var firstname = $('#firstname').val();
var lastname = $('#lastname').val();
//post them
$.post( "test.php", { firstname: firstname, lastname: lastname })
.done( function(data) {
//add those values to the end of the list you printed above
$("<li>" + firstname + ' ' + lastname + "</li>").appendTo('#student-list');
});
});
});
</script>
You might want to do some testing in in the $.post call above to make sure it was handled properly. Read more about that in the docs.
If you really need three files, then you'll might need to use ajax to do some sort of polling on studentlist.php using setTimeout to see if you have any new items.
The cheap-way is using a meta-refresh to refresh your page (or use JavaScript setInterval and ajax).
The more expensive way is having a Realtime JavaScript application. Look at Socket.IO or something like that.
I have a select box with a list of books. The user can select a book and hit the submit button to view the chapters on a separate page.
However, when the user changes the select box, I would like a partial page refresh to display the past notes the user entered on the book, and allow the user to write a new note for that book. I do not want the review and creation of notes for a particular book done on the next page with the chapters, as it will clutter it up.
I'm using Python/Bottle on the backend and its SimpleTemplate engine for the front end.
Currently, when the select box is changed, an ajax call receives a Json string containing the book information and all the notes. This json string is then converted into a json object via jQuery.parseJson().
What I would like to be able to do is then loop over the notes and render a table with several cells and rows.
Would I have to do this in jQuery/js (instead of bottle/template framework) ? I assume so as I only want a partial refresh, not a full one.
I'm looking for a piece of code which can render a table with variable numbers of rows via jQuery/js from a json object that was retrieved with ajax.
<head>
<title>Book Notes Application - Subjects</title>
<script src="http://code.jquery.com/jquery-latest.min.js"
type="text/javascript"></script>
<script>
$(document).ready(function(){
$('#subject_id').change(function(){
var subject_id = $(this).val();
$.ajax({
url : "subject_ajax?subject_id=" + subject_id,
success : function(data) {
alert(data)
json = jQuery.parseJSON(data);
},
error : function() {
alert("Error");
}
});
})
})
</script>
</head>
<body>
<!-- CHOOSE SUBJECT -->
<FORM action="/books" id="choose_subject" name="choose_subject" method="POST">
Choose a Subject:
<select name="subject_id" id="subject_id">
% for subject in subjects:
<option value="{{subject.id}}">{{subject.name}}</option>
% end
</select><input type="submit" name="sub" value="Choose Subject"/>
<BR />
</FORM>
This greatly depends on how your JSON and HTML are formatted. But with a table somewhere like:
<table id="books">
<tr>
<th>Chapter</th>
<th>Summary</th>
</tr>
</table>
You could do something like:
$(function(){
$('#choose_subject').submit(function () {
var subject_id = $(this).val();
$.getJSON("subject_ajax?subject_id=" + subject_id, function(data) {
console.log(data);
$.each(data.chapters, function (index, chapter) {
$('#books').append('<tr><td>' + chapter.title + '</td><td>' + chapter.summary + '</td></tr>');
})
});
return false;
})
})
This supposes JSON like:
{
"notes": [
"Note 1",
"Note 2"
],
"chapters": [
{
"title": "First chapter",
"summary": "Some content"
},
{
"title": "Second chapter",
"summary": "More content"
}
]
}
Other notes:
If you use HTML 4 or earlier, keep all your tags in upper case. If you're using XHTML or HTML5, keep all your tags in lower case.
You don't need $(document).ready(function () {...}), with recent versions of jQuery $(function () {...} ) works the same and it's easier to read.
You can use $.get instead of $.json if you're only using the success state (as you are here). And if you're confident that the data you'll get is valid JSON, you can use getJSON instead of get. It will parse the JSON for you deliver it to you as a JavaScript object automatically.
It's usually more convenient to use console.log rather than alert when you're testing. Actually, it's usually a bad idea in general to ever use alert.
I'm not familiar with Python/Bottle or its SimpleTemplate engine, but you could consider generating the html for the table on the server side and returning it in the ajax response, rather than returning JSON.
var subject_id = $(this).val();
$.ajax('subject_ajax', {
type: 'get',
data: { subject_id: subject_id },
dataType: 'html',
success : function(html) {
// Insert the html into the page here using ".html(html)"
// or a similar method.
},
error: function() {
alert("Error");
}
});
When calling .ajax():
The "type" setting defaults to "get", but I prefer to explicitly set it.
Use the "data" setting for the ajax call to specify the URL parameter.
Always specify the "dataType" setting.
I also recommend you perform the ajax call in an on-submit handler for the form, and add an on-change handler for the select that submits the form.
$(document).ready(function(){
$('#subject_id').change(function() {
$(this.form).submit();
});
$('#choose_subject').submit(function(event) {
event.preventDefault();
var subject_id = $('#subject_id').val();
if (subject_id) {
$.ajax(...);
}
});
});
This way your submit button should work in case it is clicked.
There are a few things you need to look at:
1) Is your SimpleTemplate library included?
2) Have you compiled your template via compileTemplate()?
Once you know your library is included (check console for errors), pass your data returned to your success handler method, compile your template, that update whichever element you are trying to update.
I'm not sure that you want to update the same element that you're defining your template in.
$(document).ready(function(){
$('#subject_id').change(function(){
var subject_id = $(this).val();
$.ajax({
url : "subject_ajax?subject_id=" + subject_id,
success : function(data) {
var template_data = JSON.parse(data);
var template = $('#subject_id').toString(); // reference to your template
var precompiledTemplate = compileTemplate(template);
var result = precompiledTemplate(template_data);
$('#subject_id').append(result);
},
error : function() {
alert("Error");
}
});
})
})
You might also try moving your template out of the element you're trying to update like this:
<script type="text/template" id="subject-select-template">
% for subject in subjects:
<option value="{{subject.id}}">{{subject.name}}</option>
% end
</script>
Then just create a blank select element like so:
<select id="select_id"></select>
Update references. Anyway, hope this is helpful. It should work but I can't test without your specific code ;)
Also, check out this demo example if you haven't yet:
https://rawgithub.com/snoguchi/simple-template.js/master/test/test.html