How to post form inside load() div - javascript

I have form with $_POST type from second page,on first page i've loaded the form with this code :
<div class="option_dialog" id="search">
<div class="close_option">Search <img onclick="search()" style="float:right;height:20px" src="img/close.png">
</div>
<div id="search_content" style="overflow:scroll;max-height:400px">
<script>
$('#first_page_div').load('second_page.php #second_page_form');
</script>
</div>
</div>
When the function search() called using onclick the above code will excuted and load the form from second page...then i submit the form using this code :
$(function () {
$('#form_id').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: 'second_page.php',
data: $('#form_id').serialize(),
success: function () {
$('#first_page_search_result').load('second_page.php #searched_result');
search_result();
}
});
});
});
When form submited via ajax on first page,the second page should process his/her request and return the searched result on first page and execute search_result() which is another hidden div will be shown after returned result.
please tell me how to make this work?regards

Related

Laravel AJAX response loads wrong route/window

I have two routes:
Route::get('/download/{hash}','DownloadController#exists')->name('exists');
Route::post('/download/{hash}','DownloadController#verify')->name('verify');
Procedure:
Basically the user enters a URL e.g. localhost/download/56iq45agosasa the first route is called and the download.blade.php view is shown. There is a form, where the user has to input a password and when the submit button is clicked, an ajax request is sent to the second (post) route.
The DownloadController#verify returns the json but displays it in a blank window (see screenshot) But it should be returned in the download.blade.php view.
Somehow the form disappears and the ajax success function is not called.
Code snippets Download.blade.php:
#section('content')
<div class="container-fluid mt-5">
<div class="row justify-content-md-center">
<div class="col-md-4">
<form method="POST">
<label for="uploadPassword">Password</label>
<input type="password" name="password" class="form-control" id="uploadPassword" placeholder="Password" required="">
<button id="btn-submit" type="submit" class="btn btn-success mt-2">Submit</button>
{{ csrf_field() }}
</form>
</div>
</div>
</div>
#endsection
#push('scripts')
<script type="text/javascript">
$(".btn-submit").click(function(e){
e.preventDefault();
let password = $("input[name=password]").val();
$.ajax({
type:'POST',
url:"",
data:{
password:password
},
success:function(data){
console.log("I don't get shown");
//alert(data.success + " " + data.matches);
}
});
});
</script>
#endpush
DownloadController:
class DownloadController extends Controller
{
public function exists(Request $request, $hash)
{
// Some private mysql queries
// Return the hash to the download view
return view('download',[
'hash' => $hash
]);
}
public function verify(Request $request, $hash)
{
return response()->json(
['success'=>'Got Simple Ajax Request.']
);
}
}
So there are two things that will help improve this code:
Wrap the listener in a document.ready function to ensure it's attached when the button is available in the page. This is necessary if #push will make the script end up above the form declaration in the page.
Listen for the form submit event so you can capture the submit via any of the possible ways that one can submit a form (e.g. by pressing ENTER on an input)
#push('scripts')
<script type="text/javascript">
$(function () {
$("form").on('submit', function (e) {
e.preventDefault();
let password = $("input[name=password]").val();
$.ajax({
type:'POST',
url:"",
data:{
password:password
},
success:function(data){
console.log("I don't get shown");
//alert(data.success + " " + data.matches);
}
});
});
});
</script>
#endpush
The problem here is that the form gets submitted.
Instead of overriding button click with your jQuery function, use it to change submit handler like so
Prevent Default on Form Submit jQuery
Make sure you put id on the form.

Submit form input value on page load with ajax

I have form and a input in it and I want to send its value to my controller.I wanna send its value when a page load or refresh current page using ajax and jquery because my page reload when I write submit function in body tags onload event.
Here is my code:
<form method="post" id="counterForm" name="counterForm">
#csrf
<input type="number" name="count" id="count" value="{{ $visit->counts }}">
</form>
Script code:
$(window).load(function(){
var n=document.getElementById("count").value;
$.ajax({
type:'POST',
url:'/count',
data:n,
});
});
My controller file :
public function count(Request $request)
{
$value=($request->count)+1;
DB::table('visitorcounter')->update(['counts'=>$value]);
}
That was my code but its not working...Thanks.
you can use .submit() :
Bind an event handler to the "submit" JavaScript event, or trigger
that event on an element.
you code would be like :
$(window).load(function() {
$('#counterForm').submit(function(){return true;});
});
Check out this example: :
$(window).load(function(){
// this is the id of the form
var url = "results.php"; // the script where you handle the form input.
$.ajax({
type: "POST",
url: url,
data:$( "#myformR" ).serialize(),
dataType: "html", //expect html to be returned
success: function (response) {
$("#prores").html(response);
}
});
});
I found it ... We can create a visitor counter very very simply by using a table with one integer column and a DB::table('test')->increment('count'); in AppServiceProvider Boot function.

