Utilizing Google App Engine for seamless deployment, integrating Ajax for dynamic interactions, and

Using the google App Engine, I am looking to implement javascript (or Ajax) for POSTing a form and updating the target div. The form includes multiple fields and files for transfer. The javascript function I am using is extracted from the "Javascript: The Definite Guide" book. I have two specific inquiries:

  1. How should I structure the "data" argument in the postFormData() function within "form.html" to pass all fields and files correctly?
  2. Is there a recommended way to design the callback function so that the response from "form.html" can update the content div?

Appreciate any assistance with this.

base.html:

...
<div id="content">
{% include "form.html" %}
</div>

Image:<br />
<img src="/file?entity_id={{entity.key}}" />
<br />

<script type="text/javascript">
  function postFormData(url, data, callback) {
    if (typeof FormData === "undefined")
      throw new Error("FormData is not implemented");
    var request = new XMLHttpRequest();
    request.open("POST", url);
    request.onreadystatechange = function() {
      if (request.readystate === 4 && callback)
        callback(request);
    };
    var formdata = new FormData();
    for (var name in data) {
      if (!data.hasOwnProperty(name)) continue;
      var value = data[name];
      if (typeof value === "function") continue;
      formdata.append(name, value);
    }
    request.send(formdata);
}
</script>
...

form.html

<form action="/form" method="POST" enctype="multipart/form-data">
  name1: <input type="text" name="name" />{{ name1 }}<br /><br />
  name2: <input type="text" name="name" />{{ name }}<br /><br />
  ...
  file1: <input type="file" name="file" />{{ file1 }}<br /><br />
  file2: <input type="file" name="file" />{{ file2 }}<br /><br />
  ...
         <input type="submit" value="Submit" onclick="return postFormData('/form', howToPrepareData?, whatIsTheCallbackFunction?)" />
</form>

Answer №1

After submitting a form (either by clicking a submit button or via JavaScript), the browser typically reloads the window to display the POST result. This may not be the desired behavior.

One solution is to use a hidden <iframe> as the target for the Form POST action. Check out this example: How to send multipart/form-data form content by ajax (no jquery)?

Answer №2

ready for a simple image upload:

HTML

<form action="/form/index.php?name=" class="imageform" method="POST" enctype="multipart/form-data">
 name: <input type="text" name="name" class="name" /><br /><br />
 file: <input type="file" name="file" class="file"/><br /><br />
        <input type="submit" value="Submit" class="submit" />
</form>
<div id="callback">
</div>

JQUERY

