Post form using AJAX in Django - ajax

I'm trying to POST form in Django using Ajax. I've already done this way before but now i cant find whats wrong with my code. When submitting the form, ajax POST's to wrong URL even though i've provided the right URL. I want to post to "/upload/videoUpload/" but it keeps on posting to "/upload".Below is the code.
HTML:
<form id="videouploadForm" method="POST" >
{% csrf_token %}
<input type="text" id="vidlc" name="video" value="submit" style="display: none" >
<input type="submit" id="sBm120" style="display: none"/>
</form>
AJAX:
<script>
$('#sBm120').trigger('click');
$(document).ready(function() {
$("#videouploadForm").submit(function(event){
event.preventDefault();
$.ajax({
method:"POST",
url:"/upload/videoUpload/",
data: {
'video': $('#vidlc').val(),
'csrfmiddlewaretoken': $('input[name=csrfmiddlewaretoken]').val()
},
success: function(data){
if (data.status){
alert(data.status);
var result = " <video poster='{% static 'images/single-video.png' %}' style='height:30vh' controls='controls' width='100%' height='30%'><source src='http://gateway.ipfs.io/ipfs/"+data.filehash+"' type='video/mp4; codecs='avc1.42E01E, mp4a.40.2'></video>";
document.getElementById("upv").innerHTML=result;
}
}
});
return false; //<---- move it here
});
});
</script>
URLS.py:
path('upload/videoUpload/', uploadVid, name="uploadVideo"),

have you tried to use Django url template tags?
url:"/upload/videoUpload/", to
url:" '{% url " uploadVideo" %} ",
Hope it works!
Sorry if you dont see properly, writing from my phone :)

Related

Posting form using AJAX

