AJAX REST call don't send data - javascript

After I click submit button, my form and page refreshes, and nothing is sent to datebase.
Code in subforum.js
$(document).on('click','#submit',function(e) {
var user = JSON.parse(sessionStorage.getItem("ulogovan"));
console.log("usao u submit");
alert("Usao");
var dataObject = JSON.stringify({
'title': $('#titleSubforum').val(),
'description': $('#descriptionSubforum').val(),
'iconPath': $('#pictureSubforum').val(),
'mainModerator': user.username,
'rules': $('#rulesSubforum').val()
});
alert($('#rulesSubforum').val());
$.ajax({
type : 'POST',
url : "../WebProjekat/rest/subforums/create",
contentType : 'application/json',
dataType : "json",
data: dataObject,
success : function(data) {
console.log("USAO U CUVANJE ");
alert("all good");
window.location.href = "index.html";
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
alert("something wrong");
console.log(textStatus);
console.log(user);
}
});
});
code in SubforumController.java
package controllers;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import beans.Subforum;
import services.SubforumService;
#Path("/subforums")
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public class SubforumController {
private SubforumService subforumService = new SubforumService();
#GET
public List<Subforum> getSubforums() {
return subforumService.getAllSubforums();
}
#POST
#Path("/create")
public Subforum createSubforum(Subforum subforum) {
System.out.print(subforum.getTitle());
return subforumService.createSubforum(subforum);
}
And code in SubforumService.java
package services;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import datebase.DatebasePath;
import beans.Subforum;
public class SubforumService {
public SubforumService() {
}
private Map<String, Subforum> subforums = DatebasePath.getSubforums();
public Subforum createSubforum(Subforum subforum) {
subforums.put(subforum.getTitle(), subforum);
DatebasePath.saveData(DatebasePath.subforumsPath);
return subforum;
}
public List<Subforum> getAllSubforums() {
return new ArrayList<Subforum>(subforums.values());
}
}
DatebasePath is good, becouse I hardcoded subforum object, and writed down to .txt file. I think that problem is between subforum.js and SubforumController.java

After I click submit button, my form and page refreshes
this is frequently caused by the form post ocuring rather than your custom $.ajax POST code.
and nothing is sent to database.
As $.ajax POST occurs asynchronously, the form's post occurs first, refreshing your page and thus not hitting your own submit handler.
There are two relatively easy options for this:
e.preventDefault in the handler
eg
$(document).on('click','#submit',function(e) {
e.preventDefault();
// remaining code
don't submit on the button
Change
<input type='submit' id='submit'>submit</input>
to
<input type='button' id='submit'>submit</input>

Related

Angular request redirect to URL after POST submission

I am new to Angular and following this tutorial to create a MailChimp submission form. I have replaced the list information & id and the tutorial with my own. On submission of the form, I want to redirect to a Thank You page, which was not shown in the tutorial.
When I submit user email to the list, I get a 200 response back from the server on my POST request.
However, I have two problems.
#1 The redirect does not navigate to the '/thanks' route. I'm not sure if this is the actual way this function should be used for navigation. I thought it would work similar to React's this.history.push. I got the basic idea for this function from this Stack Overflow question
subscribe-form-component.ts
export class SubscribeFormComponent implements OnInit {
subscribeData: any = <any>{};
constructor(
private subscribeService: SubscribeService,
private router: Router
) {}
ngOnInit() {}
onSuccess() {
this.router.navigate(['/thanks']);
}
subscribe(subscribeForm: NgForm) {
if (subscribeForm.invalid) {
return;
}
this.subscribeService.subscribeToList(this.subscribeData).subscribe({
complete: () => {this.subscribeData},
next: () => {this.onSuccess},
error: (err) => {
console.log('err', err);
},
});
}
}
However, in the console log console.log('err', err), though the submit form returns a 200 response from the sever, I did notice a JSONP error:
Error: JSONP injected script did not invoke callback.
message: "Http failure response for https://xxxxxxx.us11.list-manage.com/subscribe/post?u=afd1f3490xxxxxxxx7883fb&id=035xxxx952&f_id=009fa6e0f0&EMAIL=xxxxxx#icloud.com&c_afd1f34907923e052b17883fb_009fa6e0f0=&c=ng_jsonp_callback_0: 0 JSONP Error"
name: "HttpErrorResponse"
ok: false
status: 0
statusText: "JSONP Error"
url: "https://xxxxxx.us11.list-manage.com/subscribe/post?u=afd1f349xxxxxxx7883fb&id=035b97f952&f_id=009xxxxf0&EMAIL=xxxxx#icloud.com&c_afd1f34907923e052b17883fb_009fa6e0f0=&c=ng_jsonp_call
If my onSuccess navigation route function/syntax is correct, I'm assuming that the reason it is not redirecting is because of this error in the console.
subscribe.service.ts
import { Injectable } from '#angular/core';
import { HttpClient, HttpParams } from '#angular/common/http';
import { Router } from '#angular/router';
#Injectable({
providedIn: 'root'
})
export class SubscribeService {
mailChimpEndpoint = 'https://xxxxxx.us11.list-manage.com/subscribe/post?u=afd1f3490xxxxxxxxxb&id=035b9xxxx52&f_id=009faxxxf0';
constructor(
private http: HttpClient,
private router: Router
) { }
subscribeToList(data: any) {
const params = new HttpParams()
.set('EMAIL', data.email)
.set('afd1f3490xxxxxxxxxxb_009fa6e0f0', '');
const mailChimpUrl = `${this.mailChimpEndpoint}&${params.toString()}`;
return this.http.jsonp(mailChimpUrl, 'c')
}
}
How do I fix this JSON P error and correctly redirect after submission?
By default, JSONP will cause the error that you are seeing when using the Angular HttpClient.
There is a HttpClientJsonpModule that can be used instead of the HttpClientModule, and it does support JSONP.
Documentation is at https://angular.io/api/common/http/HttpClientJsonpModule

How can I use main.dart variable in my JS file?

I'm trying to create a calling app using flutter and I've created the backend using a node.js. This is how my main.dart file in flutter looks like:
import 'package:flutter/material.dart';
import 'dart:async';
import 'dart:io';
import 'package:flutter/services.dart';
import 'package:flutter_dialpad/flutter_dialpad.dart';
import 'dart:js';
import 'package:js/js.dart';
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
#override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
backgroundColor: Colors.black,
body: SafeArea(
child:
DialPad(
enableDtmf: true,
outputMask: "(000) 000-0000",
backspaceButtonIconColor: Colors.red,
makeCall: (number){
print(number);
}
)
),
),
);
}
}
I want to use this "number" variable in my app.js file which looks like this:
const accountSid = '***';
const authToken = '***';
const client = require('twilio')(accountSid, authToken);
client.calls.create({
url: 'http://demo.twilio.com/docs/voice.xml',
to: '+10000000',
from: '+1000000',
}, function(err, call){
if (err) {
console.log(err);
} else {
console.log(call.sid);
}
})
I want to be able to use the "number" variable from my main.dart file in the "to" field in my app.js file. Please help me out...
What you need is a way to pass data between applications, and the easiest way for that would be through a REST API
You can use the HTTP module in NodeJS or a third-party package like Express and set up a POST Route to your NodeJS Server, where the number is sent as data.
Once the data is received on your server, you can call your Twilio function, and send a response back.
On Flutter, you can use the http package to make the API call.

