I have a form on form-window, and inside form window I have a form with many fields and one upload button. When try to submit form using Ajax.request I have got textfield value but can not get file data. Except filename.
var fd = Ext.getCmp('users-form').form;
var fileInput = document.getElementById('company_logo');
console.log(fd.getEl().dom.files);
params = {
name : fd.findField('name').getValue(),
login : fd.findField('login').getValue(),
email : fd.findField('email').getValue(),
password : fd.findField('password').getValue(),
password_repeat : fd.findField('password_repeat').getValue(),
id : fd.findField('id').getValue()
company_logo : fd.findField('logo').getValue()
}
console.log(params);
Ext.Ajax.request({
url: Scada.reqUrl('users', 'save'),
method: 'post',
params: {
data: Ext.encode(params)
},
success: function() {
console.log('in success');
},
failure: function() {
console.log('in failure');
}
});
Here logo is input type file. I want to send logo data with ajax request. Please help me to figure out the problem. Thanks
Not sure why you started a new question instead of editing Encode form data while fileupload true in Extjs Form Submit as this seems to be the same problem.
Assuming logo is your file upload field you are trying to get the file data using getValue does not actually return the file content (if you use modern there is a getFiles method which returns the selected file objects).
General problems with your approach:
As I stated in my original answer it is not a good idea to send files in a standard ajax request. In your case those problems are:
If you expect getValue to return file contents, you are potentially encoding binary data into a JSON string. This will maybe work but create a large overhead and as the only available JSON datatype that could handle this content is string your parser would have to guess that property company_logo contains binary data and needs to be somehow converted into some sort of file reference.
You are sending files without metadata, so when just adding the raw content into your JSON string you would not be able to detect the expected file type without testing the file in multiple ways
As far as I know you would not be able to access the file content in classic toolkit at all
Submitting the data as a form: In your original question you explained that you submit the form instead of doing Ajax requests which is generally the preferred way.
When you submit a form that contains a file upload field the form will automatically be submitted as multipart/form-data the raw files are added to the request body with it's original content while preserving metadata collected by the browser.
If you look at https://docs.sencha.com/extjs/7.0.0/modern/Ext.Ajax.html#method-request you would have to set isUpload to true and use the form proeprty instead of params, passing a reference to the parent form.
rookie here. I've searched and searched and still remain ignorant.
I am making an array of markers/info windows for a Google Maps API. Currently, I have succeeded in loading my markers from an external JSON file. JSON data looks like this: https://codedump.io/share/5XUwRzOFvREi/1/json-array
pathway ./json/Markers
{"Markers": [
{
"title" : "Meow Monestary",
"position" : {
"lat" : 40.5178,
"lng" : -122.6438
},
"posterContact" : {
"name" : "Mr Meowser",
"email" : "MrMeow#Couch.com",
"phone" : "(555)-202-3040",
"private" : true
},
"type" : "myResidence",
"ownerContact" : {
"name" : false,
"email" : false,
"phone" : false,
"private" : true
},
"description" : "Meow meow purrrrr. Dogs are not my favorite but they are my second favorite.",
"private" : true
},
I want users to be able to fill out a form containing all of this data and then push the new marker object into the JSON array. So far I have collected the form, created a Javascript object, and converted it to a JSON string like this...
function submitForm(){
//place form data into array
var formData = $("#shelterForm").serializeArray();
//build the javascript object using the values in the array
var shelter = {
title:formData[0].value,
position:{
lat:formData[1].value,
lng:formData[2].value
},
posterContact:{
name:formData[3].value,
email:formData[4].value,
phone:formData[5].value,
private:formData[6].value
},
type:formData[7].value,
ownerContact:{
name:formData[8].value,
email:formData[9].value,
phone:formData[10].value,
private:formData[11].value
},
description:formData[12].value,
private:formData[13].value
};
shelterString = JSON.stringify(shelter);
}
I'm sure there was an easier way to do this. If you feel inclined to go into this... GREAT!! My main issue though is that now I have my JSON string, but can't figure out how to push it into my array. I'm thinking maybe pass the string to PHP and write to file, or possibly ajax allows this?
Whether or not you use AJAX, you will still need a script on the server to save the data server side. Doing an AJAX request is more advanced than just a regular form POST, so I would recommend against it for a beginner.
Once the data is sent to PHP, you will need to store it. The most common way this would be done is with a database, typically MySQL. When the form is posted, you would get the data from the $_POST variable and store it as a new row in the database. Then, for the JSON file, rather than using a static file, you would point the maps to a PHP script for the external JSON file. That script would then query the database, assemble the data into an associative array with code very much like your javascript submitForm() function, and then call json_encode() to convert that array into a JSON string that it would then print. On the client side, you would not need your submitForm() function anymore.
If you don't want to mess around with a database, you can use a regular file on your server and have the PHP script modify that file. It is a little messier, though, and if you have an error in your script or the server loses power while writing the file, you could lose all your data, so I would recommend also setting up a daily backup if you have important data in the file. Also, you will have to take special precaution to not allow two different people to submit their updates at the same time, since having two processes writing to the same file concurrently will cause garbage data. Databases are built to be more resilient to these problems out of the box.
If you want to go the file route, you would probably still want to move the creation of the JSON into PHP. Your javascript relies on the exact indicies of the form elements, and is hard to read and maintain. In PHP, you would have something like:
$shelter = [
'title' => $_POST['shelter_title'],
'position' => [
'lat' => $_POST['shelter_latitude'],
'lng' => $_POST['shelter_latitude']
],
The $_POST keys are the name attributes from your form elements, which makes it much easier to maintain than using index numbers, which would have to be renumbered if you added or removed a form field.
Then, you would need to lock the json file to make sure that two processes don't try to update it at the same time
if (!flock($json_filename,LOCK_EX)) {
die('We are having trouble updating our records. Please try again later.');
}
//Now nobody else can write to the file until the script finishes or calls flock($json_filename, LOCK_UN) to release the lock
Then, we load the old JSON file, and update it with our new record:
$old_json = file_get_contents($json_filename); //get JSON data as string
$old_data = json_decode($old_json); //convert JSON data into PHP array
$new_data = array_push($old_data['Markers'], $shelter); //add the new shelter to PHP array
$new_json = json_encode($new_data); //convert the PHP array back to a JSON string
file_put_contents($json_filename, $new_json); //write the string to the file
//json file is updated, so now you can display a message, or redirect the user to a new page with header('Location: foo')
I haven't tested this code, so back up your JSON before trying this.
What you should be doing here, is to have a local json file to which the google map api would be pointed to and to add to that file using the html form with a php action where you would ingest the form data and add it to the json file.
<form action="addJson.php" method="post">
addJson.php (to get the general idea)
<?php
$localFile = 'json/Markers.json';
$data = [$_POST]; // reformat if required
$existing = json_decode(file_get_contents($localFile));
$all = array_merge($existing,$data);
file_put_contents($localFile,json_encode($all));
echo 'thanks for addition';
?>
And you can totally omit the javascript submitForm function.
I have a simple web application so far that is written in php using the laravel framework.
My question is in the title: if I have a web form that has multiple SELECT elements, could somebody use javascript to append new options to that `SELECT' element and submit the form (therefore saving items that weren't suppose to options in my database?)?
As the comments have suggested, it is certainly possible to append options, or even change the values of what is being submitted.
To prevent this, you can use server side validation to check what is being passed in. Laravel provides validation out of the box that makes doing this a breeze.
The validation rule you want to use is in:
The field under validation must be included in the given list of values.
Inside your controller function that receives the request, just add this at the top to validate the request before you pass it in to your database:
$validator = Validator::make($request->all(), [
'select_input' => 'in:foo,bar',
], [
'select_input.in' => 'The option selected was not valid!',
]);
if ($validator->fails()) {
return Redirect::back()
->withErrors($validator)
->withInput();
}
You would need to add these to the top of your controller:
use Validator;
use Input;
use Redirect;
There's plenty more validation that you can utilise, just read the docs.
I'm planning on server's cherrypy with programming of python and mako.
Now i have one problem because i know to pass value of Mako template to Javascript with
<script type="text/javascript">
var contapara=${input_nparams};
</script>
and viceversa? It 's possible apply viceversa Mako<---JAvascript?
Thanks
Edit:
Because I have one variable of Mako (kwargs) that contains the data of all forms sent.
The user enters a word that is the "clave" and is stored in Javascript.
After this I pass in Mako to search in variable (kwargs).
Call the function's MAko.
After exist this I open one windows with the textarea (new form) and I have to write data.
AFter the user change data and send the form.
Make a view that takes in the arguments that you would want to send to mako, then in your javascript use ajax. for example:
jQuery.ajax(
{
url : url_of_the_mako_view,
data : {foo:bar,foo2:bar2},
type : 'POST',
success : function(data)
{
/*
when the mako template is rendered by your view then the result will
be passed to this function in the variable data
*/
}
}
)
If you are after something a little more like a page redirect then you can do something more like this:
make a form that redirects to the right place
put in a hidden field
populate the hidden field with a json string representing the arguments you want to pass to mako
submit the form
Then in the view that gets the form data you need to turn the json into a dictionary and pass that to mako
I need to send a complete form via ajax to prevent the refresh of the complete page. Since the form has a huge number of inputfields, i dont want to build the querystring manually. I found some scripts collecting all elements in the form and building the querystring automatically. But is there any easier way to build the query string automatically?
using serialize() method of your jquery form wrapper object !
see : http://api.jquery.com/serialize/
http://api.jquery.com/serialize/
http://api.jquery.com/serializearray/
Try jQuery serialize.
Example from jQuery site
$('form').submit(function() {
alert($(this).serialize());
return false;
});
You can use jQuery .serialize to serialize all input fields in the form. Try below script and alert the value,
var formValues = $('form').serialize();
alert(formValues);
you need to have the info in your page and send it in a query string to another page right??
you could simply add the Previous page Type directive in the page you're redirecting to, and add properties in your first page to return the values in the controls and call it using previous page property
refer to this article