Everything almost works! i just need to find out why the code below won't give me more than the first buttons values.
public static function getProjectOnSearch($inp){
return DB::table('projecten')
->select(DB::raw('titel,status,prioriteit,soort,projectnaam,projecturl
,gebruikersnaam,wachtwoord
,gebruiker_id,omschrijvingproject'))
->where('projectnaam', 'LIKE', '%'.$inp.'%')
->get();
}
I want to fill in some input fields with values from my database upon clicking an button. I have the code working to fill in an name and click on the search button to fill the inputs. That works great. When I use that code with the other button it won't work. see my code below.
Javascript code :
<script type="text/javascript">
$("#wijzigKnop2").on("click",function(){
var email2 = $('#zoeknaam2').val('');
$('#titel2').val('');
$('#status2').val('');
$('#prioriteit2').val('');
$('#type2').val('');
$('#projectnaam2').val('');
$('#projecturl2').val('');
$('#gebruikersnaam2').val('');
$('#wachtwoord2').val('');
$('#omschrijving2').val('');
$.ajax({
method: "POST",
url: "/updateProjectData",
data: { input: email2 ,
_token: "{{ csrf_token() }}"
}
})
.done(function( msg ) {
$('#titel2').val(msg[0].titel);
$('#status2').val(msg[0].status);
$('#prioriteit2').val(msg[0].prioriteit);
$('#soort2').val(msg[0].soort);
$('#projectnaam2').val(msg[0].projectnaam);
$('#projecturl2').val(msg[0].projecturl);
$('#gebruikersnaam2').val(msg[0].gebruikersnaam);
$('#wachtwoord2').val(msg[0].wachtwoord);
$('#omschrijving2').val(msg[0].omschrijvingproject);
});
});
</script>
HTML Button with hidden input for value (normally the value would be typed in but this button will get the value from an HTML table which generates a row throught a foreach)
<input type="hidden" value="{{$project->projectnaam}}"
id="zoeknaam2" name="zoeknaam2" class="form-control" placeholder="Projectnaam">
<button class="btn btn-success btn-xs" id="wijzigKnop2" name="zoekProject" type="button">
<i class="glyphicon glyphicon-pencil"></i>
</button>
Any answers or ideas are very welcome thanks in advance for posting!
Please check
var email2 = $('#zoeknaam2').val('');
this should be not blank
var email2 = $('#zoeknaam2').val();
If you get proper value in at server side then problem at server side code.
To check on response,do
console.log(JSON.stringify(msg));
As per questioner server side solving
public static function getProjectOnSearch($inp){
return DB::table('projecten') ->select(DB::raw('titel,status,prioriteit,soort,projectnaam,projecturl ,gebruikersnaam,wachtwoord ,gebruiker_id,omschrijvingproject')) ->where('projectnaam', 'LIKE', '%'.$inp.'%') ->get();
}
fixes all things.
Get the value of the element then clear it.
var email2 = $('#zoeknaam2').val();
$('#zoeknaam2').val('');
Related
Problem
When i click on the add to cart button the url cart_add is triggered and the product value is added to it but the issue is that the quantity form value is not retrieved due to which the product is actually not added to the cart.
The code i have written is as follows
Script
$(document).on("click",".Id_submit",function(event){
event.preventDefault();
var selector = $(this).closest(".productID")
console.log(selector.find("form").attr('action'))
const form_data = {
csrfmiddlewaretoken: $('#transactionIDValue input[name="csrfmiddlewaretoken"]').val()
}
$.ajax({
type : 'POST',
url: selector.find("form").attr('action'),
data: form_data,
success: function()
{
alert("Product added to cart")
}
});
});
HTML
<form id='transactionIDValue' class="d-inline" method="post">
{{cart_product_form}}
{% csrf_token %}
<input type="submit" class="btn btn-primary shadow px-5 py-2 Id_submit" value="Add To Cart">
</form>
Views.py
#require_POST
#csrf_exempt
def cart_add(request, product_id):
cart = Cart(request)
product = get_object_or_404(transactions, id=product_id)
form = CartAddProductForm(request.POST)
if form.is_valid():
cd = form.cleaned_data
print(cd)
cart.add(product=product, quantity=cd['quantity'])
else:
print('error')
print(cart)
# request.session['items_total'] = cart.product.count()
return HttpResponseRedirect(reverse('main:home'),'success')
ISSUE
Now, the issue is that when the {{cart_product_form}} is called the quantity drop is set to the page but when i click on the add_to_cart the value from it is not added to cart, so i rechecked it even didn't even gets in the form validation check in the views. Can anyone help through this issue. This issue is only when i am using the add_cart function using ajax, but if i use it without ajax it works. All i want to know why is value from {{cart_product_form}} is not passed to the cart.
I have a tag and a button. On click of the button, an actionResult in a controller is called. Like this.
<button type="button" onclick="location.href='#Url.Action("GetAllItems", "Items")'">Get Items</button>
And here's the ActionResult
public ActionResult GetAllItems() {
string selectedItem = string.Empty;
ItemsRepository itemsRepository = new ItemsRepository();
ModelState.Clear();
return View(itemsRepository.GetAllItems());
}
selectedItem is the variable I want to store either the selectedText or the selectedValue. But I don't know how to.
This is the <Select> tag.
<select style="width:170px" id="ItemsID" name="Items"></select>
And this is the rough function to get the different results from onChange event.
<script>
$(document).ready(function () {
$("#ItemsID").change(function () {
var a = $('#ItemsID option:selected').val();
var b = $('#ItemsID option:selected').text().trim();
var c = $('#ItemsID option:selected').index();
alert(a);
alert(b);
alert(c);
})
});
Please help.
location.href doesn't sent a POST request. What you got to do is to place a form tag with your ActionResult to make a POST request.
<form action='yourAction'>
<select name='name'></select>
<button type="submit">Get Items</button>
</form>
You can use following code to get the value of your select in the action method. Note that you must pass the name attribute of your html select element to Request.
var selectedValue = Request["Items"];
Also, make sure the button that is clicked submits a form by using code like below.
The main point is that you can only use Request object to access a html element value in C# code, provided the html element and the submit button are within the same form. If you use a button that redirects the user rather than submits a form then this will not work, so it must be a submit type button as in code below.
#using (Html.BeginForm("YourActionName", "ControllerName")) {
<select style="width:170px" id="ItemsID" name="Items"></select>
<input type="submit" value="Submit Data" id="btnSubmit" />
}
This is my HTML code
<form class="addtowatchlistform" action="logo/insertwatchlist.php" method="POST">
<input type="hidden" name="tmdb_id" value="'.$result[$x]["tmdb_id"].'"/>
<button id="addtowatchlistbutton" type="submit" name="tmdb_id" value="'.$result[$x]["tmdb_id"].'" data-tooltip="ADD TO YOUR WATCHLIST" class="material-icons" style="color:'.$watchlisticoncolor.'">add_box</button>
</form>
// Same form as above
<form class="addtowatchlistform" action="logo/insertwatchlist.php" method="POST">
<input type="hidden" name="tmdb_id" value="'.$result[$x]["tmdb_id"].'"/>
<button id="addtowatchlistbutton" type="submit" name="tmdb_id" value="'.$result[$x]["tmdb_id"].'" data-tooltip="ADD TO YOUR WATCHLIST" class="material-icons" style="color:'.$watchlisticoncolor.'">add_box</button>
</form>
Jquery Code:
<script>
$(".addtowatchlistform").submit(function(e) {
var data = $(this).serialize();
var url = $(this).attr("action");
var form = $(this); // Add this line
$.post(url, data, function(data) {
try {
data = JSON.parse(data);
$(form).children("button").css('color',data.watchlisticoncolor);
$(form).children("button").data('tooltip', data.addremove + " TO YOUR WATCHLIST"); // This line not working
} catch (e) {
console.log("json encoding failed");
return false;
}
});
return false;
});
</script>
PHP file insertwatchlist.php file
$response = new \stdClass();
$response->addremove = "REMOVE";//you can get the data anyway you want(e.g database)
$response->watchlisticoncolor = "red";
die(json_encode($response));
Output of PHP file insertwatchlist.php file
{"addremove":"REMOVE","watchlisticoncolor":"red"}
Expected Result:
1.)When someone clicks on add_box button, it submits the form without reloading the page (This one works fine)
2.) When someone clicks on add_box button, it's color changes. (works fine too)
3.) When someone click on add_box button, the data-tooltip="" value changes. (this one do not work)
So the 3rd point do not work as expected, what is wrong in my Jquery code? Console tab is empty, it shows nothing.
your jquery code should be like this
$(form).children("button").attr('data-tooltip',data.addremove + "TO YOUR WATCHLIST");
or
$('.material-icons').attr('data-tooltip',data.addremove + "TO YOUR WATCHLIST");
I'm currently implementing a feature that somebody can add addresses on my page. He can do this via a simple form. What I have now (to print the addresses) is:
#foreach($addresses as $address)
#if($address->typeOfAddress==0)
Name: {{$address->name}}<br/>
Straße: {{$address->street}}<br/>
PLZ: {{$address->plz}}<br/>
Ort: {{$address->city}}<br/>
<a type="button" class="btn btn-info" href="/editAddress/{{$address->id}}">Bearbeiten</a>
<a type="button" class="btn btn-danger deleteAddressButton" href="/deleteAddress/{{$address->id}}">Löschen</a>
<br/><br/>
#endif
#endforeach
The variable addresses is passed into the view from the controller.
What I'm trying to achieve now, is that the user can simply click on one of those address parts, like name, straße, plz and ort, and it's converted to an input field, so the value can be changed. Then, when leaving the focus (so clicking somewhere else (or maybe add a save button next to it)), the new data has to be sent to the controller by ajax (the request itself should be no problem then). But: How can I convert it to an input field and how can I then convert it back and react to it (to then send the ajax request)?
I searched in the internet, but didn't find something...
Edit: found a fiddle here (http://jsfiddle.net/yXcZG/3) that does nearly what I want, but I have the problem, that it doesn't seem to keep the format, 1. it has much more space between the lines and: when clicking on it to edit, the input field jumps to the bottom of the page and doesn't stay on the same position. Also I just want the variables to be editable, not the text before the :.
So this is what I tried: (of course the AJAX thing is still missing, but first the other thing has to work)
In JS:
$(document).on('click', '.editableText', function (e) {
console.log(this);
TBox(this);
});
$("input").live('blur', function (e) {
RBox(this);
});
function TBox(obj) {
var id = $(obj).attr("id");
var input = $('<input />', { 'type': 'text', 'id': id, 'class': 'editableText', 'value': $(obj).html() });
$(obj).parent().append(input);
$(obj).remove();
input.focus();
}
function RBox(obj) {
var id = $(obj).attr("id");
var input = $('<p />', { 'id': id, 'class': 'editableText', 'html': $(obj).val() });
$(obj).parent().append(input);
$(obj).remove();
}
HTML:
#foreach($addresses as $address)
#if($address->typeOfAddress==0)
Name: <span id="addressName{{$address->id}}" class="editableText">{{$address->name}}</span><br/>
Straße: <span id="addressStreet{{$address->id}}" class="editableText">{{$address->street}}</span><br/>
PLZ: <span id="addressPLZ{{$address->id}}" class="editableText">{{$address->plz}}</span><br/>
Ort: <span id="addressCity{{$address->id}}" class="editableText">{{$address->city}}</span><br/>
<a type="button" class="btn btn-danger deleteAddressButton" href="/deleteAddress/{{$address->id}}">Löschen</a>
<br/><br/>
#endif
#endforeach
Edit2: Found this answer on stackoverflow too (https://stackoverflow.com/a/6814092/3375021), so use contenteditable, but I have the problem, that I on blur neither know, which address should be changed in the database, nor which part of the address..
If you're looking for a jQuery working solution you can go with this
JsFiddle example
You have a listener for when you click an element that is editable, it'll take the value of it and put it inside an input.
After you blur you can take this value and do whatever you want with it..
Here is the javascript (jQuery) part.
$(function(){
$('body').on("click", ".changeable", function(e){
var text = $(this).text();
$(this).html("<input type='text' class='input-editable' value='" + text + "'>");
$(this).find('input').focus();
});
$('body').on("blur", ".input-editable", function(e){
var text = $(this).val();
$(this).parent().html(text);
console.log("Value changes to: " + text);
});
});
I think you should be using <?php echo $variable; ?> instead of blade {{$variabl}}
If you going to store a html tags or js into your database then you need to not use blade to echo it, you should use php simple echo function instead
I'm trying to pass a JavaScript variable to the value of an hidden input button to use in my PHP file output.
My HTML is:
<input type = "hidden" id = "location2" name = "location2" value = ""/>
I'm using this onclick="myFunction();" in my "Submit Form" input to run the function as it is not able to be done in the window.load()
My JavaScript below is calling indexes from another function and assigning the text to the variable 'location' (I know this sounds strange but it was the only way I have got it to work so far):
function myFunction() {
var x = document.getElementById("box2").selectedIndex;
var y = document.getElementById("box2").options;
var location=(y[x].text);
document.getElementById("location2").value=(location);
}
Any help would be hugely appreciated as I am really struggling and have been working on this for some time (as you can probably tell, I dont really know what I'm doing) - I just need to call the value of this variable into my PHP file output and the majority of my web form is completed.
Thanks very much
Marcus
I've just changed my HTML as follows
I've removed myFunction from my submit
I've added the following HTML button:
<button onclick="myFunction();" id = "location2" name = "location2" value="">Click me</button>
The variable is now passing!!!! The only problem is when I press the onclick button, it is now submitting my form!!
Is it okay for me to replace my previous submit button with this code??
THANKS TO EVERYONE FOR THEIR HELP ON THIS!!
I Was not sure what you doing but below example may help you. It will post the value as well as the option text.
Here we are using print_r to print the $_POST array from the AJAX Request. using this method, you should be able to debug the issue.
<!DOCTYPE html>
<html>
<body>
<?php if($_POST) {
print_r($_POST); die;
} ?>
<form name="" id="" method="post" >
Select a fruit and click the button:
<select id="mySelect">
<option>Apple</option>
<option>Orange</option>
<option>Pineapple</option>
<option>Banana</option>
</select>
<input type = "hidden" id = "location2" name = "location2" value = ""/>
<input type = "hidden" id = "locationname" name = "locationname" value = ""/>
<button type="submit" id="submit">Display index</button>
</form>
<script>
function myFunction() {
var x = document.getElementById("mySelect").selectedIndex;
var y = document.getElementById("mySelect").options;
//alert("Index: " + y[x].index + " is " + y[x].text);
document.getElementById("location2").value=(y[x].index);
document.getElementById("locationname").value=(y[x].text);
//alert($("#location2").val());
}
var submit = document.getElementById('submit');
submit.onsubmit = function(e){
myFunction();
};
</script>
</body>
</html>
i'm assuming your form method is 'POST' and action value is the same php page where you are expecting to see the 'location2' hidden input value, if that is the case, you can use $_POST['location2'] to get the value in that php page.
Yes it is fine to use button tag by default it acts like the submit button inside the form tag. You can also make it act like button(won't submit the form) by using the attribute type='button'.
Edited
button or input type='submit' can submit the form only when it is placed within the form tag(without javascript).
<form action='http://www.stackoverflow.com/'>
<button>stackoverflow</button> <!-- this works -->
</form>
<form action='http://www.stackoverflow.com/'></form>
<button>stackoverflow</button><!-- this won't work -->
var go = function() {
document.forms[0].submit();
};
<form action='http://www.stackoverflow.com/'></form>
<button onclick='go()'>stackoverflow</button><!-- still works -->