Using d3.js via postgres

I'm currently studying java spring and d3.js. And found myself on a roadblock since i can't seem to find the right answer to my problem after countless trial and error plus research.
The code below is the one that is my controller:
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import dashboard.atmandcam.model.MyModel;
import dashboard.atmandcam.repo.MyRepo;
#RestController
public class MyController {
#Autowired
private MyRepo myRepo;
#GetMapping("/test")
public String sayHi() {
return "hi";
}
#GetMapping("/queries")
public List<MyModel> getResult(){
return myRepo.getQueryResult();
}
#GetMapping("/queries/{id}")
public List<MyModel> getSpecific(#PathVariable String id){
return myRepo.getSpecificResult(id);
}
}
Then this is my d3.js
var url = "/queries/31370100";
d3.json(url, function(data) {
console.log(data);
});
the result of my controller is w/ the URL (http://localhost:9090/queries/31370100):
I wanna know how can i use the JSON found on my url in d3.js so i can build my charts around my database.

Cross Origin requests at server side

Hi I am facing issue in cross origin requests at server side when trying to open file which is retrieved from database using java.I am unaware of this cross orgin requests.When file is clicked then it is giving error as
jquery.min.js:4 XMLHttpRequest cannot load file:///C:/Users/JR00432239/Desktop/trial/src/temp/filetest1.docx. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.
Can anyone please help me to resolve this issue.
Here is my java code:
package fileretrieve;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.nio.charset.Charset;
import java.sql.Blob;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import dbConnection.Dbconn;
#MultipartConfig
public class FileRetrieve extends HttpServlet {
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/plain");
PrintWriter out = response.getWriter();
String onelevel=request.getParameter("onelevel");
Connection conn = null; // connection to the database
String message = null;
Statement st = null;// message will be sent back to client
try {
// connects to the database
conn = Dbconn.getConnection();
st = conn.createStatement();
PreparedStatement ps=conn.prepareStatement("select data from files1 where board=?");
ps.setString(1,onelevel);
//out.print("<table width=25% border=1>");
// out.print("<center><h1>Result:</h1></center>");
ResultSet rs=ps.executeQuery();
/* Printing column names */
ResultSetMetaData rsmd=rs.getMetaData();
int count=0;
while(rs.next())
{
count=count+1;
FileOutputStream fos = new FileOutputStream("C:\\Users\\JR00432239\\Desktop\\trial\\src\\temp\\filetest"+count+".docx");
fos.write(rs.getBytes(1));
fos.close();
// out.print("<tr>");
// out.print("<td>"+rsmd.getColumnName(1)+"</td>");
// out.print("<td>"+count+"</td></tr>");
// getServletContext().getRequestDispatcher("/home.html").forward(request, response);
System.out.println("writing...");
response.getWriter().write("{\"name\":\""+count+"\",\"path\":\"C:/Users/JR00432239/Desktop/trial/src/temp/filetest"+count+".docx\"}");
}
// out.print("</table>");
//
}catch (Exception e2)
{
e2.printStackTrace();
}
finally{
// request.setAttribute("data", data);
// RequestDispatcher rd =request.getRequestDispatcher("userview.jsp");
//
out.close();
}
// forwards to the message page
// getServletContext().getRequestDispatcher("/home.html").forward(request, response);
}
}
Here is my html code:
Submit
Here is my javascript page:
$("#retrieve").click(function(){
$.ajax({
url : 'FileRetrieve',
method:"POST",
data : {
onelevel : $('#onelevel').val()
},
crossDomain: true,
success : function(responseText) {
var data=JSON.parse(responseText)
$("#files_data").html('')
$("#files_data").html('<table><tr><td><button onclick="getFile()">'+data.name+'</button></td></tr></table>')
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Status: " + textStatus); alert("Error: " + errorThrown);
}
});
return false;
});
If you're using chrome, as a simple solution try a chrome extention like Allow-Control-Allow-Origin:*
https://chrome.google.com/webstore/detail/nlfbmbojpeacfghkpbjhddihlkkiljbi?utm_source=chrome-app-launcher-info-dialog
if not fixed,
run chrome using command line with the flag
path/to/chrome.exe --allow-file-access-from-files
or just switch to firefox and check whether the issue is still there
this would be a quick-fix only in the development
EDIT
As far as I know, best thing you can do is make the files available in http server and access them using http protocol.

