Javascript onClick function doesnt work - javascript

I build some little mvc asp.net project to check some function of the OutBrain API.
I made a input type of text which get MarketerI ID and should return his name (from the server). But when i push the button nothing happen and i really dont have a clue why and whould glad to get some help !
Thanks
My code :
outBrain.js File
$("#buttonB").on('click', function () {
getMarketer();
});
function getMarketer() {
$.ajax({
url: "/home/GetOutBrainMarketers",
data: { id: $("marketerID").val() },
success: function (result) {
var marketer = JSON.parse(result);
document.getElementById("nameMarketer").innerHTML = (marketer.name);
}
});
}
cshtml File (which include the script file path):
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="~/Scripts/outBrain.js"></script>
#{
ViewBag.Title = "Home Page";
}
<br />
<div class="details">
<label>Enter Marketer ID</label>
<input type="text" class="form-control" id="marketerID">
<input type="button" class="btn btn-default" value="OK" id="buttonB" />
<section class="details">
<div class="name">
<label>Name</label>
<label id="nameMarketer"></label>
</div>
</section>
</div>
There is also the code of the controller but dont see a point to add it.

Try:
$("#buttonB").click(function () {
getMarketer();
});

Your selector in ajax is missing a #.
It is $("marketerID").val(), should be $("#marketerID").val();
Could this be the problem?

Change this code
$.ajax({
url: "/home/GetOutBrainMarketers",
data: { id: $("marketerID").val() },
success: function (result) {
var marketer = JSON.parse(result);
document.getElementById("nameMarketer").innerHTML = (marketer.name);
}
});
by this :
$.ajax({
url: "/home/GetOutBrainMarketers",
data: { id: $("marketerID").val() },
success: function (result) {
var marketer = JSON.parse(result);
$("#nameMarketer").html(marketer.name);
}
});
And Good luck

I think, you have to put the your js files at the end, so it wwil be like this:
#{
ViewBag.Title = "Home Page";
}
<br />
<div class="details">
<label>Enter Marketer ID</label>
<input type="text" class="form-control" id="marketerID">
<input type="button" class="btn btn-default" value="OK" id="buttonB" />
<section class="details">
<div class="name">
<label>Name</label>
<label id="nameMarketer"></label>
</div>
</section>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="~/Scripts/outBrain.js"></script>
I suggest you use #section, so your code will be more organize.

Related

Javascript - After creating a div, Ajax is not working

