Why method not allowed http exception? - javascript

I have a form in laravel.
I want to send the data to server using ajax post request.
The laravel give me error. I dont know why?
My view source url is : http://localhost/lily/public/search
(1/1) MethodNotAllowedHttpException
in RouteCollection.php (line 251)
at RouteCollection->methodNotAllowed(array('GET', 'HEAD'))
in RouteCollection.php (line 238)
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
crossorigin="anonymous"></script>
</head>
<body>
<script type="text/javascript">
$(document).ready( function () {
$("#submit").submit( function(){
var name = $("#name").val();
console.log(name);
$.ajax({
type: "POST",
url : "{{url('/search')}}",
data : name ,
success : function(data)
{
console.log(data)
},
error : function(error)
{
console.log(error)
}
});
});
});
</script>
<div class="col-md-6 offset-3">
<form id="submit" method="POST">
<input type="name" name="name" id="name">
<button type="submit" class="btn btn-success">search</button>
</form>
</div>
</body>
</html>
Route::post('/search/{name}', 'HomeController#in');
public function in() {
return json("fdfdfdfdfdf");
}

You defined a a route for /search/parameter, but your action is only '/search'.
Remove the useless {name} part in the route. Or make it optional with {name?}

Pass the CSRF token along with the request, after changing your route definition to either remove {name} or making it optional {name?} then change your data to
$(document).ready(function() {
$("#submit").submit(function() {
e.preventDefault(); // Prevent the Default Form Submission
var name = $("#name").val();
console.log(name);
$.ajax({
type: "POST",
url: "{{ url('/search') }}",
data: {
name: name,
_token: "{{ csrf_token() }}"
},
success: function(data) {
console.log(data)
},
error: function(error) {
console.log(error)
}
});
});
});
The input type should be text instead of name in the form
<input type="text" name="name" id="name">

Because you did not add CSRF token value as a hidden type.
You must add CSRF hidden input to Form.
<input type="hidden" name="_token" value="{{ csrf_token() }}" />

Related

sending message to telegram bot

i need some help,
am trying to send message to telegram bot
but things are not working out for me,
am just trying to archive what i want to do. am new to jquery and javascript
below is what i tried
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<script>
$(document).ready(function () {
$("#add_button").click(function(event) {
Execute();
});
var fname = document.querySelector('input[name="fname"]').value;
var country = document.querySelector('input[name="country"]').value;
Message: "<html><br>| Fullname: ${fname} <br> | Country: ${country} <br></html>";
function Execute(){
$.ajax({
type: 'POST',
url: 'https://api.telegram.org/bot<token>/sendMessage?chat_id=<id>text=<message>&parse_mode=html',
data: Message,
success: function(res) {
$('#response').text('Message sent');
},
error: function() {
alert("error failed");
}
});
};
});
</script>
<input type="text" id="fname" name="fname" placeholder="fullname">
<input type="text" id="country" name="country" placeholder="country">
<input type="button" id="add_button" value="Submit">
<div id="response"></div>
<body>
</body>
</html>
There are several issues in you script:
Your <body> tag is misplaced
AFAIK, your payload must be form encoded (not as GET params)
Use ` for format strings instead of "
read the input values in the execute method, not outside (otherwise you read them only once on page load).
You cannot use <br> or <html> in the message, see the docs
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<input type="text" id="fname" name="fname" placeholder="fullname">
<input type="text" id="country" name="country" placeholder="country">
<input type="button" id="add_button" value="Submit">
<div id="response"></div>
<script>
const token = '<token>';
const chatId = '<chat_id>';
$(document).ready(function () {
$("#add_button").on('click', function (event) {
execute();
});
function execute() {
const fname = document.querySelector('#fname').value;
const country = document.querySelector('#country').value;
const message = `Fullname: ${fname}\nCountry: ${country}`;
$.ajax({
type: 'POST',
url: `https://api.telegram.org/bot${token}/sendMessage`,
data: {
chat_id: chatId,
text: message,
parse_mode: 'html',
},
success: function (res) {
console.debug(res);
$('#response').text('Message sent');
},
error: function (error) {
console.error(error);
alert("error failed");
}
});
}
});
</script>
</body>
</html>
And a security note:
Do NOT use this script in any production! NEVER EVER!
Everyone would be able to read and abuse your bot token.
Use a backend for this.

Ajax 500 internal server error in laravel 7,