How to call function in Cordova Plugin

I wrote a simple cordova plugin which displays an alert.
JS file: alert.js
module.exports = {
alert: function(title, message, buttonLabel, successCallback) {
cordova.exec(successCallback,
null, // No failure callback
"Alert",
"alert",
[title, message, buttonLabel]);
}
};
Java File: Alert.java
package com.acme.plugin.alert;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaInterface;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CordovaWebView;
import org.apache.cordova.PluginResult;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class Alert extends CordovaPlugin {
protected void pluginInitialize() {
}
public boolean execute(String action, JSONArray args, CallbackContext callbackContext)
throws JSONException {
if (action.equals("alert")) {
alert(args.getString(0), args.getString(1), args.getString(2), callbackContext);
return true;
}
return false;
}
private synchronized void alert(final String title,
final String message,
final String buttonLabel,
final CallbackContext callbackContext) {
new AlertDialog.Builder(cordova.getActivity())
.setTitle(title)
.setMessage(message)
.setCancelable(false)
.setNeutralButton(buttonLabel, new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialogInterface, int which) {
dialogInterface.dismiss();
callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, 0));
}
})
.create()
.show();
}
}
How do I call the alert function of alert.js from another js? And what parameter should i pass to map to successCallback??
according to cordova git for creating plugin see github page you can do it like this
Add the following code to wherever you need to call the plugin functionality:
‍‍‍cordova.plugins.<PluginName>.<method>();
where <PluginName> is your plugin name and <method> is your method.

Categories

Resources