I have a button for a form. When I click the button, the form is created. After being created, the form is not working with Ajax. My script codes are in here. My #testform is not wrong because it's working without creating form. Do you have any ideas?
function addDiv() {
var panel = document.querySelector(".add_new");
var div = document.createElement("div");
div.innerHTML = '<br> <form id="testform" method="POST"> <div class="row" style="padding-left:10rem;"> <div class="col-md-4"> <input type="text" class="form-control" value="" placeholder="Başlık" name="yeniBaslik" required></div> <div class="col-md-4"> <input type="text" placeholder="Açıklama" name="yeniAciklama" class="form-control" value="" name="" required> </div> <div class="col-md-2 text-left"> <button type="submit" class="btn btn-success btn-animated btn-wide addToDatabase">Add to the Database</button> </div> </row> </form> <br>';
panel.appendChild(div);
}
$("#testform").submit(function(e) {
e.preventDefault();
var formData = new FormData($("#testform").get(0));
$.ajax({
url: 'config.php',
type: 'POST',
data: formData,
contentType: false,
processData: false,
success: function() {
setTimeout(
function() {
$(".addToDatabase").html("Successfully.");
}, 1000);
}
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button onclick="addDiv()"> Create a form </button>
<div class="add_new"></div>
Since second statement is executed before "div" is created, submit event is not being listened to on the new <form>
function addDiv() {
/*...*/
panel.appendChild(div);
$("#testform").submit(function(e) { /*...*/ });
}

How can I get my search bar work with Google?

I have this search bar and I can't connect it to Google as a search functionality, I tried with this guy's code but I couldn't:
<form id="frmSearch" action="index.html" class="searchform order-sm-start order-lg-last">
<div class="form-group d-flex">
<input type="text" class="form-control pl-3" placeholder="Buscar">
<button type="submit" placeholder="txtsearch" class="form-control search"><span class="fa fa-search"></span></button>
</div>
</form>
Thanks in advance!
You could use an AJAX call to a php page where you are going to implement cURL to get data from google searching url!
Of course you will need to code your own cURL in PHP: PHP + curl, HTTP POST sample code?
here you can find how to implement it!
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
document.addEventListener('DOMContentLoaded', () => {
const form = document.querySelector("form#frmSearch");
form.onsubmit = function() {
let keyword = encodeURIComponent(this.querySelector("input#keyword").value);
$.ajax({
url: `./php_curl_file.php?q=${encodeURIComponent(keyword)}`,
type: 'GET',
error: (err) => {
throw new Error(err);
},
success: (searchData) => {
console.log( searchData );
}
});
return false;
}
} );
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="frmSearch" class="searchform order-sm-start order-lg-last">
<div class="form-group d-flex">
<input type="text" id="keyword" class="form-control pl-3" placeholder="Buscar">
<button type="submit" placeholder="txtsearch" class="form-control search">
<span class="fa fa-search"></span> Search
</button>
</div>
</form>

Calling JQuery Ajax Functions in Foreach loop - Need assitance

I am currently studying programming and trying to build a website with .Net Core.
I have the following issue. I am not familiar with JavaScript that much and I have two JQuery/AJAX functions on my Index page. One of the function is for the posts likes/dislikes and the other for posts comments.
My ViewModel contains a collection of Posts:
public IEnumerable<IndexPostViewModel> Posts { get; set; }
public int PagesCount { get; set; }
public int CurrentPage { get; set; }
Into my view I am looping through each Post and in it, through each Comment.
#foreach (var post in Model.Posts)
{
<div class="post-content">
<img src=#post.ImageUrl width="500" height="500" alt="post-image" class="img-responsive post-image" />
<div class="post-container">
<img src="http://placehold.it/300x300" alt="user" class="profile-photo-md pull-left" />
<div class="post-detail">
<div class="user-info">
<h5>#post.User.UserName <span class="following">following</span></h5>
<p class="text-muted">Post published at: #post.CreatedOn</p>
</div>
<div class="reaction">
<a class="btn text-green" href="#" method="post" onclick="sendVote(#post.Id, true)"><div class="icon ion-thumbsup" id="upVotes">#post.UpVotes</div></a>
<a class="btn text-red" href="#" method="post" onclick="sendVote(#post.Id, false)"><div class="fa fa-thumbs-down" id="downVotes">#post.DownVotes</div></a>
</div>
<div class="line-divider"></div>
<div class="post-text">
<p>#post.Text</p>
</div>
<div class="line-divider"></div>
#foreach (var comment in post.Comments)
{
<div class="post-comment">
<img src="http://placehold.it/300x300" alt="" class="profile-photo-sm" />
<p>#post.User.Email<i></i> #comment.Text</p>
</div>
}
<form id="myForm" asp-controller="Comment" asp-action="Create" method="post">
<input type="hidden" name="PostId" id="postId" value="#post.Id" />
<textarea name="text"></textarea>
<input type="submit" value="Submit Comment" />
</form>
</div>
</div>
</div>
And these are the functions in the Scripts section:
#section Scripts {
function sendVote(postId, isUpVote) {
var json = { postId: postId, isUpVote: isUpVote };
$.ajax({
url: "/api/votes",
type: "POST",
data: JSON.stringify(json),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
$("#upVotes").html(data.upVotes);
$("#downVotes").html(data.downVotes);
}
});
}
// wait for the DOM to be loaded
$(document).ready(function () {
// bind 'myForm' and provide a simple callback function
$('#myForm').each.ajaxForm(function () {
alert("You have just posted a comment");
document.location.reload(true);
});
});
</script>
}
My issue is that both functions are working correctly only for the first post. Can you please assist on how to modify the functions to be applied for each element in the loop?
Thanks in advance.
the problem is simple.
your selector and ids are not unique
id can only be defined for one element, same id on multiple/same elements will cause this issue.
the link tag has a common id for all records, it needs to be unique.
make the ids unique , i added #post.Id with ids, this will make each unique
<div class="reaction">
<a class="btn text-green" href="#" method="post" onclick="sendVote(#post.Id, true)"><div class="icon ion-thumbsup" id="upVotes_#post.Id">#post.UpVotes</div></a>
<a class="btn text-red" href="#" method="post" onclick="sendVote(#post.Id, false)"><div class="fa fa-thumbs-down" id="downVotes_#post.Id">#post.DownVotes</div></a>
</div>
and in you js change the selector by adding id
function sendVote(postId, isUpVote) {
var json = { postId: postId, isUpVote: isUpVote };
$.ajax({
url: "/api/votes",
type: "POST",
data: JSON.stringify(json),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
$("#upVotes_"+postId).html(data.upVotes); // change here
$("#downVotes_"+postId).html(data.downVotes);
}
});
}
and also for myform do the same, you dont need id for form, but if you want just add the #post.Id to id,
<form id="myForm" class="myform" asp-controller="Comment" asp-action="Create" method="post">
<input type="hidden" name="PostId" id="postId" value="#post.Id" />
<textarea name="text"></textarea>
<input type="submit" value="Submit Comment" />
</form>
and in event change id to class to make it dynamic,
$('.myForm').each.ajaxForm(function () {
// $(this) will give you access to the specific form only
alert("You have just posted a comment");
document.location.reload(true);
});

HTML Form Submit does not reach my javascript

I am trying to reach my javascript code when I press the submit button within my form and it is not triggering my javascript code at all.
So I got this form within my Bootstrap Modal using the following code:
<form id="updateUserForm">
<div class="form-group">
<label for="firstName">First name:</label>
<input type="text" class="form-control" id="firstnameModalInput" />
</div>
<div class="form-group">
<label for="middleName">Middle name:</label>
<input type="text" class="form-control" id="middlenameModalInput" />
</div>
<div class="form-group">
<label for="lastName">Last name:</label>
<input type="text" class="form-control" id="lastnameModalInput" />
</div>
<div class="form-group">
<label for="mobileNumber">Mobile number:</label>
<input type="text" class="form-control" id="mobilenumberModalInput" />
</div>
<div class="form-group">
<label for="email">Email:</label>
<input type="text" class="form-control" id="emailModalInput" />
</div>
<div class="form-group">
<label for="Enabled">Enabled:</label>
<input type="checkbox" class="form-control" id="enabledModalInput" style="width:34px" />
</div>
<div class="modal-footer">
<input type="submit" class="btn btn-default" data-dismiss="modal" id="submit" value="Apply" />
</div>
</form>
And the javascript code I have:
$('document').ready(function(){
$("#updateUserForm").submit(function (event) {
console.log("Method entered");
event.preventDefault();
var serialize = $("#updateUserForm").serialize();
$.ajax({
type: "POST",
data: serialize,
url: "/Dashboard/UpdateUser",
datatype: JSON,
succes: function (data) {
console.log("succes!");
console.log(data);
},
error: function (data) {
console.log("error");
console.log(data);
}
})
})
})
I have another function in that javascript that is used to populate the input fields and that works fine, so I guess the HTML can reach the javascript file. But it does not reach the javascript submit function (it doesn't do the console.log for example) . Does anyone have an idea what I am doing wrong?
EDIT:
I have been playing around a bit more, and it seems that I can acces the javascript method when I try to reach it from outside of the bootstrap modal, it goes wrong somewhere within the modal.
Use return false instead of prevent default end of the function and change the submit function with on function.
$('document').ready(function(){
$("#updateUserForm").on("submit", function () {
console.log("Method entered");
var serialize = $("#updateUserForm").serialize();
$.ajax({
type: "POST",
data: serialize,
url: "/Dashboard/UpdateUser",
datatype: JSON,
succes: function (data) {
console.log("succes!");
console.log(data);
},
error: function (data) {
console.log("error");
console.log(data);
}
})
return false;
})
})
try this
$("#updateUserForm").on('submit', function (e) {
e.preventDefault();
});
Can you please try below code. and please check post URL"/Dashboard/UpdateUser" is right?
$("#UpdateUserForm").submit(function (e)
{
var isValid = $("#UpdateUserForm").valid();
if (!isValid)
return;
//This is important as it prevents the form being submitted twice
e.preventDefault();
$.ajax({
type: "POST",
url: "/Dashboard/UpdateUser",
data: $("#UpdateUserForm").serialize(),
success: function (response)
{
var status = '';
status = response.Status;
console.log("succes!");
console.log(data);
}
})
.error(function () {
console.log("error");
console.log(data);
});
});
$("#updateUserForm").on('submit', function (e) {
e.preventDefault();
});
Or use action properties in form.

Call a method in a .cs from javascript

I'm stacking with the following problem: I want to create a Template witch contains forms (3 textboxes and a button).Inside this template, through a javascript, have to call a function (CRUD method) that is inside a .cs.
So...that's one of my CRUD function in EmployeeBL.cs :
[WebMethod]
public static bool CreateEmployee(int Id, string Nome, string Cognome)
{ ...}
while here it's my Employee.tpl witch should call CreateEmployee():
<div class="container" style="max-width: 400px">
<form class="form-horizontal" method="post" id="Form"
data-bv-feedbackicons-valid="glyphicon glyphicon-ok"
data-bv-feedbackicons-invalid="glyphicon glyphicon-remove"
data-bv-feedbackicons-validating="glyphicon glyphicon-refresh"
data-bv-submitbuttons='button[type="submit"]'>
<div class="form-group">
{Message}
</div>
<div class="form-group">
<input type="text" class="form-control" id="Id" placeholder="User name" value="{Model.Id}"
data-bv-notempty-message ="{UserNameNotEmptyMessage}" />
</div>
<div class="form-group">
<input type="text" class="form-control" id="FirstName" placeholder="First Name" value="{Model.FirstName}"
data-bv-notempty-message="{FirstNameNotEmptyMessage}" />
</div>
<div class="form-group">
<input type="text" id="LastName" placeholder="Last Name" value="{Model.LastName}" />
</div>
<div class="form-group">
<button type="submit" class="btn btn-default" value="Submit" id="myButton" >Create Employee</button>
</div>
Now always inside this tpl put a script like here:
<script type="text/javascript">
$(document).ready(function ()
{
$("#Form").bootstrapValidator();
$("#myButton").click(function(){
var Id=foo($('#Id').val());
var FirstName= foo($('#FirstName').val());
var LastName=foo($('#LastName').val());
});
});
Summarizing: i need to create an Employee (with Id,LastName,FirstName) that goes to write on my DB via clicking on Button
So my question is how to set visible the namespace of EmployeeBL.cs and how to call it's method CreateEmployee() inside script (clicking on Button)? Thx in advance!!
#Yuri: First of all Ty so much for help.Same time i found out that is better avoid this way. It was my fault cause i skipped telling you i'm working with ACSPNET with Owin and MVC pattern. So i created MVC files and a Business Logic one..In Controller under the function Invoke() i have to find a method to call EmployeeBL.CreateEmployee() and same time return a template like here:
public class EmployeeController : Controller<EmployeeModel>
{
public override ControllerResponse Invoke()
{
var claims = new List<Claim>{
new Claim(ClaimTypes.Name,Model.Id.ToString()),
new Claim(ClaimTypes.Name,Model.Name),
new Claim(ClaimTypes.Name,Model.Surname)
};
return newTpl(GetView<EmployeeView().Get(Model,Html.MessageBox.Show(StringTable.EmployeeModel)) , StringTable.PageTitleCreateEmployee);
}
}
where Get() function is defined in this way:
public class EmployeeView : View
{
public ITemplate Get(EmployeeModel viewModel = null, string message = null)
{
return
TemplateFactory.Load("Employee.tpl")
.Model(viewModel)
.Set().Set("Message", message);
}
}
Thus in Employee.tpl is defined only forms and button.
this should work
function createUser()
{
$.ajax({
type: "POST",
url: "YourPageName.aspx/CreateEmployee",
data: {Id: foo($('#Id').val()), Nome: foo($('#FirstName').val()),Cognome:foo($('#LastName').val()) },
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert('Ok'); }
error: function (request, status, thrownError) {
alert(thrownError);
}
});
}

Categories