Trying to figure out why my code does not send over all POST data. The code is used on main page to get request information stored in db and used on separate page to post status updates made by me to DB. Its basically the same, except variable names.
Note: I have searched here a lot. Ive used var_dump that shows only 'content' data in the array. Im not fully comfortable with js but can follow some of it. Hence the code below is a template that Ive edited and tested on one page before trying to expand to another. Thats where the issue is. I am not sure why it works for one and not the other. Apologies if this is considered duplicate of anything, but I didnt find a good answer in similar post that would explain why.
admin.php:
<form action="insert.php" method="post" enctype="multipart/form-data">
<div class="share">
<div class="arrow"></div>
<div class="panel panel-default">
<div class="panel-body">
<div class="">
<img src="../logo.png" style="height:60px; width:60px; float:left; margin-right:3px;" />
<textarea name="content1" id="content1" cols="40" rows="10" class="form-control message" style="height: 60px; width:450px; overflow: hidden;"></textarea>
</div>
</div>
<div class="panel-footer">
<div class="row">
<div class="col-md-7">
<div class="form-group">
<div class="btn-group">
<select name="avatar" id="avatar" class="form-control-issue-avatar"> <----whats not sending
<option value="0" selected="selected">Author</option>
<option value="per1">P</option>
<option value="per2">W</option>
</select>
</div>
</div>
</div>
<div class="col-md-5">
<input type="submit" value="Post" class="post_button">
</div>
</div>
</div>
</div>
</form>
Here is the insert.php:
if(isSet($_POST['content1'], $_POST['avatar']))
{
$content1=$_POST['content1'];
$avatar=$_POST['avatar']; // <--- comes back NULL
$sql_in= mysqli_query($con,"SELECT comment,comment_id,status_time FROM comments order by comment_id desc");
$r=mysqli_fetch_array($sql_in);
}
and lastly the post.js that calls it:
$(function() {
$(".post_button").click(function() {
var element = $(this);
var test = $("#content1").val();
var dataString = 'content1='+ test;
if(test=='')
{
alert("Please Enter Some Text");
}
else
{
$("#flash").show();
$("#flash").fadeIn(400).html('<span class="loading">Loading Comment...</span>');
$.ajax({
type: "POST",
url: "insert.php",
data: dataString,
cache: false,
success: function(html){
$("#display").after(html);
document.getElementById('content1').value='';
$("#flash").hide();
}
});
}
return false;
});
});
the var_dump etc:
Array ( [content1] => sass )
C:\wamp64\www\post\insert.php:32:
array (size=1)
'content1' => string 'sass' (length=4)
Add id attribute to the form and then use serialize() on the form to get all data from the form to pass via ajax to php
<form id='formid'>
$.ajax({
data: $('#formid').serialize(),
//other Ajax stuff
});
Related
I am trying to insert some HTML before a divider class="replydivider" using insertBefore() but I can't get it to work. This is my code:
<div class="col-sm-12 mb-2 replydivider">
<div class="row">
<div class="col-sm-2 offset-1">
<img src="/assets/uploads/user/<?=$_SESSION['userImage'];?>" class="border rounded-circle comment-user-img mr-3">
</div>
<div class="col-sm-8 rounded form-inline">
<form method="POST" class="form-group reply-form">
<input type="text" name="comment" class="form-control mr-2" placeholder="Reply here" required>
<input type="hidden" name="postId" value="<?=$id?>">
<input type ="hidden" name="replyId" value="<?=$row['commentId'];?>">
<input type="submit" class="btn-sm btn-primary" value="Reply">
</form>
</div>
</div>
</div>
The issue I'm having is it has to be inserted before the div relative to the form that is submitted as there will be many replydividers and forms on the page.
I've tried the following and countless variations but can't get it to work:
$(this).closest('.replydivider').before(data);
$(this).closest('div').find(".replydivider").before(data);
$(this).closest('form').find(".replydivider").before(data);
$(data).insertBefore('.replydivider');
Any guidance would be appreciated.
EDIT:
This is my jquery function:
$(function () {
$('.reply-form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: '/comment/addComment',
data: $(this).serialize(),
success: function (data) {
alert('test');
var test = "<p>Sample data</p>";
$(this).closest('.replydivider').before(test);
}
});
$(this).closest('form').find("input[type=text]").val("");
});
});
Interestingly, if I put the $(this).closest('.replydivider').before(test); line outside the ajax call it works, but not inside it. I put the alert there to test it was returning successful and it is.
.ajax()
The this reference within all callbacks is the object in the context option passed to $.ajax in the settings; if context is not specified, this is a reference to the Ajax settings themselves.
If you want this in the callbacks to be the element that received the event then set the context property of Ajax like:
.......
context:this,
success: function (data) {
.......
I'm learning javascript/jquery on the go, I'm trying to reload a form but keeping its js properties (required and masked inputs), code and pictures attached.
First image: Masked inputs works like a charm
Second image: The form its fully filled, still working
Third image: The form it reloaded, but no properties applied
The html form (minmized, just the first field)
<div class="card-body" id="clientsAddFormContainer">
<form method="post" action="main/clients/addController.php">
<div class="form-group row" id="clientRutDiv">
<div class="col-lg-6">
<div class="form-group" id="clientRutInnerDiv">
<label class="col-form-label" for="clientRut">RUT <span class="required">*</span></label>
<input type="text" name="clientRut" id="clientRut" class="form-control" placeholder="Ej. 11.111.111-1" required="" data-plugin-masked-input="" data-input-mask="99.999.999-*" autofocus>
</div>
</div>
</div>
</div>
</form>
<footer class="card-footer">
<div class="switch switch-sm switch-primary">
<input type="checkbox" name="wannaStay" id="wannaStay" data-plugin-ios-switch checked="checked" />
</div> Mantenerme en esta página
<button type="button" style="float: right;" class="btn btn-primary" onclick="realizaProceso();">Enviar</button>
</footer>
The JS for realizaProceso()
function realizaProceso(){
var validator =0;
validator += validateRequiredField('clientRut');
if(validator == 0){
var parametros = {
"clientRut" : document.getElementById('clientRut').value,
"tableName" : 'clients'
};
$.ajax({
data: parametros,
url: 'route/to/addController.php',
type: 'post',
success: function (respText) {
if(respText == 1){
if(document.getElementById('wannaStay').checked){
$("#clientsAddFormContainer").load(location.href + " #clientsAddFormContainer");
}else{
window.location = "linkToOtherLocation";
}
}else{
showNotyErrorMsg();
}
},
error: function () {
showNotyErrorMsg();
}
});
}else{
showNotyValidationErrorMsg();
}
}
So my JS check all fields are validated, then prepare the array, and wait for the php binary response, 1 means the data has been inserted to db, if wannaStay is checked reload the div "clientsAddFormContainer" but as I said, it loose the properties.
Please sorry for my grammar or any other related english trouble, not a native english speaker.
Ps. I've removed some code so it could go different than the images.
Thanks in advance!
EDIT!
The original code is
<div class="card-body" id="clientsAddFormContainer">
<form method="post" action="main/clients/addController.php">
</form>
</div>
one the js exec I got
<div class="card-body" id="clientsAddFormContainer">
<div class="card-body" id="clientsAddFormContainer">
<form method="post" action="main/clients/addController.php">
</form>
</div>
</div>
2nd EDIT
I found the answer in other stackoverflow question
EDIT: Changed the HTML form statement to work like so:
<form action="." class="form-horizontal" id="groupinfoForm" onsubmit="SubmitToServer()" method="post">
Question: Do i still also need the method="post">
Also changed the javascript to work with the onsubmit:
function SubmitToServer() {
event.preventDefault();
//some ajaxy goodness here... still working on this.
$.ajax({
data: $("#groupinfoForm").serialize(),
success: function(resp){
alert ("resp: "+resp.name);
}
})
//I thinK i have to change all this to work inside the .ajax call?
formData = $('form').serializeArray()
$('#group_info option:first').prop('selected',true);
gid = $('#group_info option:selected').val()
//test alert
alert("Submitting data for provider: " + $("#provider_id").val() + " and " + gid + " and " + formData[0]['date_joined']);
$("#groupinfo-dialog").modal('hide');
}
I have a form, that is standard django. Fill it out send it off goes to a different page upon success..shows errors if you don't fill out portions.
Now I have a modal form that will pop up to fill out some extra data. I have decided to try to my hand at ajax for this. I have some of it working:
Inside the class that is an UpdateView:
def post(self, request, *args, **kwargs):
if self.request.POST.has_key('group_info_submit') and request.is_ajax():
print("YOU SURE DID SUBMIT")
return HttpResponse("hi ya!")
The problem is it always redirects to a different page, and fails validation anyway because the form the modal pops over is not complete and trying to be submitted.
I saw this post here:
Ajax Form Submit to Partial View
This seems overly complicated, I just have a small div in my form that is a modal div that I would like to submit sort of separately from the rest... The java script I have in the code:
$.ajax({
data: $("#groupinfoForm").serialize(),
success: function(resp){
alert ("resp: "+resp.name);
}
})
Then the little modal html snippet is:
<div class="container">
<div id="groupinfo-dialog" class="modal" title="Group Information" style="display:none">
<div class="modal-dialog">
<h1> Group Information </h1>
<div class="modal-content">
<div class="modal-body">
<form action="." class="form-horizontal" id="groupinfoForm" method="post">
{% csrf_token %}
{{ group_information_form.non_field_errors }}
<div class="col-md-12">
{{ group_information_form.date_joined_group.errors }}
{{ group_information_form.date_joined_group.label_tag }}
{{ group_information_form.date_joined_group }}
</div>
<div class="col-md-12">
{{ group_information_form.provider_contact.errors }}
{{ group_information_form.provider_contact.label_tag }}
{{ group_information_form.provider_contact }}
</div>
<div class="col-md-12">
{{ group_information_form.credentialing_contact.errors }}
{{ group_information_form.credentialing_contact.label_tag }}
{{ group_information_form.credentialing_contact }}
</div>
<div class="col-md-12">
<div class="col-md-3">
</div>
<div class="col-md-8 form-actions">
<input type='button' class='btn' onclick="CancelDialog()" value='Cancel'/>
<input type='submit' class='btn btn-success' onclick="SubmitToServer()" value='Save' name='group_info_submit'/>
</div>
<div class="col-md-1">
</div>
</div>
<input type="hidden" id="provider_id" name="provider_id" value="{{ provider_id }}" />
<input type="hidden" id="group_id" name="group_id" value="{{ group_id }}" />
</form>
</div>
</div>
</div>
</div>
</div> <!-- end modal Group Info Dialog -->
I do have a model form on the backend in the forms.py here. Also note there was a SubmitToServer() call, that is where I thought I could toss all the ajax stuff over the fence to the server, but I guess I need that $.ajax? I am still learning the deeper parts of jquery. I want to do a lot of preprocessing before i submit the data. My attempt at the submittoserver javascript was here:
Wasn't sure how to get all the form data (just the three fields I care about from the modal) to send it over...my attempt here:
function SubmitToServer() {
formData = $('form').serializeArray()
$('#group_info option:first').prop('selected',true);
gid = $('#group_info option:selected').val()
alert("Submitting data for provider: " + $("#provider_id").val() + " and " + gid + " and " + formData[0]['date_joined']);
$("#groupinfo-dialog").modal('hide');
}
So can I bypass the main form validation and just send the three fields over somehow? and not have it redirect but stay on the page?
You have to intercept the submit event. add onsubmit="someFunction()" to the form. In the someFunction ajax the data you want to validate before submitting, and if all is ok return true, else false.
https://jsfiddle.net/am5f14oc/
<html>
<body>
<form onsubmit="validateFunc()" action="." method="post">
<input id="name" type="text" name="name">
<input type="submit"/>
</form>
</body>
</html>
and the javascript
function validateFunc() {
formData = $('form').serializeArray();
// do ajax or whatever and return true if everything is ok
return false;
}
I have a form with multiple data entries. Ajax (at the bottom) requires the data that is being passed to it to be bundled together. How do I take the un-submitted text in my form fields and bundle it into a JSON object to be sent to my Ajax?
<div id="editUserPinForm" class="ui raised segment signin">
<div class="cmborder">
<div class="form_heading">Edit Your Pin</div>
<form>
<div class="ui form attached fluid segment">
<div class="two fields">
<div class="field">
<label>Title</label>
<input type="text" name="pin[title]" class="ui input" value="{{pin/title}}">
</div>
<div class="field">
<label>Activity</label>
<input type="text" name="pin[activity]" class="ui input" value="{{pin/activity}}">
</div>
</div>
<div class="field">
<label>Description</label>
<textarea name="pin[description]" class="ui input">{{pin/description}}</textarea>
</div>
<div class="inline field">
<input type="hidden" name="pin[guideID]" value="{{pin/guide_id}}">
</div>
<div class="inline field">
<input type="hidden" name="pin[lat]" value="{{pin/lat}}">
</div>
<div class="inline field">
<input type="hidden" name="pin[long]" value="{{pin/long}}">
</div>
<div class="inline field">
<input type="submit" value="Submit Changes" class="ui blue submit button">
</div>
</div>
</form>
<span class='close_message' id="messageclose">×</span>
</div>
</div>
<script>
$( "#messageclose" ).on("click", function() {
$('#editUserPinForm').fadeOut();
});
$("#editUserPinForm").submit(function() {
$.ajax({
type: "PATCH",
url: "api/pins/{{pin/id}}",
contentType: 'application/json',
dataType: 'json',
data: JSON.stringify( {pin:{description:value}})
}).success: function(response){
alert(response); //response from server.
};
});
</script>
I used jQuery Serialize instead and it worked like a charm.
https://github.com/macek/jquery-serialize-object
The problem with
JSON.stringify($(this).serializeArray());
is that it converts an array into a JSON, but the array adds a "Name" and "Value" that makes the resultant JSON really hard to use.
You could use the internal jQuery $('#domNode').serializeArray() which will return an array of all the inputs in an array of objects. It follows the W3C pattern for returning the valid inputs for successful controls, meaning it will not return disabled controls.
Ref:
https://api.jquery.com/serializeArray/
http://www.w3.org/TR/html401/interact/forms.html#h-17.13.2
In order to send the form as a json string.
You have to create an array with inputs names and values pairs, by gathering every input name and value to associate them in an array of objects containing the name and value pair :
$("#editUserPinForm").submit(function() {
jQuery("#editUserPinForm").find("input").each( function()
{
var form_data = new Array(); // The array that'll contain inputs names and values
form_data.push( { $(this).attr('name') : $(this).val() } );
var form_jsoned = JSON.stringify(form_data);
// Then here you can call ajax and send the json data
$.ajax({
type: "PATCH",
url: "api/pins/{{pin/id}}",
contentType: 'application/json',
dataType: 'json',
data: form_jsoned
}).success: function(response){
alert(response); //response from server.
};
}
}
I'm currently trying to make a ajax comment function work once a user clicks "open comments".
Currently I'm getting data back from my php script and the status of the ajax call is "200 OK" so it definetely works but I'm just unable to get the correct value for the current comment which has been clicked on in order to post it to the php script.
What I'm asking is how do I get the value of the ".posted_comment_id" class and then how do I load the data which is returned into the ".commentView" class?
jQuery/AJAX:
$(".closedComment").click(function(){
var $this = $(this);
$this.hide().siblings('.openComment').show();
$this.siblings().next(".commentBox").slideToggle();
$.ajax({
type: "POST",
url: "http://example.dev/comments/get_timeline_comments",
data: {post_id: $this.siblings().next(".commentBox").find(".posted_comment_id").val()},
dataType: "text",
cache:false,
success:
function(data){
$this.closest(".commentView").load(data);
}
});
return false;
});
HTML:
<div class="interactContainer">
<div class="closedComment" style="display: none;">
open comments
</div>
<div class="openComment" style="display: block;">
close comments
</div>
<div class="commentBox floatLeft" style="display: block;">
<form action="http://example.com/comments/post_comment" method="post" accept-charset="utf-8">
<textarea name="comment" class="inputField"></textarea>
<input type="hidden" name="post" value="13">
<input type="hidden" name="from" value="5">
<input type="hidden" name="to" value="3">
<input type="submit" name="submit" class="submitButton">
</form>
<div class="commentView"></div>
<div class="posted_comment_id" style="display:none;">13</div>
</div>
</div>
Replace .val by .html or .text. This will return the innerHTML of the element.
data: {
post_id: $this.siblings().next(".commentBox").find(".posted_comment_id").text()
}
You might need to convert the string to an integer to make it work.
If the query selector fails, this selector might do the job instead:
$this.parent().find(".posted_comment_id")
To add the returned data on your webpage, use the success handler. Here's an example of how it's done:
success: function(json) {
// Parse your data here. I don't know what you get back, I assume JSON
var data = JSON.parse(json),
content = data.whatever_you_want_to_print;
// Assuming your selector works, you put in in the element using .html
$this.closest(".commentView").html(content);
}
});
You probably want to do something like:
$(this).parents('.interactContainer').find(".posted_comment_id").text()