$(document).ready(function() 
{ 
$('.submit').on('click', function() 
{
if($(".name").val()==""){
$(".name").val("Enter Name Here")
}
else { 
var s = $(".name").val();
var n = $(".imageform").attr("action");
$(".imageform").attr("action", function() {
return s+n;
}
$("#callback").html('Uploading.....');
$(".imageform").ajaxForm(
{
target: '#callback'
}).submit();
}
});
});

don't forget to include this link in the head:

<script type="text/javascript" src="http://demos.9lessons.info/ajaximageupload/scripts/jquery.form.js"></script>

all text echoed in the php file will be displayed in #callback. To preview an image, echo the HTML there and maintain the action=/form/index.php?name= in the PHP file. Also, in the PHP file, use $name=$_GET['name'];

Answer №3

I encountered an issue with the code below. It seemed to work sporadically, sometimes functioning properly and other times not. During the times it failed, a Firebug error message popped up saying "ReferenceError: $ is not defined". Can anyone shed some light on what might be causing this issue and whether the code provided is correct? Thank you.

$(document).ready(function() { 
    // binding 'myForm' and setting a basic callback function 
    $('#myForm').ajaxForm(function(returnData) {
        $('#content').html(returnData)
    }); 
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for personalizing text and icon colors in the TableSortText element of Material-ui

My Goal: I aim to empower users with the ability to apply customized styles to my EnhancedTable component by utilizing a styles object containing properties like headCellColor, headCellBackgroundColor, bodyCellColor, bodyCellBackgroundColor, and more. The ...

After upgrading to version 4.0.0 of typescript-eslint/parser, why is eslint having trouble recognizing JSX or certain react @types as undefined?"

In a large project built with ReactJs, the eslint rules are based on this specific eslint configuration: const DONT_WARN_CI = process.env.NODE_ENV === 'production' ? 0 : 1 module.exports = { ... After upgrading the library "@typescript-es ...

Error: Attempting to call vector.subSelf method, which does not exist

Currently, I am experimenting with creating a tank game inspired by Isaac Sukin's "Nemesis" game for AngelHack. The specific change I want to make involves using a model of a tank ("Tank.obj") instead of the default cube used as an enemy. However, I ...

Modify the button's text with jQuery after it has been clicked

I've been struggling to update the text of a button after it's clicked, and I'm encountering an issue where it works in one part of my code but not in another. Could someone please guide me on what might be missing in my code? The first bl ...

Error encountered in jQueryUI Autocomplete: the function 'this.source' is not defined

I have been working on incorporating a live search feature that scans through keys in a JSON obtained from a public API. To achieve this, I am utilizing Jquery UI. However, I encountered the following error and I am uncertain about how to resolve it. Un ...

Utilize jQuery/AJAX to extract a specific value from JSON data and transform it into a different value within the same

Hello everyone, I've been coding all day to try and solve this issue but my code doesn't seem to be working. Can anyone help me with this problem? I'm trying to convert selected JSON data into a different value. Let's take an example: ...

Differences between an AngularJS function() and a factory function() when used in a

When it comes to Angular, I've come across directives being written in two different ways: .directive('example', function () { // Implementation }); .directive('example', function factory() { // Implementation }) Can you ...

"Fake out Jquery with Mockjax for a fun twist on X

I'm attempting to utilize X-editable select2 for users to add tags to images. I've managed to create the tags, and a pop-up box appears when clicked for editing. The new tag is also added to the page. However, the issue lies in the fact that the ...

When working with Vuejs, if you try to use "axios" in a .js file, you may encounter an error

I am currently working with VueJS and attempting to send a GET request to my API. I am using axios, but encountering an issue when trying to import it. If I use require for the import, I receive this error: Uncaught ReferenceError: require is not defined. ...

Is it possible to utilize JStestDriver for testing JavaScript code embedded within JSP files?

Just a quick question: Is it feasible to conduct unit testing, specifically with JStestDriver, on Javascript code that is embedded within JSP files? Or do I need to extract it into separate external javascript files? ...

The Typescript compiler is throwing an error in a JavaScript file, stating that "type aliases can only be used in a .ts file."

After transitioning a react js project to react js with typescript, I made sure to move all the code to the typescript react app and added types for every necessary library. In this process, I encountered an issue with a file called HeatLayer.js, which is ...

Issue with Vue class binding failing to update when state is modified

I'm attempting to utilize Vue class binding depending on the index within the v-for loop. While I can see that the state in Vue dev tools is changing correctly, the class name itself isn't being updated. <div class="group" v-for= ...

Execute JavaScript after authentication instead of forwarding the user to another page

Short version: How can we efficiently handle a second AJAX call after an ASP.NET Membership Authentication response? Long version: Let's say we have a web-based Paint program created using ASP.NET MVC. A user is painting a picture when suddenly their ...

Error detected in Deno project's tsconfig.json file, spreading into other project files - yet code executes without issues?

I am working on a Deno project and need to utilize the ES2019 flatMap() method on an array. To do this, I have created a tsconfig.json file with the following configuration: { "compilerOptions": { "target": "es5", ...

What is the best way to determine when an IndexedDB instance has finished closing?

In the world of IndexedDB, the close method operates asynchronously. This means that while close finishes quickly and returns immediately, the actual connection closure happens in a separate thread. So, how can one effectively wait until the close operatio ...

Is it possible for jquery.find() to only target immediate children?

How can I use jQuery.find() to specifically target only the direct children of an element without selecting their descendants? Leading the selector with '>' or using '*' doesn't give me the desired result. While I know about jQ ...

Is XML parsing used by AJAX?

Is an XML parser used by AJAX? If so, where is it used? I believe that the client-side JavaScript engine utilizes the DOM parser to extract necessary information from the XML document received from the server. Could it be possible that AJAX doesn't us ...

Utilizing jQuery and ajax to send emails within WordPress

Currently facing a minor issue while working on a straightforward quotation form in WordPress. I have two forms; the first one sends data to jQuery for calculations (using minimal options, hence no need for a database), then displays an HTML row. Everythin ...

Retrieving information from MongoDB for a specific ObjectID associated with the current authenticated user

Having two collections in my MongoDB structured as follows: Data User: id: ObjectId ("5fb39e3d11eaad3e30cfb1b0") userName: "Tobias" password: "yyy" id: ObjectId ("5fb3c83fb774ff3340482250") userName: "Thor&qu ...

Implement a loader in AngularJS to display when transitioning between pages

Is there a way to implement a loader that appears when the page starts changing and only disappears once the entire page is fully rendered to prevent clipping bugs? I have already set up the loader as shown below: $scope.$on('$routeChangeStart' ...