flask ajax/jquery form submission - javascript

So I have this code below.
This is my jquery/ajax script
$(function() {
$(".reply").click(function(){
var id = $(this).attr("id");
var element = ".comment_replies#" + id;
$(element).show();
$(".submit_reply#" + id).click( function(event) {
event.preventDefault();
var reply_box = ".reply_box#" + id
var data = $(reply_box).val
$.ajax({
type : "POST",
url : "{{url_for('main.HomePage')}}",
data: JSON.stringify(data, null, '\t'),
contentType: 'application/json;charset=UTF-8',
success: function(result) {
console.log(result);
console.log(data)}
})
})
})
})
here is the form:
<form class = "reply_form" action="#" method="post">
<input class = "reply_box" type="text" placeholder ="write a reply" name="reply" id = "{{'id_' +com.id|string}}">
<input type="submit" class = "submit_reply" value = "reply" id = "{{'id_' +com.id|string}}">
<input type="hidden" value="{{com.id}}" name = "form_id">
</form>
and if I do:
if request.json["data"] in my HomePage view it somehow doesn't pass
because usually i'd just go if request.form when submitting the form the usual way. here is my homepage view
if request.json["data"] and request.method == "POST":
return request.json["data"]
it's only a test to see if it return what I want it too and it fails.
am I suppose to have extra imports for json? because I don't have any.
I also see this error on firebug:
POST http://127.0.0.1:5000/homepage
400 BAD REQUEST
11ms
I could submit the form the usual way but I wanna try submitting the form and appending the info without a page refresh.

Related

How to submit a form and get some text in return using Ajax

