Put method with Ajax (the script isn't triggered) - javascript

I am implementing Put method with Ajax:
<!doctype html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#submitPut').click( function () {
console.log("click");
var sendName = $('#name').val();
var sendDescription = $('#description').val();
$.ajax({
url: '/musicalstyle', //Your api url
type: 'PUT', //type is any HTTP method
data: {
name: sendName,
description: sendDescription,
}, //Data as js object
success: function () {
}
})
;
});
});
</script>
</head>
<body>
<form>
<label for="name">Nombre</label>
<input type="text" id="name" />
<label for="description">DescripciĆ³n</label>
<input type="text" name="description" id="description"/>
<input id="submitPut" type="button" value="SubmitPut">
</form>
</body>
</html>
This form is working fine but when introduce it on real environment the script isn't called (my view in production environment is using Thymeleaf and Boostrap). It's like <button class="btn btn-primary" id="submitPut" type="button">Actualizar</button> isn't triggering the submitPut function.
Here form of production environment:
<form>
<div class="form-group row">
<label for="name" class="col-sm-2 col-form-label">Nombre</label>
<div class="col-sm-6">
<input type="text" class="form-control" id="name">
</div>
</div>
<div class="form-group row">
<label for="description" class="col-sm-2 col-form-label">DescripciĆ³n</label>
<div class="col-sm-6">
<input type="text" class="form-control" id="description">
</div>
</div>
<br>
<button class="btn btn-primary" id="submitPut" type="button">Actualizar</button>
</form>
How can I force to button call ajax function?
Thanks,

Your id of input is submit while you called onclick function on query, submitPut.
So,
<input id="submitPut" type="button" value="SubmitDelete"/>

#Biplove I have eddited my comment. Id of input is equal than name of onclick function.