How do I submit Ajax form from javascript and update target div?

I have a bootstrap modal popup, with an ajax helper form on which I need to do some js validation prior to submitting. If validation fails, I'm showing some extra things on the form. If my validation passes I want to submit the form, and update a specific div with a PartialView. To do the validation, I'm calling a js function from a button on the form, and passing in the form. If my validation passes, I call the form's submit.
This works, but the PartialView displays full page, rather than in the target div. The form works properly and updates the target div when I submit directly from a submit input on the form instead of submitting from the js function.
How do I update my target div when submitting from js function?
See code:
function validateActionItem(sender) {
var $formToSubmit = $(sender).closest('form');
$formToSubmit.submit();
}
<div id="MyDivContainer" class="col-lg-12">
#Html.Action("MyPartial", "MyController", new { ID = Model.ID })
<div class="modal fade" id="MyModal">
<div class="modal-dialog modal-lg">
<div class="modal-content">
#using (Ajax.BeginForm("MyAction", "MyController",
new { ID = Model.ID },
new AjaxOptions {
UpdateTargetId = "MyDivContainer",
OnSuccess = "closeModal()"
},
new { #id = "MyForm"}))
{
<div class="modal-body">
<!-- My form fields -->
</div>
<div class="modal-footer">
<button class="btn btn-primary" role="button"
type="button" onclick="validate($(this))">
Validate Submit
</button>
</div>
}
</div>
</div>
</div>
My _Layout.cshtml contains...
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/bundles/jqueryval")
<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script>
The MyAction action returns PartialView(model).
Can anyone point to what I'm doing wrong, and why my PartialView displays full page when submitting the form from javascript but properly updates the target div when I replace the button with a regular input submit on the form?
UPDATE
I have refactored the submit like so, but it's never getting called for some reason?
jQuery().ready(function () {
$("#MyForm").submit(function (e) {
$.ajax({
url: "/MyController/MyAction",
type: "POST",
dataType: "html",
contentType: false,
data: $("#MyForm").serialize(),
success: function (partialViewResult) {
closeModal();
$("#MyDivContainer").empty().append(partialViewResult);
}
});
});
});
UPDATE 2
I discovered that the jquery script must be after the modal popup in my cshtml, so now I'm reaching the submit event of my input button. However, I can't get to my controller action... the ajax call errors.
$("#MyForm").submit(function (e) {
e.preventDefault();
var id = $('#ID').val();
alert("submit function called");
alert("ID: " + id);
$.ajax({
url: "/MyController/MyAction",
type: "POST",
dataType: "html",
data: { ID: (id)},
error: alert("Error!")
});
});
I hit the "Error" alert, and don't know how to debug this to figure out what's wrong.
I've got it working. Thanks everyone for the help. Here's the code:
For whatever reason, the script has to be placed after the modal popup markup.
<script type="text/javascript">
$("#MyForm").submit(function (e) {
e.preventDefault();
//getting fields to be checked
if //checking failed validations
{
//doing some things if val fails
}
else
{
var id = $('#ID').val();
$.ajax({
url: "/MyController/MyAction",
type: "POST",
dataType: "html",
data: {ID: id},
success: function (partialViewResult) {
closeMyModal();
$("#MyDivContainer").empty().append(partialViewResult);
}
});
}
});
</script>

load form using ajax then again submit using ajax

I have a page where I'm displaying some information. You can select a option and the page will then display a form by loading the form using ajax response:
$("body").on("change", "#patient_id", function(event){
var prescription_id = $(this).val();
event.preventDefault(); // disable normal link function so that it doesn't refresh the page
var curr_data = {
action: 'refferedcall',
prescription_id: prescription_id,
dataType: 'json'
};
$.post(hmgt.ajax, curr_data, function(response) {
$('.prescription_content').html(response);
return true;
});
});
This works fine. But this view is a form. I want to then submit the included form with Ajax as well. But I can't seem to do it. I think it is because if I set up a button handler for the form it doesn't work as the form isn't present when the main page and JQuery script is loaded.
So to be clear, I'm loading this div onto my main page using JQuery and Ajax load. I then want to simply submit this form with Ajax also.
<div class="prescription_content">
<div class="title">Submit News</div>
<form role="form" id="ref_form" name="ref_form_p">
<div class="form-group">
<label for="pat_ref_hosp">Hospital to Refer:</label>
<input type="text" class="form-control" id="pat_ref_hosp" name="pat_ref_hosp" value="<?php if(!empty($result->reffer_hospital)){ echo $result->reffer_hospital; }?>">
</div>
<input type="hidden" class="form-control" id="pres_note" name="pres_note" value="<?php echo $result->priscription_id ;?>">
<button type="button" id="<?php echo $result->priscription_id ;?>" class="btn btn-success reffering_status">Refer Now</button>
</form>
</div>
TIA
Then I submitted form again using ajax through below button click event:
$("body").on("click", ".reffering_status", function(event){
event.preventDefault(); // disable normal link function so that it doesn't refresh the page
var prescription_id = $("#pres_note").val();
var pat_ref_hosp = $("#pat_ref_hosp").val();
var curr_data = {
action: 'reffering_status',
dataType: 'json',
prescription_id: prescription_id,
pat_ref_hosp : pat_ref_hosp,
};
console.log(curr_data);
)};
Here is log displaying
Object {action: "reffering_status", dataType: "json", prescription_id: "1", pat_ref_hosp: ""}
pat_ref_hosp is empty
I don't know how to display ajax in jsfiddle
https://jsfiddle.net/3ggq3Ldm/
Yes the way you are doing it will not work because the contents of the DIV you are loading-in is not loaded into the DOM when your initial
$("body").on("click", ".reffering_status", function(event){});
call is made.
If I am understanding you correctly, this is the behaviour you want to achieve:
$("#patient_id").on("change", function(event) {
var prescription_id = $(this).val();
event.preventDefault(); // disable normal link function so that it doesn't refresh the page
var curr_data = {
action: 'refferedcall',
prescription_id: prescription_id,
dataType: 'json'
};
$.post(hmgt.ajax, curr_data, function(response) {
$(".prescription_content").html(response);
$(".reffering_status").on("click", function(event){
event.preventDefault(); // disable normal link function so that it doesn't refresh the page
var prescription_id = $("#pres_note").val();
var pat_ref_hosp = $("#pat_ref_hosp").val();
var curr_data = {
action: 'reffering_status',
dataType: 'json',
prescription_id: prescription_id,
pat_ref_hosp : pat_ref_hosp
};
console.log(curr_data);
)};
return true;
});
});
You simply need to run the code that attaches your click listener AFTER the DOM has already been updated with the new information.
Please let me know if this code does what you were intending it to.

using jquery to make ajax call and update element on form submit

Here is my html form
<div id=create>
<form action=index.php method=get id=createform>
<input type=text name=urlbox class=urlbox>
<input type=submit id=createurl class=button value=go>
</form>
</div>
<div id=box>
<input type=text id=generated value="your url will appear here">
</div>
Here is the javascript im trying to use to accomplish this;
$(function () {
$("#createurl").click(function () {
var urlbox = $(".urlbox").val();
var dataString = 'url=' + urlbox;
if (urlbox == '') {
alert('Must Enter a URL');
}else{
$("#generated").html('one moment...');
$.ajax({
type: "GET",
url: "api-create.php",
data: dataString,
cache: false,
success: function (html) {
$("#generated").prepend(html);
}
});
}return false;
});
});
when i click the submit button, nothing happens, no errors, and the return data from api-create.php isnt shown.
the idea is that the new data from that php file will replace the value of the textbox in the #box div.
i am using google's jquery, and the php file works when manually doing the get request, so ive narrowed it down to this
Because you're binding to the submit click instead of the form's submit.. try this instead:
$('#createForm').submit(function() {
// your function stuff...
return false; // don't submit the form
});
Dan's answer should fix it.
However, if #createurl is not a submit/input button, and is a link styled with css etc., you can do this:
$('#createurl').click(function () {
$('#createForm').submit();
});
$('#createForm').submit(function () {
// all your function calls upon submit
});
There is great jQuery plugin called jQuery Form Plugin. All you have to do is just:
$('#createform').ajaxForm(
target: '#generated'
});

Categories