Here is my HTML. Just a simple form:
<form>
Username:
<input type="text" id="username"/>
<br/>
Password:
<input type="password" id="password"/>
<br/>
<input type="submit" id="submit" value="submit"/>
</form>
Here is my JS associated with it:
function init(){
$("#submit").click(function() {
var url = "http:example.com/mail";
alert("what?");
$.ajax(url, {
type : 'post',
data : {
'username' : $("#username").val(),
'password' : $("#password").val()
},
success : function() {
alert("done");
}
});
});
}
After I clicked on the submit button, the $.ajax function is supposed to do a post to the URL where I keeps my server running.
However, from my server side log or firebug network monitoring, I didn't see any sign of the POST method. (The first alert was triggered but the second wasn't.)
They are two different applications that I developed, so after I did some research, here is one explanation:
Since $.ajax() uses XMLHttpRequest, it is subject to XHR's cross-domain restriction. Are your SiteA and SiteB on different hosts/ports? If so, you're seeing the expected behavior.
Is that so? If so, is there any workaround?
You need return false; at the end of the click handler to prevent the default submission of the form. Although once you prevent the form from submitting, you will still have the cross-domain restriction, which is not trivial to solve. Look into jsonp for a possible solution.
Change your event handler to this...
function init(){
$("#submit").click(function(event) {
event.preventDefault();
var url = "http:example.com/mail";
alert("what?");
$.ajax(url, {
type : 'post',
data : {
'username' : $("#username").val(),
'password' : $("#password").val()
},
success : function() {
alert("done");
}
});
});
}
This will stop the form from actually doing a full POST to the server.
I think this will work
function init(){
$("#submit").click(function(event) {
event.preventDefault();
var url = "http:example.com/mail";
alert("what?");
$.ajax(url, {
type : 'post',
data : {
'username' : $("#username").val(),
'password' : $("#password").val()
},
cache: 'false',
async: 'false',
success : function() {
alert("done");
}
});
});
}
Related
I'm trying to refresh a div when submiting a form, but I'm having a 404 error
jquery.min.js:2 POST Https://xxxx.com.ar/Home/#Url.Action(%22Pagination2%22,%22Home%22) 404 (Not Found)
This is my form:
<form action="~/Home/Pagination" method="post" id="ajax_submit_siguiente">
<button class="siguiente-imagen #ViewData["btnSiguiente"]" id="btnSiguientePaginacion" value="#item.getNumeroEntrega()" type="submit">
Siguiente
</button>
</form>
And this is my js:
$(document).ready(function () {
$("#ajax_submit_siguiente").submit(function (e) {
// prevent regular form submit
e.preventDefault();
var data = {
'paginacion': 'siguiente',
'entrega': $("#btnSiguientePaginacion").val()
}
$.ajax({
url: '#Url.Action("Pagination","Home")',
type: 'POST',
data: data,
success: function (result) {
console.log(result);
// refresh
$(" #container-galeria-imagenes").load(window.location.href + " #container-galeria-imagenes ");
},
error: function (err) {
console.log(err);
}
});
})
});
And this is my JsonResult...
[HttpPost]
public async Task<JsonResult> Pagination(string paginacion, string entrega)
{
List<PedidoViewModel> list;
// Working code....
return Json(list);
}
I'm very new with ajax, I read the documentation and was like this how to refresh a div after sending a submit...
since its a form submit rather than creating the object serialize the form and pass it to the server. also just to double confirm check the conversion of '#Url.Action("Pagination","Home")'is correct using the browser debugger tool and also make sure the routing is implemented correctly in Server side
$(document).ready(function() {
$('#myForm').submit(function(event) {
event.preventDefault(); // prevent the form from submitting normally
$.ajax({
type: 'POST',
url: '/my/url',
data: $('#myForm').serialize(),
success: function(response) {
$('#myDiv').html(response); // update the content of the div with the response
}
});
});
});
I have Laravel web App contain search on database .
first I have this input :
<input class="form-control mr-sm-2" type="text" id="search_me" placeholder="{{__('home.Search')}}" aria-label="Search" onkeyup="myFunction()">
<input type="hidden" id="course_id" value="{{$course->id}}">
so I create this JavaScript function :
<script>
function myFunction() {
var search_me=document.getElementById('search_me').value;
var id=document.getElementById('course_id').value;
$.ajax({
method : 'POST',
url : "{{route ('search')}}",
dataType : 'json',
data:{
'_token':'{{csrf_token()}}',
'search_data':search_me ,
'course_id':id,
},
success:function(data){
console.log(data);
}
});
}
</script>
then I create the route like this :
Route::get('/search', [App\Http\Controllers\user\User_controller::class, 'search_data'])->name('search');
and the controller method of :
public function search_data(Request $request)
{
$output="";
$questions = Question::table('questions')->where('course_id',$request->course_id)->where('question' ,'LIKE' ,'%'.$request->search_data."%")->get();
return json_nencode($questions);
}
when I type on the text input I get error :
main.js?attr=DEbA4C86cFywU9oORVUcm4fay4bVMB7MeKBvEkL0Iy2jpADxMlMEszxyl6A-4lWVGp58XG2e-YEmLqgl2mGpQg:1078 POST http://127.0.0.1:8000/ku/search 405 (Method Not Allowed)
inside this error I found this :
return fun.apply(this, [].slice.call(arguments));
I followed many examples like this ,I don't know where is my error ?
Update
I made some changes :
I change ajax request to :
var route = 'route("search"'+'/'+search_me+'/'+id;
$.get("{{"+route+"}}", function(data,status){
console.log( data );
});
also I change the route to get.
then I change the controller to :
public function search_data($search , $id)
{
$output="";
$questions = Question::table('questions')->where('course_id',$id)->where('question' ,'LIKE' ,'%'.$search."%")->get();
return json_nencode($questions);
}
Now when I keyup the Input text I get this :
your ajax method is post but your route is get
change route to post
Route::post('/search', [App\Http\Controllers\user\User_controller::class, 'search_data'])->name('search');
or your ajax to get
$.ajax({
method : 'GET',
url : "{{route ('search')}}",
dataType : 'json',
data:{
'search_data':search_me ,
'course_id':id,
},
success:function(data){
console.log(data);
}
});
Thankfully I solved it by this way :
the route :
Route::get('/search'.'/{search}/{course}', [App\Http\Controllers\user\User_controller::class, 'search_data'])->name('search');
the js function :
function myFunction(id) {
var search_me=document.getElementById('search_me').value;
var route = "{{URL::to('search')}}"+'/'+search_me+'/'+id;
if(search_me != ""){
$.get(route, function(data,status){
console.log(data);
});
}
}
</script>
try to add this code before using $.ajax request
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': "{{ csrf_token() }}"
}
});
let me know if it helps and it's also documented on the official laravel docs.
here is the LINK
after this, you don't need to add __token inside the $.ajax request.
For some reason if I use POST instead of GET in my .ajax call it doesn't reach the Controller.
From what I read multipar/form-data can send non-file inputs as well, hence this should work.
I've tried a number of variations and it doesn't work, and now I'm curious as a dog seeing a mirror for the first time !
Here is the code
Here is my Form which I've cut down to the bare bones :
<form id="forward-post" enctype="multipart/form-data" action="">
<input type="hidden" value="{{$post->id}}" name="val[postid]" />
<button class="post-forward-button" class="btn btn-sm btn-success" id="post-submit-button"><i class="icon ion-compose"></i> Forward</button>
</form>
Here is the Javascript function being called :
$(document).on('submit', '#forward-person', function (e)
{
e.preventDefault(); // To prevent page refresh after ajax call
$.ajax({
url : baseUrl + 'post/forward',
type : 'POST',
data : new FormData(this),
contentType : false,
cache : false,
processData : false,
success : function(data) {
console.log('Success function of the ajax call');
}
});
});
Controller
public function forward()
{
Log::info('Inside forward()');
if (\Input::has('val'))
{
Log::info('Val found');
}
return 0;
}
The route and everything works for GET, but I'm posting it here again, for completion sake :
Route::get('forward', [
'uses' => 'App\Controllers\PostController#forward'
]);
I also noticed that when I'm doing a GET, the controller doesn't find 'val' in the Input.
Any clue, what I'm doing incorrectly ?
since it is making ajax post request, your route has to be
Route::post('forward', [
'uses' => 'App\Controllers\PostController#forward'
]);
<html>
<body>
<form method="POST">
<label>username</lable>
<input id="username" name="username" type="text">
<label>emailid</lable>
<input id="emailid" name="emailid" type="text">
<button id="enter" type="submit">submit</button>
</form>
<script type="text/javascript">
$(document).ready(function () {
var userName = $("#username").val();
var emailId = $("#emailid").val();
$($enter).click(function () {
$.ajax({
type: 'POST',
url: ".....rest service url....",
dataType: JSON,
data: {
"UserName": userName,
"EmailId": emailId
},
success: function (data) {
alert("success");
}
error: function (e) {
alert("error" + e)
}
});
});
});
</script>
</body>
</html>
I'm trying to post the form field in rest service which expects a JSON response.
I'm getting an alert error message (object Object)
I'm not getting where the error is.
You can try $.post instead of $.ajax
$.post( "your url",{ UserName: userName, EmailId: emailId }, function( data ){
alert("Success");
});
Just make sure that parameters you are passing matches with your REST service.
$($enter).click(function () {
this part of code looks invalid, provide a correct selector to the click function.
First change this
$($enter).click(function to
$("#enter").click(function () {
Are you sure the the service you written for this task is a post service...some times i do the mistake like post data and write service for getting data.If you can show your service structure it will help to have a better insight.
i have the following form,
<form action="localhost/xyz.aspx" method = "post" enctype="multipart/form-data">
<input type="text" name="name">
<input type="text" name="age">
<input type="text" name="submit">
</form>
My requirement is to complete the action using AJAX & jQuery and without a form tag explicitly added in html.
TIA
update1
i have tried
function onButtonClicked()
{
$.ajax({
type: 'POST',
url: "xyz.aspx",
data : {"name" : "john", "age" : "22"},
crossDomain : true,
beforeSend: function (x) {
if (x && x.overrideMimeType) {
x.overrideMimeType("multipart/form-data");
}
},
success: function(data){
alert("Success");
},
error: function(data){
alert("on start process error");
}
});
}
sample.html
<html>
<body>
<input type="button" onclick = "onButtonClicked()">
</body>
</html>
It returns Unsupported Media Type 415.
I want send form data using ajax
You can select the individual inputs and use them in an array to post. This way doesn't need a wrapper:
// Click button with ID #submit
$("button#submit").click(function () {
// Send to submit.php
$.post("submit.php", {
// Send these values via POST
val1: $("#val1").val(), // Get value from input #val1
val2: $("#val2").val() // Get value from input #val2
}, function(result){
// Output result to #output element
$('#output').html(result);
});
});