After import JQuery with
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script>window.jQuery || document.write('<script src="../js/jquery.slim.min.js"> <\/script>')</script><script src="../js/bootstrap.bundle.js"></script></body>
Ajax is executed.
My method Put in Controller should redirect to another view and seems to be redirecting. The Spring logs show:
2020-05-21 16:04:15.367 DEBUG 552 --- [nio-8182-exec-9] o.s.web.servlet.DispatcherServlet : PUT "/musicalstyle", parameters={masked}
2020-05-21 16:04:15.368 DEBUG 552 --- [nio-8182-exec-9] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped to com.musicnet.springboot.controller.SystemAdministratorController#updateStyle(Style, Model)
2020-05-21 16:04:15.558 DEBUG 552 --- [nio-8182-exec-9] o.s.w.s.v.ContentNegotiatingViewResolver : Selected '*/*' given [*/*]
2020-05-21 16:04:15.632 DEBUG 552 --- [nio-8182-exec-9] o.s.web.servlet.DispatcherServlet : Completed 200 OK
Here the style is updated so put method is working fine but the view isn't showed on browser. I suspect that Spring doesn't have any problem in order to redirect view, the problem is that ajax script isn't redirecting to the returned view.
How can I modify the ajax script to process the view returned by Spring?
Edit
In fact, I get the redirect putting in ajax script:
success: function () {
window.location.reload();
}

Related

Zendesk App Error & Delayed/Failed Webhook Post

I am building a Zendesk app that will post a variety of information to a webhook. Currently, I am running into two issues. The client.invoke() function says it is not a function in the console when the send email button is pressed. Additionally, sometimes the after the button is pressed, the app will successfully post to the webhook, other times it won't post at all. I cannot narrow down what is causing the discrepancies on when it posts. I'm unsure if this is related to the app I've built or an issue interacting with Zendesk.
Here is the app:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link href="https://cdn.jsdelivr.net/bootstrap/2.3.2/css/bootstrap.min.css" rel="stylesheet">
<link href="main.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript" src="https://assets.zendesk.com/apps/sdk/2.0/zaf_sdk.js"></script>
<script src="https://cdn.jsdelivr.net/handlebarsjs/4.0.8/handlebars.min.js"></script>
</head>
<body>
<script>
var client = ZAFClient.init();
client.invoke('resize', { width: '100%', height: '450px' });
client.get('ticket.brand.subdomain').then(
function(data) {
var subdomain = data['ticket.brand.subdomain'];
console.log('Zendesk Subdomain is ' + subdomain);
document.getElementById('subdomainform').value = subdomain;
}
);
client.get('ticket.organization.id').then(
function(data) {
var org_id = data['ticket.organization.id'];
console.log('Org id is ' + org_id);
document.getElementById('orgidform').value = org_id;
}
);
</script>
<form name="submissionForm">
<div class="formBox">
<label for="title">First Name</label>
<input type="text" id="firstName" placeholder="First Name"/>
</div>
<div class="formBox">
<label for="title">Last Name</label>
<input type="text" id="lastName" placeholder="Last Name"/>
</div>
<div class="formBox">
<label for="title">Email</label>
<input type="text" id="email" placeholder="Email"/>
</div>
<div class="formBox">
<select id="rescom">
<option value="residential">Residential</option>
<option value="commercial">Commercial</option>
</select>
</div>
<div class="formBox">
<button id="btn">Click to Send Email</button>
</div>
<div><p id="explain">The fields below are ready-only and required for submission. If you don't see them, please refresh the app.</p></div>
<div class="formBox">
<input type="text" id="subdomainform" readonly="readonly"/>
</div>
<div class="formBox">
<input type="text" id="orgidform" readonly="readonly"/>
</div>
</form>
<script>
let content = [];
const addDay1 = (ev)=>{
let information = {
id: Date.now(),
firstName: document.getElementById('firstName').value,
lastName: document.getElementById('lastName').value,
email: document.getElementById('email').value,
subdomain: document.getElementById('subdomainform').value,
orgid: document.getElementById('orgidform').value,
rescom: document.getElementById('rescom').value
}
content.push(content);
document.forms[0].reset();
const Url ='{PLACEHOLDER}';
$.ajax({
url: "{WEBHOOK URL}",
type: "POST",
dataType: 'json',
data: {information},
complete: function(){alert("Failure")}
});
}
document.addEventListener('DOMContentLoaded', ()=>{
document.getElementById('btn').addEventListener('click', addDay1);
});
</script>
</body>
</html>
What am I missing? Appreciate any and all help that can be provided.
This was solved my a community manager from Zendesk. See post below:
Make sure ZAFClient is fully registered before attempting to do
subsequent ZAFClient methods. Something like:
client.on('app.registered', e => {
client.get('ticket.brand.subdomain').then(
function(data) {
var subdomain = data['ticket.brand.subdomain'];
console.log('Zendesk Subdomain is ' + subdomain);
document.getElementById('subdomainform').value = subdomain;
}
);
client.get('ticket.organization').then(
function(data) {
var org_id = data['ticket.organization.id'];
console.log('Org id is ' + org_id);
document.getElementById('orgidform').value = org_id;
}
);
}) The "not a function in the console" error is caused from the app's HTML page being resubmitted again when you click the button. In
Zendesk Apps framework, the connection from the app (using
ZAFClient.init()) to the main agent window is done through parameters
that are passed to the app when the framework first loads it. You can
see this in your browser's Network tab if you look for something like
"iframe.html?origin=https%3A%2F%2Fyour_subdomain.zendesk.com&app_guid=ff7133010-abff-4f1c-a7bf-ff7133fff7133"
-- the origin and app_guid params are needed to make the connection. When you resubmit the page, those parameters no longer are passed on
the new page reload and the new call to ZAFClient.init() doesn't
successfully initialize. Thus leading the error when the now invalid
'client' object is attempting to be used to call 'invoke'. You have to
treat these app pages like single-page apps.
Phew! All that said -- you can still use HTML functionality,
just don't have it resubmit the entire page when the button is
pressed. You can do this by adding type="button" to the button tag.
Click to Send Email
See also: HTML button to NOT submit form
Hope this gets you on your way!

Ajax form not submitting form rails

I'm using a super basic google form on my website. I'm using this website to extract the HTML to display it on my website - http://stefano.brilli.me/google-forms-html-exporter/
Once I hit submit, nothing happens. The page is just locked. I'm trying to resubmit it to another page. Here is my code
<div class="row">
<form action="https://docs.google.com/forms/d/e/1FAIpQLSfJQ9EkDN8aggSL9AEB2PK4BGiZgBzLDbS1IPppfSkU1zy-oA/formResponse"target="_self" id="bootstrapForm" method="POST">
<div class="col-sm-6 col-md-3">
<input id="679075295" type="text" name="entry.679075295" class="form-control" >
</div>
<div class="col-sm-6 col-md-3">
<input id="897968244" type="text" name="entry.897968244" class="form-control" >
</div>
<div class="col-sm-6 col-md-3">
<input id="685661947" type="text" name="entry.685661947" class="form-control" >
</div>
<input id="503500083" type="hidden" name="entry.503500083" value="<%= #investment.id %>" >
<div class="col-sm-6 col-md-3">
<button type="submit" value"submit" class="btn btn--primary type--uppercase" >Get Started</button>
</div>
</form>
Here is the ajax script
<script>
$('#bootstrapForm').submit(function (event) {
event.preventDefault()
var extraData = {}
$('#bootstrapForm').ajaxSubmit({
data: extraData,
dataType: 'jsonp', // This won't really work. It's just to use a GET instead of a POST to allow cookies from different domain.
error: function () {
// Submit of form should be successful but JSONP callback will fail because Google Forms
// does not support it, so this is handled as a failure.
alert('Form Submitted. Thanks.')
// You can also redirect the user to a custom thank-you page:
window.location = 'http://reif.com.au/thankyou'
}
})
})
</script>
</div>
Feeling a little silly on this one. Essentially i didn't copy over all of the scripts. I was rushing through.. ALWAYS number 1 error!
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.form/4.2.2/jquery.form.min.js" integrity="sha256-2Pjr1OlpZMY6qesJM68t2v39t+lMLvxwpa8QlRjJroA=" crossorigin="anonymous"></script>
This is what i needed to add, it now successfully submits and redirects!

.click() function doesn't work javascript / jquery

UPDATE:
Somehow the just work fine after I tried it..
UPDATE
I'm using .click() function on my javascript, but it doesn't work.
Here is my JS code:
src="jquery.js";
var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
var institutionID, acadCareerID;
$(document).ready(function(){
getInstitution();
institutionID = $( "select#institution option:checked" ).val();
if(institutionID == null){
institutionID = 1;
}
getAcadCareerByInstitution(institutionID);
acadCareerID = $( "select#acadCareer option:checked" ).val();
if(acadCareerID == null){
acadCareerID = 1;
}
getPeriodByAcadCareerAndInstitution(acadCareerID);
getDepartmentByAcadCareer(acadCareerID);
$("select#institution").change(function(){
institutionID = $( "select#institution option:checked" ).val();
getAcadCareerByInstitution(institutionID);
})
$("select#acadCareer").change(function(){
acadCareerID = $( "select#acadCareer option:checked" ).val();
getPeriodByAcadCareerAndInstitution(acadCareerID);
getDepartmentByAcadCareer(acadCareerID);
})
$("div#search").click(function(){
alert("The paragraph was clicked.");
console.log("abc");
});
});
all functions like getInstituion(), getAcadCareerByInstitution(institutionID) etc are ajax call.
Here is my HTML code:
<form action="doInsertSchedule" method="POST" enctype="multipart/form-data">
{{csrf_field()}}
<div class="form-group">
<label for="institution">Institution</label>
<select name="institution" class="form-control" id="institution">
</select>
</div>
<div class="form-group">
<label for="acadCareer">Academic Career</label>
<select name="acadCareer" class="form-control" id="acadCareer">
</select>
</div>
<div class="form-group">
<label for="period">Period</label>
<select name="period" class="form-control" id="period">
</select>
</div>
<div class="form-group">
<label for="department">Department</label>
<select name="department" class="form-control" id="department">
</select>
</div>
<div class="form-group">
<label for="date">Deadline Date</label>
<input type="date" class="form-control" id="deadline" placeholder="Deadline Date" name="deadline">
</div>
<button type="submit" class="btn btn-default">Submit</button>
<div id="search" class="btn btn-default">Search</div>
</form>
I already put jquery for my Master Layout (Laravel 5)
<head>
<link rel="stylesheet" type="text/css" href="{{url()}}/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="{{url()}}/css/style.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.6.3/css/font-awesome.min.css">
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="{{url()}}/js/tools.js"></script>
<script src="{{url()}}/js/bootstrap.min.js"></script>
<title>BINUS - #yield('title')</title>
<meta name="csrf-token" content="{{ csrf_token() }}" />
</head>
I want the Search Button / Div to do something when I click. I can't see what's wrong here.
I already tried <div> to <button> but it just will work like submit. I also already tried to put event.preventDefault() at my JS code, but it didn't work too.
Maybe you can try with event delegation...
$(document).ready(function(){
$("body").on("click", "#search", function(){
alert("The paragraph was clicked.");
console.log("abc");
});
});
You code works OK. You need to write the jquery library in the final, just before of </body>
...
<script type="text/javascript" src=".../jquery.js"></script>
</body>
Example it works ok!: Example Jsfiddle
<button type="submit" class="btn btn-default">Submit</button>
<div id="search" class="btn btn-default">Search</div>
This looks like it will render on the page as two buttons. Your ID here is attached to the div, not to the button, they should both appear to look like buttons providing bootstrap is loaded, but only the div with "search" as the content will do anything.
This is the only thing that appears odd, the only other problem is you are not loading your jquery as stated elsewhere.
I don't have the reputation to comment, but have you added a jquery library before your script?
Secondly, if you did and the items on the page are loaded after the document has loaded you will need to change your code up, for instance:
Give your form an id
<form action="doInsertSchedule" method="POST" enctype="multipart/form-data" id="postForm">
Then in your jquery script
<script>
$('#postForm').on('click', '#search', function(){
alert("The paragraph was clicked.");
console.log("abc");
});
</script>
The above will allow the javascript to run on items that are bought in after document load, however it is important you set it on a parent element that is avaiable at document load

My ajax code don't send the data to the database

I want to use ajax to add data in the database but nothing happens
i don't know whats wrong is it in the ajax!or in the php
This is part of my code:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript" >
$(document).ready(function(){
$("#commentForm").submit(function(){
var U_N = $('input[name="U_N"]').val();
var I_name = $('input[name="I_name"]').val();
var context = $("#inputmessage").val();
$.ajax({
type: "POST",
cache: false,
url : "aAddComm_Menu.php",
data : {U_N:U_N,I_name:I_name,context:context},
});
});
});//end of document ready function
</script>
this the html form:
<form class="form-horizontal" role="form" id="commentForm" method="POST" action="">
<div class="form-group">
<label for="inputmessage" class="col-sm-2 control-label">comment</label>
<div class="col-sm-10">
<textarea name = "context" class="form-control" id="inputmessage" rows="3" placeholder="Enter your comment here . . "></textarea>
</div>
</div> <!-- End of /.form-group -->
<input type="hidden" value = "$Item['Item_Name']" name="I_name"/>
<input type="hidden" value ="$U_N" name="U_N"/>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button name="SendC" type="submit" class="btn btn-primary" ;>Send</button>
</div>
</div>
</form>
and this is a part of the php page for adding to the database
extract($_POST)
if(isset($context))
{
mysql_query("INSERT INTO menu_commnet VALUES('$I_name','$U_N',NULL,NOW(),'$context')");
}
var U_N = $("input#U_N").val();
var I_name = $("#I_name").val();
var context = $("#context").val();
The jQuery selectors are wrong, you're not selecting anything. The # selector stands for id attribute, but you're trying to select by value of name attribute. You should either add/change id attributes of your input fields, or use
var U_N = $("input[name=U_N]").val();
var I_name = $("input[name=I_name]").val();
var context = $("[name=context]").val();
Tip: next time use developer console inside your browser, you can easily test if selectors are correct. You can type in javascript code as you would inside .js file and test if it's working like you expect.
Also, don't do this in your PHP, use prepared statements.
Did you included you Database conection on your Backend script?
extract($_POST)
'if(isset($context)) {
mysql_query("INSERT INTO menu_commnet VALUES('$I_name','$U_N',NULL,NOW(),'$context')");
}'
i think here you should include you database info, 'include_once("database info.php"); , also make sure you ajax will return a result, and echo php errors, just to be sure its an ajax or php error,
I have few comment regarding your issue :
Replace $("document").ready(function(){ with
$(document).ready(function(){
Before extracting in PHP ,
try var_dump($_POST)
Based on your HTML code use:
var U_N = $('input[name="U_N"]').val();
var I_name = $('input[name="I_name"]').val();
var context = $("#inputmessage").val();
Here is final working example. Just add "ev" argument to submit callback function , then use ev.preventDefault() in it.
$(document).ready(function(){
$("#commentForm").submit(function(ev){
ev.preventDefault();
var U_N = $('input[name="U_N"]').val();
var I_name = $('input[name="I_name"]').val();
var context = $("#inputmessage").val();
$.ajax({
type: "POST",
cache: false,
url : "aAddComm_Menu.php",
data : {U_N:U_N,I_name:I_name,context:context}
});
});
});//end of document ready function
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form class="form-horizontal" role="form" id="commentForm" method="POST" action="">
<div class="form-group">
<label for="inputmessage" class="col-sm-2 control-label">comment</label>
<div class="col-sm-10">
<textarea name="context" class="form-control" id="inputmessage" rows="3"
placeholder="Enter your comment here . . "></textarea>
</div>
</div>
<input type="text" value="" name="I_name"/>
<input type="text" value="" name="U_N"/>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button name="SendC" type="submit" class="btn btn-primary">Send</button>
</div>
</div>
</form>

Sending HTML form via AJAX to PHP server

I'm working on phonegap, basically its like making mobileapps crossplatform by using HTML, JS and CSS. On the device i currently have the JS and the HTML (form) in same document.
What I'm trying to do is to pass email and password to my server, and then process it there through a login. I've tested the login script on the server and it works with hardcoded data. So I'm guessing somewhere when sending the data from the device its failing.. I'm fairly new to JS too.
I tried to hardcode the data in the AJAX but it doesnt seem to work. Preferebly I would like to use something like var pdata = $('#form').serialize(); or something else if its better.
Any ideas?
EDIT: Forgot to say that the PHP on the server auto submits by using JS when $_POST is set (isset)
The form
<form id="form" onsubmit="dologin()">
<div class="form-group">
<label for="email">Epost</label>
<input type="email" class="form-control" name="email" value="" placeholder="Epost">
</div>
<div class="form-group">
<label for="password">Passord</label>
<input type="password" class="form-control" name="password" value="" placeholder="Passord">
</div>
<div class="checkbox">
<label>
<input type="checkbox" name="remember_me">
Husk meg
</label>
</div>
<button type="submit" class="btn btn-primary">Logg inn</button>
</form>
The javascript
<script>
function dologin() {
//var pdata = $('#form').serialize();
//alert(pdata);
$.ajax({
type: 'POST',
data: {email:"test#test.no",password:"test"},
url: 'LINK',
success: function(data) {
alert(data);
},
error: function() {
alert("error");
}
});
return false;
};
</script>
The PHP
<form id="form" method="post">
<!-- {{ Form::label('email', 'Email Address') }} -->
<div class="form-group">
<input type="text" name="email" value="<?php if(isset($_POST["email"])) echo $_POST['email'];?>">
</div>
<div class="form-group">
<!-- {{ Form::label('password', 'Password') }} -->
<input type="text" name="password" value="<?php if(isset($_POST["password"])) echo $_POST['password'];?>">
</div>
</form>
Are you able to hit your server via through phonegap?
If no then please check your config.xml for white list urls - change access control property to
access origin = "*"
Hopeful you will be able to hit your server with data.
You can use weinre to debug your app. That way you will be able to see if the request was placed from the app or not.
http://people.apache.org/~pmuellr/weinre/docs/latest/Home.html

Categories

Resources