I Already put the token in the data to be send but the error still 500 internal server error
in the web.php
Route::post('/Achievement', 'AchievementController#store');
url /Achievement go to AchievementController and run function store
in the AchievementController
public function store(Request $req){
$idPembicara= Pembicara::where('idUser','like',Auth::user()->id)->first();
$data = Penghargaan::create([
'idPembicara'=>$idPembicara->id,
'tahun' => $req['tahunRow1'],
'lokasi' => $req['lokasiRow1'],
]);
return $data;
}
app.blade.php
<meta name="csrf-token" content="{{ csrf_token() }}">
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
achievement.blade.php
<form id="updateAchievement">
{{csrf_field()}}
<input type="text" class="form-control" id="tahunRow1" name="tahunRow1">
<input type="text" class="form-control" id="lokasiRow1" name="lokasiRow1">
<button type="submit" value="submit" class="btn btn-primary"></button>
</form>
<script type="application/javascript">
$(document).ready(function() {
$("#updateAchievement").submit(function(e) {
e.preventDefault();
var token = $('meta[name="csrf-token"]').attr('content');
var mData = {
'lokasiRow1': $('input[name=lokasiRow1]').val(),
'tahunRow1': $('input[name=tahunRow1]').val(),
_token: token,
};
console.log(mData);
$.ajax({
type: "POST",
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
url: "/Achievement",
data: mData,
success: function(e) {
location.reload();
},
error: function(e) {
console.log(e);
}
});
});
});
is there anything i miss, thanks before, sorry for bad english

I want to get my textbox values from HTML document and post those when submit button is pressed using Json file in node JS

