every bootstrap modal repeat same id in laravel with ajax - ajax

i wrote some code to view my all showing events details using bootstrap modal popup when click read more button. but when i click read more button every response repeats same id.
this is my laravel code
#if(!empty($event))
#foreach($event as $value)
<!-- Single Blog Post -->
<div class="single-blog-post d-flex" id="event_tag">
<div class="post-thumbnail">
<img src="{{asset('images/'.$value->image)}}" alt="">
</div>
<div class="post-content">
<a class="post-title">
#if(strlen($value->title) <= 35)
{{$value->title}}
#else
{{substr($value->title, 0, 35) . '...'}}
#endif
</a>
<div class="post-meta d-flex justify-content-between">
<center><button id="event_button" class="post-cata cata-sm cata-success text_white" data-toggle="modal" data-target="#myModal">Read More</button></center>
</div>
</div>
<input type="hidden" name="event_id" id="event_id" value="{{$value->id}}"></div>
#endforeach
#endif
and this is javascript code to get id and show every id detail.
<script>
$(document).on("click", "#event_button", function() {
var id = $("event_id").val();
console.log(id);
$.ajax({
url: "/event/" + id + "/show",
dataType: "json",
success: function(html) {
$("#event_title").html(html.data.title);
}
});
})
</script>
every time repeats id no 2 when click each event read more button. how can i fix this?