This is my Fiddle code:
$("form.signupform").submit(function(e) {
e.preventDefault();
var data = $(this).serialize();
var url = $(this).attr("action");
var form = $(this); // Add this line
$.post(url, data, function(data) {
$(form).children(".signupresult").html(data.signupresult);
$(form).children(".signupresult").css("opacity", "1");
});
return false;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<form class="signupform" method="post" action="admin/signupinsert.php">
<p class="signupresult"></p>
<input type="text" name="firstname" />
<input type="submit" value="Sign Up"/>
</form>
Signupinsert.php page code:
// Code to insert data into Database
$signupresult = "Some value here";
$response = new \stdClass();
$response->signupresult = $signupresult;
header('Content-Type: application/json');
print json_encode($response);
Expected Result:
When user clicks on submit form button, the code runs in background. And submits the form without reloading the page.
And the signupinsert.php page return some text, and its text display on a paragraph with class signupresult.
And the form can be submitted unlimited times, without reloading the page.
Problem:
The form only gets submitted once. If I try to submit it twice, "Nothing Happens" (No values inserted into database, no value returned in paragraph with class signupresult.
Where is the problem?
You have to tell your request that you expect JSON as return. Else data.signupresult doesn't make sense; data is seen as a string.
I always use $.ajax, never $.post; I find it easier to add options.
$.ajax({
url: $(this).attr("action"),
dataType: 'JSON',
type: 'post',
data: $(this).serialize(),
success: function(data) {
...
}
})

Ajax form set textbox value onsubmit

after submit the form using ajax i cant set the value on the multiple textbox correctly, here's my form
<form id="searchForm" action="process.php" method="post">
<input id="cust_code" name="cust_code" required>
<input id="cust_code1" name="cust_code1" disabled>
<input id="cust_name" name="cust_name" disabled>
<button type="submit">Search</button>
</form>
process.php
$cust_code = $_POST['cust_code'];
$result = mysql_query("SELECT code,cust_name FROM information WHERE code=$cust_code") or die(mysql_error());
$data = mysql_fetch_array($result);
javascript:
var formData = {
'cust_code': $('#cust_code').val()
};
$.ajax({
type : 'POST',
url : 'process.php',
data : formData,
dataType : 'json',
encode : true,
success: function(data) // recieved data from process.php
{
var code = data[0];
var cust_name = data[1];
// Update id value
document.getElementById('cust_code').value = code;
document.getElementById('cust_code1').value = code;
document.getElementById('cust_name').value = cust_name;
}
})
the value of cust_code and cust_code1 changed after submit, but not for cust_name
any ideas?
EDIT: the id's has been use on another page(php include) so that make the input wont change, solved!
You can assign value by this way also in JQuery:
document.getElementById('cust_code').val(code);
or
document.getElementById('cust_code').attr('value',code);
The same IDs have been used on another page(php include) so the input value won't change, changing the ID to cust_names seems to do the trick

add comment using ajax(from form)

I want to add comment using ajax. But i faced a problem, that ajax doesn't work. I put alert into success:, but it doesn't go into success function.
$(document).ready(function()
{
$("#comment_form").submit(function(e){
e.preventDefault();
var url_ = "http://127.0.0.1:8000/articles/addcomment/" + "1" + '/';
$.ajax({
url: url_,
type: "post",
success: function(result){
alert(result);
}
});
});
});
Here is my form:
<form action="/articles/addcomment/1/" method="post" id = "comment_form">
<input type = "text" name="commentText" id = "commentText">
<input type="submit" class="button" value="Добавить комментарий" id = "add_comment">
</form>
Console error:
jquery.min.js:5 POST 127.0.0.1:8000/articles/addcomment/1 403 (FORBIDDEN)

Pass view as data to js in symfony

I am tryng to implement a search function in my index page using java script. I hav got a form to enter the name and when apply serach, the index page will get updated and load the new index page with the search results
Here is the form in my index page
<div id="content">
<form id="myForm" action="{{path('index_search')}}" method="POST" >
Write your name here:
<input type="text" name="name" id="name_id" value="" /><br />
<input type="submit" value="Send" />
</form>
</div>
<div id="output">#current index</div>
Here is the action exexcuted
public function searchAction()
{
$request = $this->get('request');
$name=$request->request->get('formName');
$em = $this->getDoctrine()->getManager();
$entities = $em->getRepository('SystemVmsBundle:VisitorsDetails')->findOneByfirstname($name);
$view = $this->render('SystemVmsBundle:VisitorsDetails:index.html.twig',array(
'entities' => $entities,
));
$return=array("responseCode"=>200, "view"=>$view);
$return=json_encode($return);//jscon encode the array
return new Response($return,200,array('Content-Type'=>'application/json'));
}
Here is the js
$(document).ready(function() {
//listen for the form beeing submitted
$("#myForm").submit(function(){
//get the url for the form
var url=$("#myForm").attr("action");
$.post(url,{
formName:$("#name_id").val(),
other:"attributes"
},function(data){
//the response is in the data variable
if(data.responseCode==200 ){
$('#output').html(data.view);
$('#output').css("color","red");
}
else{
alert("An unexpeded error occured.");
}
});
return false;
});
});
However my js is working,but can not pass data as view to the js.How to pass the view 'index.html.twig' to the js?
When inspects with firebug,i got like
{"responseCode":200,"view":{"headers":{}}}
Any ideas?Thanks in advance!
Try to specify the dataType on your $.post function, like this:
$.post(url, {formName: $("#name_id").val(), other: "attributes"},
function(data) {
if(data.responseCode == 200){
$('#output')
.html(data.view)
.css("color","red");
} else {
alert("An unexpeded error occured.");
}
}, 'json');
But If you only need the html, not other data inside the json, you should change the logic, render a normal template and use dataType 'html'. goes like this:
// ...Controller.php
$view = $this->render('SystemVmsBundle:VisitorsDetails:index.html.twig',array(
'entities' => $entities,
));
return new Response($view);
// index.html.twig
$.ajax({
url: url,
dataType: 'html',
type: 'POST',
data: {formName: $("#name_id").val(), other:"attributes"},
success: function (data) {
$('#output').html(data).css("color","red");
}
});

submit the form using ajax

I'm developing an application (a kind of social network for my university). I need to add a comment (insert a row in a specific database). To do this, I have a HTML form in my html page with various fields. At time of submit I don't use the action of form but i use a custom javascript function to elaborate some data before submitting form.
function sendMyComment() {
var oForm = document.forms['addComment'];
var input_video_id = document.createElement("input");
var input_video_time = document.createElement("input");
input_video_id.setAttribute("type", "hidden");
input_video_id.setAttribute("name", "video_id");
input_video_id.setAttribute("id", "video_id");
input_video_id.setAttribute("value", document.getElementById('video_id').innerHTML);
input_video_time.setAttribute("type", "hidden");
input_video_time.setAttribute("name", "video_time");
input_video_time.setAttribute("id", "video_time");
input_video_time.setAttribute("value", document.getElementById('time').innerHTML);
oForm.appendChild(input_video_id);
oForm.appendChild(input_video_time);
document.forms['addComment'].submit();
}
The last line submits the form to the correct page. It works fine. But I'd like to use ajax for submitting the form and I have no idea how to do this because I have no idea how to catch the form input values. anyone can help me?
Nobody has actually given a pure javascript answer (as requested by OP), so here it is:
function postAsync(url2get, sendstr) {
var req;
if (window.XMLHttpRequest) {
req = new XMLHttpRequest();
} else if (window.ActiveXObject) {
req = new ActiveXObject("Microsoft.XMLHTTP");
}
if (req != undefined) {
// req.overrideMimeType("application/json"); // if request result is JSON
try {
req.open("POST", url2get, false); // 3rd param is whether "async"
}
catch(err) {
alert("couldnt complete request. Is JS enabled for that domain?\\n\\n" + err.message);
return false;
}
req.send(sendstr); // param string only used for POST
if (req.readyState == 4) { // only if req is "loaded"
if (req.status == 200) // only if "OK"
{ return req.responseText ; }
else { return "XHR error: " + req.status +" "+req.statusText; }
}
}
alert("req for getAsync is undefined");
}
var var_str = "var1=" + var1 + "&var2=" + var2;
var ret = postAsync(url, var_str) ;
// hint: encodeURIComponent()
if (ret.match(/^XHR error/)) {
console.log(ret);
return;
}
In your case:
var var_str = "video_time=" + document.getElementById('video_time').value
+ "&video_id=" + document.getElementById('video_id').value;
What about
$.ajax({
type: 'POST',
url: $("form").attr("action"),
data: $("form").serialize(),
//or your custom data either as object {foo: "bar", ...} or foo=bar&...
success: function(response) { ... },
});
You can catch form input values using FormData and send them by fetch
fetch(form.action,{method:'post', body: new FormData(form)});
function send(e,form) {
fetch(form.action,{method:'post', body: new FormData(form)});
console.log('We send post asynchronously (AJAX)');
e.preventDefault();
}
<form method="POST" action="myapi/send" onsubmit="send(event,this)">
<input hidden name="crsfToken" value="a1e24s1">
<input name="email" value="a#b.com">
<input name="phone" value="123-456-789">
<input type="submit">
</form>
Look on chrome console>network before 'submit'
You can add an onclick function to your submit button, but you won't be able to submit your function by pressing enter. For my part, I use this:
<form action="" method="post" onsubmit="your_ajax_function(); return false;">
Your Name <br/>
<input type="text" name="name" id="name" />
<br/>
<input type="submit" id="submit" value="Submit" />
</form>
Hope it helps.
Here is a universal solution that iterates through every field in form and creates the request string automatically. It is using new fetch API. Automatically reads form attributes: method and action and grabs all fields inside the form. Support single-dimension array fields, like emails[]. Could serve as universal solution to manage easily many (perhaps dynamic) forms with single source of truth - html.
document.querySelector('.ajax-form').addEventListener('submit', function(e) {
e.preventDefault();
let formData = new FormData(this);
let parsedData = {};
for(let name of formData) {
if (typeof(parsedData[name[0]]) == "undefined") {
let tempdata = formData.getAll(name[0]);
if (tempdata.length > 1) {
parsedData[name[0]] = tempdata;
} else {
parsedData[name[0]] = tempdata[0];
}
}
}
let options = {};
switch (this.method.toLowerCase()) {
case 'post':
options.body = JSON.stringify(parsedData);
case 'get':
options.method = this.method;
options.headers = {'Content-Type': 'application/json'};
break;
}
fetch(this.action, options).then(r => r.json()).then(data => {
console.log(data);
});
});
<form method="POST" action="some/url">
<input name="emails[]">
<input name="emails[]">
<input name="emails[]">
<input name="name">
<input name="phone">
</form>
It's much easier to just use jQuery, since this is just a task for university and you do not need to save code.
So, your code will look like:
function sendMyComment() {
$('#addComment').append('<input type="hidden" name="video_id" id="video_id" value="' + $('#video_id').text() + '"/><input type="hidden" name="video_time" id="video_time" value="' + $('#time').text() +'"/>');
$.ajax({
type: 'POST',
url: $('#addComment').attr('action'),
data: $('form').serialize(),
success: function(response) { ... },
});
}
I would suggest to use jquery for this type of requirement . Give this a try
<div id="commentList"></div>
<div id="addCommentContainer">
<p>Add a Comment</p> <br/> <br/>
<form id="addCommentForm" method="post" action="">
<div>
Your Name <br/>
<input type="text" name="name" id="name" />
<br/> <br/>
Comment Body <br/>
<textarea name="body" id="body" cols="20" rows="5"></textarea>
<input type="submit" id="submit" value="Submit" />
</div>
</form>
</div>​
$(document).ready(function(){
/* The following code is executed once the DOM is loaded */
/* This flag will prevent multiple comment submits: */
var working = false;
$("#submit").click(function(){
$.ajax({
type: 'POST',
url: "mysubmitpage.php",
data: $('#addCommentForm').serialize(),
success: function(response) {
alert("Submitted comment");
$("#commentList").append("Name:" + $("#name").val() + "<br/>comment:" + $("#body").val());
},
error: function() {
//$("#commentList").append($("#name").val() + "<br/>" + $("#body").val());
alert("There was an error submitting comment");
}
});
});
});​
I would like to add a new pure javascript way to do this, which in my opinion is much cleaner, by using the fetch() API. This a modern way to implements network requests. In your case, since you already have a form element we can simply use it to build our request.
const formInputs = oForm.getElementsByTagName("input");
let formData = new FormData();
for (let input of formInputs) {
formData.append(input.name, input.value);
}
fetch(oForm.action,
{
method: oForm.method,
body: formData
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.log(error.message))
.finally(() => console.log("Done"));
As you can see it is very clean and much less verbose to use than XMLHttpRequest.

Categories