This is my JS file:-
$(document).ready(function(){
$('form').on('submit', function(){
var email = $("form input[type=text][name=emails]").val();
var todo = {email: email.val(),
pass:dat.val()};
$.ajax({
type: 'POST',
url: '/project',
data: todo,
success: function(data){
//do something with the data via front-end framework
location.reload();
}
});
return false;
});
});
This is my html document:-
<html>
<head>
<script src="https://code.jquery.com/jquery-3.2.1.js"></script>
<script src="/assests/todo-list.js"></script>
<body>
<form>
<div class="container">
<label><b>Email</b></label>
<input type="text" placeholder="Enter Email" name="emails" required>
<label><b>Password</b></label>
<input type="password" placeholder="Enter Password" name="psw" required>
<button type="submit" class="signupbtn">Sign Up</button>
</div>
</div>
</form>
</body>
</head>
</html>
I want that when i click submit button value from both text boxes gets saved in my database(using Mlab),for that i am using a json file to fire post request to the server.
My main post request handler:-
app.post('/project',parser,function(req,res)
{
var register=Todo(req.body).save(function(err,data)
{
if(err) throw err
res.json(data);
});
});
EDIT:-
I removed my Javascript file and now i am directly posting the form using and i am able to save my email address but not the password.
This is my main code now :-
app.post('/views/register',parser,function(req,res)
{
var data={
email:req.body.emails,
password:req.body.passcode
};
var send=Todo(data).save(function(err)
{
if(err) throw err
res.render('login')
})
});
If I understand your question right, you're missing the contentType param.
$.ajax({
type: 'POST',
contentType: "application/json; charset=utf-8",
...
then try again.
I was not following the correct schema for the database when creating the object
var data={
email:req.body.emails,
password:req.body.passcode
};
The property name was pass and i was using password that's why it was not inserting the password.
var data={
email:req.body.emails,
pass:req.body.passcode
};

Mailchimp via jQuery Ajax. Submits correctly but JSON response is returned as a separate page

I have the following form:
<form class="footer-newsletter-form" id="footer-newsletter" method="post" action="http://xxxxxx.us1.list-manage.com/subscribe/post-json?u=xxxxxxxxxxxxxxxxxxxxxxxxx&id=xxxxxxxxxx&c=?">
<input id="email" name="EMAIL" type="email" class="input-text required-entry validate-email footer__newsletter-field" value="{% if customer %}{{ customer.email }}{% endif %}" placeholder="{{ 'general.newsletter_form.email_placeholder' | t }}" aria-label="{{ 'general.newsletter_form.newsletter_email' | t }}">
<button type="submit" title="Subscribe" class="button button1 hover-white footer__newsletter-button">SUBSCRIBE</button>
<div id="subscribe-result"></div>
</form>
And the following jquery bit:
<script type="text/javascript">
$(document).ready(function () {
function register($form) {
jQuery.ajax({
type: "GET",
url: $form.attr('action'),
data: $form.serialize(),
cache : false,
dataType : 'jsonp',
contentType: "application/json; charset=utf-8",
error : function(err) { console.log('error') },
success : function(data) {
if (data.result != "success") {
console.log('success');
} else {
console.log('not success');
//formSuccess();
}
}
});
}
jQuery(document).on('submit', '.footer-newsletter-form', function(event) {
try {
var $form = jQuery(this);
event.preventDefault();
register($form);
} catch(error){}
});
});
</script>
Which submits correctly. However, when I press the submit button what I expect to happen is that the page does not refresh and when I check the browser console I'll either see "success" or "not success". Instead what happens is I'm sent to a page that displays the following JSON message: ?({"result":"success","msg":"Almost finished... We need to confirm your email address. To complete the subscription process, please click the link in the email we just sent you."}).
So how do I take that success message (or error if there's an error) and have the page not only remain as is, but also capture the success message so I can display a "Success" alert? The success alert I know how to do. I just need help having the browser remain where it is and tell the difference between success and error.
P.S. I'm not sure if this is relevant but the platform is Shopify. I don't think Shopify does anything to prevent the submission from going through as it should or the response coming back so I don't think it is relevant.
The whole issue was the $(document).ready(function () {}); part. For some reason unbeknownst to me that causes the event.preventDefault(); method from running and the form submits regularly. If you remove the $(document).ready(function () {}); part it'll work as intended.
My final code for anyone looking in the future:
Form:
<form class="footer-newsletter-form" method="POST" id="footer-newsletter" action="https://xxxxxxxxxxxxx.us1.list-manage.com/subscribe/post-json?c=?">
<input type="hidden" name="u" value="xxxxxxxxxxxxxxxxxxxxxxxxxxx">
<input type="hidden" name="id" value="xxxxxxxxxx">
<input id="email" name="EMAIL" type="email" class="input-text required-entry validate-email footer__newsletter-field">
<button type="submit" title="Subscribe" class="button button1 hover-white footer__newsletter-button">SUBSCRIBE</button>
<div id="subscribe-result"></div>
</form>
And the JS:
<script>
function register($form) {
$.ajax({
type: "GET",
url: $form.attr('action'),
data: $form.serialize(),
cache: false,
dataType: 'json',
contentType: "application/json; charset=utf-8",
error: function (err) {
console.log('error')
},
success: function (data) {
if (data.result != "success") {
console.log('Error: ' + data.msg);
} else {
console.log("Success");
$($form).find("div#subscribe-result").html("<p class='success-message'>Almost finished... We need to confirm your email address. To complete the subscription process, please click the link in the email we just sent you!</p>");
setTimeout(function() { $($form).find("div#subscribe-result").hide(); }, 7000);
}
}
});
}
$(document).on('submit', '#footer-newsletter', function (event) {
try {
var $form = jQuery(this);
event.preventDefault();
register($form);
} catch (error) {}
});
</script>

How to grab the text field values and send the value over a webservice

When the user clicks on the button, i need the values of the following TextFields to be submitted to a Webservice located at /TestService/SaveMethod.
<div class="content">
#Html.TextBoxFor(mo => mo.id, new { id = "id" })
<input type="text" id="fname" name="fname" />
<input type="submit" value="send" class="save"/>
</div>
jquery:
$(function () {
$('.save').click(function () { // How to grab the values of those textfields and send it over the webservice located at `/TestService/SaveMethod` });
});
You don't need the jQuery unless you explicitly want to use it and that too for ajax. Just put one form in your html like:
<div class="content">
#using(Html.BeginForm("SaveMethod","TestService",new{},FormMethod.Post,new{}){
#Html.TextBoxFor(mo => mo.id, new { id = "id" },new{})
<input type="text" id="fname" name="fname" />
<input type="submit" value="send" class="save"/>
}
</div>
You can get the textfield value in script by accessing its value using val() method and send the value to webservice using ajax post.
$(function () {
$('.save').click(function () {
var name = $("#taYourName").val();
$.ajax(
{
Type: "POST",
contentType: "application/xml",
url: "YourNameIs.asmx/YourName",
data: { yourName: name },
success: function (msg) {
$("#lblForAjax").text(msg);
}
});
});
});
Should be like this : it will give you first name value.
$(function () {
$('.save').click(function ()
{
var name = $("#fname").val();
});
});
You can do it with jquery ajax . This is a tested code for you .
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Test webservices</title>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
$(document).ready(function () {
$('#submit').click(function (e) {
e.preventDefault();
var x = $('#myval').val();
$.ajax({
url: 'webservice.php',
type: 'GET',
contentType: 'text/html',
dataType: 'text',
data: {
data : x
},
success: function(response)
{
alert("data send to webservice");
},
error: function (response)
{
},
});
});
});
</script>
</head>
<body>
<form action='' method='get'>
<input type='text' name='myval' id='myval' >
<input type='submit' value='Go' id='submit' >
</form>
</body>
</html>
I hope this will solve your problem .

Categories

Resources