Your code has some mistakes in html too. For example, has fixes ids in html.
'event_id'
'event_button'...
Try this...
<button id="event_button-{!! $value->id !!}" data-target="event_id-{!! $value->id !!}"
<input type="hidden" name="event_id" id="event_id-{!! $value->id !!}"
The code above will fixed the id issue.
Now let's to the JS code... Change the click event:
$(document).on("click", "button.post-cata", function() {
var id = $("#" . $(this).data("target").val();
...
Do you need to associate tags to work with the right value. Avoid to put fixes ids inside a php loop. The html id element must be unique in document.
So, has many ways to do this. In this case, the input hidden fild is not necessary. you can put the id in a attribute in the button tag too.
<button data-id="{!! $value->id !!}...
So in the jquery click event do:
var id = $(this).data('id');
It's more ease and clean.

give class name to button and add attribute to button
<button class="event_button post-cata cata-sm cata-success text_white" data-eventid="{{$value->id}}">Read More</button>
so no need to use hidden input id
now using jQuery :
$(document).on('click','.event_button',function(){
var event_id = $(this).attr("data-eventid");
$("#myModal").modal("show");
$.ajax({
url: "/event/" + event_id+ "/show",
dataType: "json",
success: function(html) {
$("#event_title").html(html.data.title);
}
});
});

Related

Browser-independent way to save text in a TextAreaFor

Using ASP.NET MVC, I have a View that contains a TextAreaFor, where I want users to be able to type in some notes and save them on-the-fly, see notes that were saved there before (whether by them or some other user), as well as modify existing notes (like to add additional notes). Here's what I have....
The divs in the View:
<div class="form-group">
<label for="InternalNotes" class="control-label">Internal Notes</label>
#Html.TextAreaFor(w => w.InternalNotes, new { #class = "form-control" , #id="notes" }) #*this is editable*#
</div>
<div class="form-group">
<div class="col-xs-6">
<button type="button" id="savenotes" class="btn btn-default btn-primary"><span class="glyphicon glyphicon-floppy-disk"></span> Save Request Notes</button>
<div style="color:green; display:none" id="notessuccess">Notes successfully saved</div>
<div style="color:red; display:none" id="noteserror">Notes unable to be saved</div>
</div>
<div class="col-xs-6 text-right">
<button type="submit" id="deletereq" class="btn btn-default btn-primary" value="delete" name="submit"><span class="glyphicon glyphicon-remove"></span> Delete Request</button>
</div>
</div>
So the user could type something into the TextAreaFor, then hit the "savenotes" button, which should save them via Ajax. This is the jQuery for that:
$(document).ready(function () {
$("#savenotes").click(function () {
$("#notessuccess").hide();
$("#noteserror").hide();
var id = #Model.AccessRequestId;
var notes = document.getElementById("notes").textContent; //innerText;
$.ajax({
data: { 'id': id, 'notes': notes },
type: 'POST',
//contentType: "application/json; charset=utf-8",
url: '/Administration/SaveRequestNotes',
success: function (data) {
if (data.success == "ok") {
$("#notessuccess").fadeIn();
} else {
$("#noteserror").fadeIn();
}
},
fail: function (data) {
$("#noteserror").fadeIn();
}
});
});
});
The "innerText" is commented out because that's what I was originally using, but it was only working in Internet Explorer - another user is using Chrome, where he could see the other user's notes that were already there, but when he'd try to save notes in addition to theirs, it would blow it all out so the notes would be empty!
So I changed it to "textContent". That still works in Internet Explorer, but now in both Chrome and Firefox while it won't empty out existing notes, it still won't save new notes added. What is a browser-independent way I can make this work so everyone's notes will get properly saved whatever they are using?
Thank you!
You can use the jQuery val() method get the text user entered to the textarea
var notes = $("#notes").val();
alert(notes);
You might also consider using the Url.Action helper method to generate the correct relative path to your action method.
url: '#Url.Action("SaveRequestNotes","Administration")',

Play framework write Action with Ok(...) that doesn't load new page

Play framework 2.4.x. A button is pressed on my home page that executes some code via Ajax, and returns its results beneath the button without loading a new page. The results wait for a user to input some text in a field and press "submit". Those results Look like this:
<li class="item">
<div>
<h3>Email: </h3>
<a>#email.tail.init</a>
<h3>Name: </h3>
<a>#name</a>
</div>
<div>
<h3>Linkedin: </h3>
<form class="linkedinForm" action="#routes.Application.createLinkedin" method="POST">
<input type="number" class="id" name="id" value="#id" readonly>
<input type="text" class="email" name="email" value="#email" />
<input type="text" class="emailsecondary" name="emailsecondary" value="" />
<input type="text" class="name" name="email" value="#name" />
<input type="text" class="linkedin" name="linkedin" value="" />
<input type="submit" value="submit" class="hideme"/>
</form>
</div>
<div>
<form action="#routes.Application.delete(id)" method="POST">
<input type="submit" value="delete" />
</form>
</div>
</li>
Along with some jquery that slides up a li after submission:
$(document).ready(function(){
$(".hideme").click(function(){
$(this).closest('li.item').slideUp();
});
});
However, since a form POST goes inside an Action that must a return an Ok(...) or Redirect(...) I can't get the page to not reload or redirect. Right now my Action looks like this (which doesn't compile):
newLinkedinForm.bindFromRequest.fold(
errors => {
Ok("didnt work" +errors)
},
linkedin => {
addLinkedin(linkedin.id, linkedin.url, linkedin.email, linkedin.emailsecondary, linkedin.name)
if (checkURL(linkedin.url)) {
linkedinParse ! Linkedin(linkedin.id, linkedin.url, linkedin.email, linkedin.emailsecondary, linkedin.name)
Ok(views.html.index)
}else{
Ok(views.html.index)
}
}
)
Is it possible to return Ok(...) without redirecting or reloading? If not how would you do a form POST while staying on the same page?
EDIT: Here is my attempt at handling form submission with jquery so far:
$(document).ready(function(){
$(".linkedinForm").submit(function( event ) {
var formData = {
'id' : $('input[name=id]').val(),
'name' : $('input[name=name]').val(),
'email' : $('input[name=email']).val(),
'emailsecondary' : $('input[name=emailsecondary]').val(),
'url' : $('input[name=url]').val()
};
jsRoutes.controllers.Application.createLinkedin.ajax({
type :'POST',
data : formData
})
.done(function(data) {
console.log(data);
});
.fail(function(data) {
console.log(data);
});
event.preventDefault();
};
});
This is an issue with the browser's behavior on form submission, not any of Play's doing. You can get around it by changing the behavior of the form when the user clicks submit.
You will first want to attach a listener to the form's submission. You can use jQuery for this. Then, in that handler, post the data yourself and call .preventDefault() on the event. Since your javascript is now in charge of the POST, you can process the data yourself and update your page's HTML rather than reloading the page.
What you need is use ajax to submit a form, check this: Submitting HTML form using Jquery AJAX
In your case, you can get the form object via var form = $(this), and then start a ajax with data from the form by form.serialize()
$.ajax({
type: form.attr('method'),
url: form.attr('action'),
data: form.serialize(),
success: function (data) {
alert('ok');
}
});
In order to accomplish this task, i had to use play's javascriptRouting
This question's answer helped a lot.
I'm not experienced with jquery so writing that correctly was difficult. For those that find this, here is my final jquery that worked:
$(document).ready(function(){
$("div#results").on("click", ".hideme", function(event) {
var $form = $(this).closest("form");
var id = $form.find("input[name='id']").val();
var name = $form.find("input[name='name']").val();
var email = $form.find("input[name='email']").val();
var emailsecondary = $form.find("input[name='emailsecondary']").val();
var url = $form.find("input[name='url']").val();
$.ajax(jsRoutes.controllers.Application.createLinkedin(id, name, email, emailsecondary, url))
.done(function(data) {
console.log(data);
$form.closest('li.item').slideUp()
})
.fail(function(data) {
console.log(data);
});
});
});
Note that my submit button was class="hideme", the div that gets filled with results from the DB was div#results and the forms were contained within li's that were class="item". So what this jquery is doing is attaching a listener to the static div that is always there:
<div id="results">
It waits for an element with class="hideme" to get clicked. When it gets clicked it grabs the data from the closest form element then sends that data to my controller via ajax. If the send is successful, it takes that form, looks for the closest li and does a .slideUp()
Hope this helps

Kendo Mobile - Submit Entire Form

I have a kendo mobile form that I will be using to capture some information from my users.
I would like to post the data to a web service or aspx(test page) using ajax. It seems like overkill to use MVVM for a form that the user fills out and there will be no reads/updates/deletes.
The ajax call happens but I cannot figure out how to post the data . Nothing goes over if i use $(this).serialize(). If I hard code some data, then it works.
There are going to be a lot of controls on the page and i hope i don't have to manually build the form data. I cannot add a <form> tag as it breaks the styling of the page.
If there is a more "kendo" way of doing this please show me how. Thanks
Here is what I have so far.
//Submit Form
function submit_form(e) {
$.post('TestPost.aspx', $(this).serialize(), function (data) {
// This is executed when the call to web service was succesful.
// 'data' contains the response from the request
alert(data);
}).error(function (xhr, ajaxOptions, thrownError, request, error) {
alert('xrs.status = ' + xhr.status + '\n' +
'thrown error = ' + thrownError + '\n' +
'xhr.statusText = ' + xhr.statusText + '\n' +
'request = ' + request + '\n' +
'error = ' + error);
});
e.preventDefault();
}
//Example of html controls
<div id="checks" data-role="view" data-title="Foo" data-layout="checklayout">
<ul data-role="listview" data-style="inset" data-type="group">
<li>Floor
<ul>
<li>
<label for="Foo">
<input type="radio" name="Foo" id="FooOk" value="Ok" />
Ok</label>
</li>
<li>
<label for="Foo2">
<input type="radio" name="Foo" id="FooNotOk" value="NotOk" />
Not Ok</label>
</li>
<li id="Comment1" class="divComment" style="display: none;">
<label>
Comments
<input type="text" name="TextComment" id="TextComment" placeholder="Type Comments" autocomplete="off" tabindex="1" />
</label>
</li>
<li id="C1" class="divComment" style="display: none;">
<label>
Charges
<select id="Charges" name="Charges" >
<option value="nc">test</option>
</select>
</label>
</li>
</ul>
</li>
</ul>
<ul data-role="listview" data-style="inset" data-type="group">
<li>Picture
<ul>
<li>
<label>
Select a Photo
<input type="file" id="kitFile" style="display: none;" />
<a data-role="button" data-click="select" style="float: right;">Select</a>
</label>
</li>
</ul>
</li>
</ul>
</div>
//Submit button
<a data-align="right" data-role="button" class="nav-button" data-click="submit_form">Save</a>
Here $(this) will give u only the button element. The easy way to do this is use the built in MVVM feature in Kendo UI Mobile. create an model as JS object and set data-model attribute of your view as this object. Now on click of the submit button, just send this object to your server using ajax. This way u are reducing the amount of data sent to the server.
Documentation on mobile and mVVM integration: http://docs.kendoui.com/getting-started/mobile/mvvm .
I have used a PageMethod previously.
http://encosia.com/using-jquery-to-directly-call-aspnet-ajax-page-methods/
Would something like this help your cause?
Let's take an example of such a method in the code behind:
[WebMethod]
public static string MyMethod(string Id)
{
return string.Format("Thanks for calling me with id: " + Id);
}
Things to note: the method must be static and decorated with the [WebMethod] attribute.
And on the client side you could invoke this method using the jQuery.ajax() function like this:
$.ajax({
url: 'default.aspx/MyMethod',
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({ ID : ID }),
success: function (result) {
alert(result.d);
}
});
Make sure that in your WebForm you have actually added reference to the jQuery library before using it.
For example:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js" type="text/javascript"></script>

Bootstrap modal email form

I've searched for an answer but could not find any. Maybe someone here can point me to the right direction.
I have a simple modal form (bootstrap). It's meant to work like this.
You enter the form and click Send. The form-info is sent to e-mailadress. When mail is sent new modal with confirmation is displayed.
I've tried to implement this solution: Bootstrap Modal ajaxified
So far i have this:
The modal:
<div class="hide fade modal" id="input-modal">
<form class="form-horizontal well" data-async data-target="#input-modal" action="/some-endpoint" method="POST">
<fieldset>
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3 id="myModalLabel">Modal header</h3>
</div>
<div class="modal-body">
<label>Name</label>
<input id="name" type="text" placeholder="Type your name...">
</div>
<div class="modal-footer">
Cancel
<button type="submit" class="btn btn-primary" value="send"/>Send</button>
</div>
</fieldset>
</form>
The Javascript:
jQuery(function($) {
$('body').on('submit','form[data-async]', function(event) {
alert('submit Event');
var $form = $(this);
var $target = $($form.attr('data-target'));
$.ajax({
type: $form.attr('method'),
url: $form.attr('action'),
data: $form.serialize(),
success: function(data, status) {
$target.html(data);
}
});
event.preventDefault();
});
});
But I need help with sending the input by mail and also sent info back to modal as a confirmation.
I've tried to solve this by myself for several days now, but now I've given up.
If you're using jQuery >= 1.5 look at the documentation here. This will provide you with a place to handle your new modal when the AJAX call returns. So your code would look something like this.
jQuery(function($) {
$('body').on('submit','form[data-async]', function(event) {
alert('submit Event');
var $form = $(this);
var $target = $($form.attr('data-target'));
$.ajax({
type: $form.attr('method'),
url: $form.attr('action'),
data: $form.serialize()
}).done(function(data){
//pop your modal here
$('#your-new-modal').modal('show')
});
event.preventDefault();
});
This is assuming you plan to send the email server side as you can't send it from Javascript. In your example you would have changed the HTML content of the tag to the data returned from the AJAX call instead of opening a new modal. You can find documentation on opening the new modal via Javascript here.
Did not run this so there may be typos.

How to trigger Ajax with flash buttons?

I'm working on something where there are 2 links which triggers some Ajax. However I need to turn the links into Flash buttons (AS3). I've never worked with Ajax before, and I have no idea how this can be done.
Edit:
The Ajax:
<script>
$(document).ready(function() {
$('a.catlink').unbind('click').click(function(e)
{
e.preventDefault();
var link = $(this);
var inputs = [];
var cat_type = $(this).attr('href').replace('#', '');
link.attr('disabled', 'disabled');
inputs.push('cat_type=' + escape(cat_type));
$.ajax(
{
type: "POST",
cache: false,
dataType: "html",
url: window.location.href,
data: inputs.join('&'),
success: function(html)
{
var json = $.parseJSON(html);
if (json['status'] == 1)
{
$('div.listing').html(json['html']);
}
link.removeAttr('disabled');
}
});
});
});
</script>
The HTML
<h1 class="section-head">Products
// **The 2 links*** //
<a class="catlink" href="#cinema">cinema</a> <a class="catlink" href="#smart">smart</a></h1>
<div class="listing">
<ul class="listing">
{foreach from=$products item="product_info"}
<li class="clearfix">
<div class="inner-left">
<img height="68" width="90" src="{$product_info.image}" />
<h2 class="normal mt-5">{if $product_info.price != '0'}${$product_info.price}{else}Click for price »{/if}</h2>
</div>
<div class="inner-right">
<h3 class="mb-0">{$product_info.productName}</h3>
<p class="small mb-5"><span class="quiet">{$product_info.category}</span></p>
<p class="mb-15">{$product_info.description}</p>
<a class="button getprice" href="{$product_info.url}">Buy Now</a>
<br><br>
</div>
</li>
{/foreach}
</ul>
</div>
If you're going to use AS3 then you can use ExternalInterface.call() to call a JavaScript function on the page. Though, using Ajax may not be required if you're using AS3 because you can make use of the URLLoader class to do the same thing (call a PHP script and decode a result).
If you describe more accurately what you want to achieve then I shall provide some example code and clarify a little more.

Resources