can anyone please help me with sending the below form using Ajax. All I want is to send it to the trolley1.php page for processing, no call backs or anything like that. Basically replicate the form but sending it with Ajax so the page does not go to the trolley1.php page. I have tried so many methods but have not been able to do this. Bill Gates or Steve Wozniak if you guys are reading this, please help
This gives me a console $.Ajax is not a function in the console
<script>
$(document).ready(function(){
$('form').submit(function(event){
event.preventDefault();
var form_data = $(this).serialize();
$.ajax({
url: "trolley1.php",
type: "POST",
dataType:"json",
data: form_data
}).done(function(data){
alert("Item added to Cart!");
}
});
});
</script>
<?php
echo "
<div class='col-sm-3 mt-5'>
<form class='ajax' method='post' action='trolley1.php?action=add&id=$id'>
<div class='products'>
<a>$img</a>
<input type='hidden' name='id' value='$id'/>
<input type='hidden' name='name' value='$product'/>
<input type='hidden' name='price' value='$price'/>
<input type='text' name='quantity' class='form-control' value='1'/>
<input type='submit' name='submit' style='margin-top:5px;' class='btn btn-info'
value='Add to Cart'/>
</div>
</form>
You have one syntax error in your JS Code - see correct code
$(document).ready(function(){
$('form').submit(function(event){
event.preventDefault();
var form_data = $(this).serialize();
$.ajax({
url: "trolley1.php",
type: "POST",
dataType:"json",
data: form_data
}).done(function(data){
alert("Item added to Cart!");
});
});
});
And you are using jQuery as additional javascript libary. jQuery uses $ to access the methods (e.g. $.ajax) Thats the reason why you get undefined as error.
So you need to load the libary first at the beginning of your page (inside <head>). E.g. directly from their CDN
<script src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>
Then it should work for you

Uploading photo Spring - Ajax

I am trying to upload a photo and get a preview of the uploaded image using Spring and Ajax.
I have the following code:
<h3>File Upload</h3>
<ul>
<li>
<form id="upload-form" method="post" enctype="multipart/form-data">
Select a file: <input type="file" name="uploadfile" size="45" accept="*" />
<br>
<input id="submit-button" type="submit" value="Upload" />
</form>
</li>
<li><p>Result: <br><span id="result"></span></p></li>
</ul>
<h3>Show Image</h3>
<ui>
<li>original:<img id="image-o" src="#" alt="original image" /></li>
<li>small: <img id="image-s" src="#" alt="small image" /></li>
<li>medium: <img id="image-m" src="#" alt="medium image" /></li>
<li>large: <img id="image-l" src="#" alt="large image" /></li>
<li>extra large: <img id="image-xl" src="#" alt="extra large image" /></li>
</ui>
<script type="text/javascript">
$(document).ready(function () {
$("#submit-button").on("click", function (event) {
event.preventDefault();
// create an FormData object
var data = new FormData($('#upload-form')[0]);
// disabled the submit button
$("#submit-button").prop("disabled", true);
// post data
$.ajax({
type: "POST",
enctype: 'multipart/form-data',
url: "image/api/upload",
data: data,
processData: false,
contentType: false,
cache: false,
timeout: 600000,
success: function (data) {
// shows server's response
// $("#result").text(data);
console.log("SUCCESS: ", data);
enableSubmitButton();
updateImages(data);
},
error: function (e) {
// shows server's response
// $("#result").text(e.responseText);
console.log("ERROR: ", e);
enableSubmitButton();
updateImages(e.responseText);
}
});
});
});
function enableSubmitButton() {
$("#submit-button").prop("disabled", false);
}
function updateImages(data) {
var url = 'http://localhost:9001/image/api/' + data;
$('#image-s').attr('src',url + '?size=s');
$('#image-m').attr('src',url + '?size=m');
$('#image-l').attr('src',url + '?size=l');
$('#image-xl').attr('src',url + '?size=xl');
$('#image-o').attr('src',url + '?size=o');
}
</script>
And my Java code:
#POST
#Path("/upload")
#Consumes(ExtendedMediaType.MULTIPART_FORM_DATA)
#Produces(ExtendedMediaType.APPLICATION_JSON_UTF8)
#Transactional
public ResponseEntity<Void> uploadImage(#RequestParam("uploadfile") MultipartFile file) {
if (file.getSize() < maxFileSize && validExtensions.contains(file.getContentType())) {
Image image = Image.builder().id(file.getSize()).build();
imageServiceConfigMapper.saveImage(image);
/* FormDataContentDisposition fileDetail = null;
ImageMetadata imageMetadata = buildImageMetadata(fileDetail, image);
imageServiceConfigMapper.saveMetadata(imageMetadata);*/
}
return new ResponseEntity<>(HttpStatus.OK);
When I choose a photo from my PC, it is accepted - see screenshot below:
When I click in upload, my browser gives the following answer:
The JSON looks like this:
BUT the selected picture is not showing:
Am I using a wrong URL?
The address of the site where I got the above screen ends is the one with index.html at the end, but I defined /api/upload as a relative path...
If I open the relative path, I got the following:
Or is it something wrong with the code responsible for the preview?
Sorry, I know there is a tones of similar issues but I could not found anything that hepled. I am quite a beginner...
Sorry for the long post and thanks for the help in advance!
Spring Content can do this and has a getting started guide and git repo with an angularjs based front-end that demonstrates exactly what you are trying to do. The getting started guide is here.

Dynamic Django forms

I want to create dropdown list in django forms.
One way is to get the options and pass it to the template from views.py
Other way is via forms.py but i'm not sure how to do that.Although the code to do that is available,it's not usable for me as i want to generate options depending on the user that it logged in(that means using request parameter).Can you suggest how to do that?
The first method of passing via views.py works to the extent of generating a dropdown but i'm not able to get the value of selected option from request.It gives a null value.
Here's my code:
Template
<script type="text/javascript">
$(document).ready(function() {
$('#remove_form').submit(function() { // catch the form's submit event
$.ajax({ // create an AJAX call...
data: $(this).serialize(), // get the form data
type: $(this).attr('method'), // GET or POST
url: '/remove/', // the file to call
success: function(response) { // on success..
$('#test').html("<p style='color:green;margin-left:40%;margin-right:40%;'>Submitted!</p>"); // update the DIV
},
error: function(e, x, r) { // on error..
$('#err').html(e); // update the DIV
}
});
return false;
});
});
</script>
......
......
<form method="POST" id="remove_form" action="">{% csrf_token %}
<select id="remove">
{% for i,p in dropdown %}
<option value="{{i}}">{{p}}</option>
{% endfor %}
</select>
{{remove|crispy}}
<input class="btn btn-primary" type="submit" value="Remove">
</form>
Also note that i'm rendering this form from one view but the data goes into another view for processing via ajax call.
<select id="remove">
The select tag takes a name attribute.
<select name="remove" id="remove">
Then your form works. http://codepen.io/C14L/pen/dMKqPE

Render template into Symfony2 with ajax

I have a action in my controller for the index route
routing.yml
index:
pattern: /index
defaults: { _controller:AcmeDemoBundle:Default:index }
Controller for this path
public function indexAction()
{
return $this->render('AcmeDemoBundle:Plugin:index.html.twig');
}
And the index.html.twig template
{% extends'::base.html.twig' %}
{% block stylesheets %}
{% stylesheets filter='cssrewrite' output='css/*.css'
'bundles/acmedemo/css/*' %}
<link href="{{ asset_url }}" type="text/css" rel="stylesheet" />
{% endstylesheets %}
{% endblock stylesheets %}
{% block body %}
<br>
<div class="container">
<div class="wp_attachment_holder">
<div class="imgedit-response" id="imgedit-response-8"></div>
<div class="wp_attachment_image" id="media-head-8">
<p id="thumbnail-head-8"><img class="thumbnail" src="http://localhost/wordpress/wp-content/uploads/2014/06/121-1024x583.jpeg" style="max-width:100%" alt=""></p>
<p><a class="btn btn-sm btn-default" id="edik-wp-extended-edit">Редактировать</a> <span class="spinner"></span></p>
</div>
<div style="display:none" class="image-editor" id="image-editor-8">
</div>
</div>
<div id="output"></div>
<img class="thumbnail" data-attach-id="8" data-src="http://localhost/wordpress/wp-content/uploads/2014/06/121-1024x583.jpeg" style="max-width:100%" alt="">
<script>
$('#edik-wp-extended-edit').click(function() {
window.location= Routing.generate('ajax');
// $('#output').load('/ajax/index');
});
</script>
</div>
{% endblock %}`
When the button Редактировать is clicked i want to load another template with ajax.
another.html.twig
<div>Hello</div>
routing.yml
ajax:
pattern: /ajax/index
defaults: { _controller :AcmeDemoBundle:Default:ajax }
options:
expose: true
Controller for this path
public function ajaxAction()
{
$template = $this->renderView('AcmeDemoBundle:Plugin:another.html.twig');
return new Response($template);
}
But when i click the button my uri will be /ajax/index. What i want is that it stays by /index and the template will be rendered into my index template
What am i doing wrong?
Thanks.
First, your ajaxAction() should be a bit different as far as I know.
For me this works:
$template = $this->forward('AcmeDemoBundle:Plugin:another.html.twig')->getContent();
$json = json_encode($template);
$response = new Response($json, 200);
$response->headers->set('Content-Type', 'application/json');
return $response;
The forward() function renders the template and returns the rendered HTML code.
Your JavaScript file should look like this:
$.ajax({
type: "POST",
dataType: 'json',
url: Routing.generate('ajax'),
async: false //you won't need that if nothing in your following code is dependend of the result
})
.done(function(response){
template = response;
$('#your_div').html(template.html); //Change the html of the div with the id = "your_div"
})
.fail(function(jqXHR, textStatus, errorThrown){
alert('Error : ' + errorThrown);
});
You make an AJAX call to the your ajaxAction, which will return the HTML of the template you want to be rendered.
After that you just need to add a <div id="your_div"></div> at the position you want the template to be rendered. This workes perfectly for me.
To mention is that you need to break down the ajax template to just the code that should be shown.
Please try generate ajax route like this
window.location= '{{ path("ajax") }}';
Added:
For make ajax request change windows.location to ajax request
$( "#output" ).load( '{{ path("ajax") }}', function() {
alert('Load done');
});
Added explanation of use:
js code will work only if you put it on Twig template. If you put it to js file it will not work.
In case of original questions.
<div id="output"></div>
<img class="thumbnail" data-attach-id="8" data-src="http://localhost/wordpress/wp-content/uploads/2014/06/121-1024x583.jpeg" style="max-width:100%" alt="">
<script>
$('#edik-wp-extended-edit').click(function() {
$( "#output" ).load('{{ path("ajax") }}');
});
</script>
You can use something like FOSJsRoutingBundle to proper use SF2 routing in js

Cross Domain Ajax Issue

I have two files
1) index.php(picks data from the code editor and submits for processing via Jquery Ajax to exec.php)
2) exec.php (currently just transfer the data it recieved via index.php using jsonp)
Code of index.php
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
function test() {
var code = document.getElementById('code').value;
var code_data = "code=" + code;
alert(code_data);
$.ajax({
type: "POST",
crossDomain: true,
url: "http://code1.guru99.com/exec.php",
data: code_data,
dataType: "jsonp",
success: function (data) {
alert(data);
}
});
alert("End of Test");
}
</script>
<form name="myform" id="myform" method="POST" class="code-box">
<textarea name="code" id="code"><?
$code='<?php
"Hello";
?>';
echo $code;
?>
</textarea> <!-- for add html tag in text area nad print the code-->
<div class="hint">This code is editable. Click Run to execute.</div>
<input type="submit" value="Run" id="submit" onClick="test();"><!--<img id="ajax-loader" name="ajax-loader" src="/img/ajax-loader.gif" class="hidden" style="vertical-align:middle" />-->
</form>
<div name="label" id="label"> </div>
<div name="out" id="out"> </div>
Code of exec.php
<?php
$code=$_POST['code'];
$fp=fopen("file.txt","w"); // Storing the data into a file just to know that data is passed
fwrite($fp,$code);
fclose($fp);
header('Content-Type: application/jsonp');
echo $_GET['callback']."(".json_encode($code).");"
?>
The problem is data just does not pass into exec.php. I am not sure why...
The code is live at http://code.guru99.com/php/
Please help...
You cannot use AJAX to do this. Instead consider posting from a hidden Iframe using a regular FORM and setting the action to the URL you desire. You can still submit the form using JavaScript.
You can also listen to the onload event on the iframe to detect when your post has completed.
Alternately, you can use a server-side proxy.
The code syntax is correct.
May the problem could be with your server

Resources