Change button data-tooltip text using Jquery Ajax (Received from - javascript

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");

Related

post form to iframe and echo result text on parent page

On my site I have a form that posts to an iframe, both parent and iframe window is on my page, domain, etc.
<iframe id="ifc1" style="display:none;" name="ifc"></iframe>
<div id="couponbox">
<form enctype="multipart/form-data" id="promo-form" class="form-inline" action="" method="post" target="ifc">
<div class="form-group">
<input type="text" name="..." placeholder="Enter Here" id="..." class="form-control" value="">
</div>
<div class="form-group">
<input type="submit" class="btn btn-primary" value="Apply Now" placeholder="">
</div>
</form>
</div>
The form is posting successfully, and on the iframe page there is a div that shows the alert/results.
<div id="alert" class="alert alert-success">.....</div>
I am trying to use JS or Jquery to find which text is showing in the alert (ie. fail, success, etc.), and then echo a message on the parent page.
// Attempt at a supposed solution
// reference to iframe with id 'ifrm'
var ifrm = document.getElementById('ifc1');
var base = document.getElementById('couponbox');
// using reference to iframe (ifrm) obtained above
var win = ifrm.contentWindow; // reference to iframe's window
// reference to document in iframe
var doc = ifrm.contentDocument? ifrm.contentDocument: ifrm.contentWindow.document;
// reference to form named 'demoForm' in iframe
var form = doc.getElementById('alert');
if (form === "Credits successfully deposited into your account") {
// Tried jQuery
$('#couponbox').append('success')
}
// jQuery attempt
if($("#ifc1").contents().text().search("successfully deposited")!=-1){
alert("found");
}
So far I haven't been able to get anything to work. Any help is appreciated.
UPDATE --
I am currently trying to use this code --
$('#ifc1').on('load', function() {
if($.trim($("#ifc1").contents().find("#alert").html()) === "Credits successfully deposited into your account"){
$("#couponbox").prepend("<b>Successfully Deposited</b>");
$("#buy").replaceWith( '<input type="submit" value="Publish" name="upsub" id="upsub" class="pubbtn action-button" placeholder="">'
} else {
$("#ifc1").contents().find("#alert").appendTo("#couponbox");
}
});
I've placed it at the end of my page. It's giving me errors with my other scripts though.
Commenting out the replacewith function, doesn't give the looping error ---
$('#ifc1').on('load', function() {
if($.trim($("#ifc1").contents().find("#alert").html()) === "Credits successfully deposited into your account"){
$("#couponbox").prepend("<b>Successfully Deposited</b>");
//$("#buy").replaceWith( '<input type="submit" value="Publish" name="upsub" id="upsub" class="pubbtn action-button" placeholder="">'
} else {
$("#couponbox").prepend("<b>Incorrect</b>");
}
});
To get the text of #alert div from iframe you can use
$(document).ready(function(){
$("#ifc1").contents().find("form#promo-form").on("submit",function(){
alert($("#ifc1").contents().find("#alert").html());
});
});
It will give you the text in #alert div.
Update
$('#ifc1').on('load', function() {
alert($("#ifc1").contents().find("#alert").html());
});
When you submit a form in iframe it also triggers load event of iframe. Check if you can get a value on load function?
Update 2
$('#ifc1').on('load', function() {
if($.trim($("#ifc1").contents().find("#alert").html()) === "success"){
alert("finish");
}
});
you can use $.trim to remove all white spaces around the string and the check if it matches with "success". TRIM
You're trying to get the contents of the form element, but you're not using innerHTML.
var ifrm = document.getElementById('ifc1');
var base = document.getElementById('couponbox');
var win = ifrm.contentWindow; // reference to iframe's window
var doc = ifrm.contentDocument? ifrm.contentDocument: ifrm.contentWindow.document;
var form = doc.getElementById('alert');
if (form.innerHTML.includes("Credits successfully deposited into your account")) {
$('#couponbox').append('success')
}

Javascript two weird problems: POST not working, window.location.href not working

I created an instant search similar to google search using JQuery. The highlighted code doesn't work. It is weird since they work fine by its own and everything else works fine. Any idea why this is happening?
Q1.
searchq() works fine, but the createq() function doesn't work, and the variable txt could be posted to other files(search.php). However, the function createq() can't POST. It does get the global variable txt after testing, but the php file(create_object.php) can't get it no matter what POST method I used. Could anyone helps to write a bit POST code which can work in my code.
Q2
I want to create a function that,when the enter is pressed, the user will be redirected to the first search result(which is anchored with an url) . To achieve this, I create a function that variable redirectUrl got the anchored url as string, however, the redirect function window.location.href doesn't work, the page simply refreshed. I tested window.location.href function by its own in another file, it works though. It is so weird that my page simply refreshed, It even refreshed when I direct to google. window.location.href("www.google.com").
Note that I didn't include the connect to database function here. Coz I think the database username and password setting would be different to yours.So please create your own if you want to test it. The mysql is set with a table is called "objects", and it has one column named "name".
Thanks in advance!
<html>
<!-- google API reference -->
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<!-- my own script for search function -->
<center>
<form method="POST">
<input type="text" name="search" style="width:400px " placeholder="Search box" onkeyup="searchq();">
<div id="output">
</div>
</form>
</center>
<!-- instant search function -->
<script type="text/javascript">
function searchq(){
// get the value
var txt = $("input").val();
// post the value
if(txt){
$.post("search.php", {searchVal: txt}, function(result){
$("#search_output").html(result+"<div id=\"create\" onclick=\"creatq()\"><br>Not found above? Create.</div>");
});
}
else{
$("#search_output").html("");
}
};
function createq(){
// allert for test purpose: test if the txt has got by the createq function
alert(txt);
**$.post( "create_object.php",{creatVal:txt} );**
}
// if enter key pressed, redirect page to the first search result
$("#search").keypress(function(evt){
if (evt.which == 13) {
// find the first search result in DOM and trigger a click event
var redirectUrl = $('#search_output').find('a').first().attr('href');
alert(redirectUrl);
**window.location.href = "www.google.com";
window.location.href = "www.google.com";**
}
})
</script>
</html>
PHP file (search.php)
<?php
if(isset($_POST["searchVal"])){
//get the search
$search=$_POST["searchVal"];
//sort the search
$search=preg_replace("#[^0-9a-z]#i","",$search);
//query the search
echo "<br/>SELECT * from objects WHERE name LIKE '%$search%'<br/>";
$query=mysqli_query($conn,"SELECT * from objects WHERE name LIKE '%$search%'") or die("could not search!");
$count=mysqli_num_rows($query);
//sort the result
if($count==0){
$output="there was no search result";
}
else{
while($row=mysqli_fetch_assoc($query)){
$object_name=$row["name"];
$output.="<div><a href='##'>".$object_name."</a></div>";
}
}
echo $output;
}
?>
php file (create_object.php)
<?php
if(isset($_POST["createVal"])){
$name=$_POST["createVal"];
var_dump($name);
}
?>
Try to bind the input with id
var txt = $("input").val();
<input type="text" name="search" style="width:400px " placeholder="Search box" onkeyup="searchq();">
Change above to this
var txt = $("#searchinput").val();
<input type="text" id="searchinput" name="search" style="width:400px " placeholder="Search box" onkeyup="searchq();">
and I think you are trying to show the search result here
<div id="output"></div>
and the jQuery binding is this in your code
$("#search_output").html("");
So change the HTML to this
<div id="search_output"></div>
also this in our code
$("#search").keypress(function(evt){
there is not HTML element bind with it and I think you are trying to bind it with search input so change above to this
$("#searchinput").keypress(function(evt){
The above change should also resolve the window.location.href not working problem
So the HTML will be;
<form method="POST">
<input type="text" id="searchinput" name="search" style="width:400px " placeholder="Search box" onkeyup="searchq();">
<div id="search_output"></div>
</form>
and Script will be
<script type="text/javascript">
function searchq(){
// get the value
var txt = $("#searchinput").val();
// post the value
if(txt){
$.post("search.php", {searchVal: txt}, function(result){
$("#search_output").html(result+"<div id=\"create\" onclick=\"creatq()\"><br>Not found above? Create.</div>");
});
}
else{
$("#search_output").html("");
}
}
function createq(){
// allert for test purpose: test if the txt has got by the createq function
alert(txt);
**$.post( "create_object.php",{creatVal:txt} );**
}
// if enter key pressed, redirect page to the first search result
$("#searchinput").keypress(function(evt){
if (evt.which == 13) {
// find the first search result in DOM and trigger a click event
var redirectUrl = $('#search_output').find('a').first().attr('href');
alert(redirectUrl);
**window.location.href = "www.google.com";
window.location.href = "www.google.com";**
}
});
</script>
Note: If you check browser console, you may see some errors, there are some typo mistakes like missing ; in your JS too.
In the PHP, here
if($count==0){
$output="there was no search result";
}
else{
while($row=mysqli_fetch_assoc($query)){
$object_name=$row["name"];
$output.="<div><a href='##'>".$object_name."</a></div>";
}
}
$output. is wrong with dot, so change it to following
if($count==0){
$output="there was no search result";
}
else{
while($row=mysqli_fetch_assoc($query)){
$object_name=$row["name"];
$output="<div><a href='#'>".$object_name."</a></div>";
}
}
Two things:
Input search id is not defined, $("#search").keypress won't work. Change to:
< input type="text" name="search" id="search" style="width:400px " placeholder="Search box" onkeyup="searchq();" >
Div id "output", should be "search_output", as required in $("#search_output"). Change to:
< div id="search_output" >
< /div >

html input fileupload returning null

I am trying to make a demo involving an html input file uploader and ajax, but I can't even get my script to getElementById.
I keep receiving an TypeError: form is null.
Here is my html and script:
<form id="file-form" action="handler.php" enctype="multipart/form-data" method="POST">
<input type="file" id="file-select" name="photos[]" multiple/>
<button type="submit" id="upload-button">Upload</button>
</form>
<script type="text/javascript">
var form = document.getElementById("file-form");
var fileSelect = document.getElementById("file-select");
var uploadButton = document.getElementById("upload-button");
form.onsubmit = function (event) {
event.preventDefault();
// Update button text.
uploadButton.innerHTML = 'Uploading...';
}
</script>
Note that 'fileSelect' and 'uploadButton' are receiving their elements and are not null.
For some reason form is not able to getElement.
I've seen several similar questions, but it seems like I am doing the right thing. Let me know if you have any suggestions.
Thanks in advance.
EDIT: I should add that this demo is in an ASP .ascx User Control Form. kami-sama's Code Snippet worked perfectly fine, but it will not do the same in my solution.
I log the 'form' variable after getElementById and it returns null and does not proceed past the form.onsubmit = function(event) line.
You should declare that your form will be handling uploaded files by adding the enctype="multipart/form-data"
w3
w3schools
I just added closing bracket to your code and it's working just fine in StackOverflow code snippet and in Firefox with html file.
var form = document.getElementById("file-form");
var fileSelect = document.getElementById("file-select");
var uploadButton = document.getElementById("upload-button");
form.onsubmit = function (event) {
event.preventDefault();
// Update button text.
uploadButton.innerHTML = 'Uploading...';
}
<form id="file-form" action="handler.php" method="POST">
<input type="file" id="file-select" name="photos[]" multiple/>
<button type="submit" id="upload-button">Upload</button>
</form>

Response from AJAX request is only displayed once

I've got some code that sends an ajax request when a form is being submitted. This works the first time the form is submitted (it's a search module), but only once. I've added an effect to highlight the table when data is returned, and you can only see it once (the data changes only once as well).
When I look at the response in the chrome dev tools, I can see it contains the data of the new search query but this isn't shown. Why can I only display results once?
JS:
$(function () {
// Creates an ajax request upon search form submit
var ajaxFormSubmit = function () {
var $form = $(this);
var options = {
url: $form.attr("action"),
type: $form.attr("method"),
data: $form.serialize()
};
$.ajax(options).done(function (data) {
var $target = $($form.attr("data-nn-target"));
var $newHtml = $(data);
$target.replaceWith($newHtml);
$newHtml.effect("highlight");
});
// Prevent default action
return false;
};
$("form[data-nn-ajax='true']").submit(ajaxFormSubmit);
});
HTML:
<form method="GET" action="#Url.Action("Index", "Show")" data-nn-ajax="true" data-nn-target="#contentlist" class="form-search">
<div class="input-append mysearch">
<input type="search" class="span5 search-query" name="query" data-nn-autocomplete="#Url.Action("AutoComplete")" />
<input type="submit" class="btn" value="Search" />
</div>
</form>
<div id="contentlist">
#Html.Partial("_Shows", Model)
</div>
I think you should use html() instead of replaceWith() method:
$target.html($newHtml);
just an idea... try
$target.html(data);
instead of
$target.replaceWith($newHtml);
By replaceWith, you might actually remove the div that you want to fill your content in. Then, the second time, it doesnt find the div to insert the content into.

Django/Python control: "if form.is_valid ():" is equal to false if the form has an input type "button"

I don't understand why if I have in my html page in a form: <input type="submit" class="btn btn-small btn-primary" id="execute" value="Esegui">`
then the form is valid otherwise if I put a
<input class="btn btn-small btn-primary" type="button" id="execute" value="Esegui">
the form is invalid.
The problem is that if I put as "input type" the submit then fails to load JSON's code:
<script type="text/javascript">
$(document).ready(function () {
$("a # single_image").fancybox();
$("# execute").click(function () {
var execute = true
$("# execute").attr("value", "Run ...");
$("# single_image.") attr("href", "");
$("# image").attr("src", "");
$.ajax({
type: "POST",
url: "/ cloud / carica_immagine"
date: {
execute: execute
}
}).done(function (msg) {
$("# execute").attr("value", "Run");
$("# single_image.") attr("href", "graphs /" + msg["user_id"] + "/" + msg["graph"] + ."png");
$("# image").attr("src", "graphs /" + msg["user_id"] + "/" + msg["graph"] + ."png");
$("# single_image.") trigger("click");
});
});
})
</ script>.
This is my view that is called by html page:
def list(request):
# Handle file upload
documents = Document.objects.all()
if request.method == 'POST':
form = DocumentForm(request.POST, request.FILES)
if form.is_valid():
newdoc = Document(docfile = request.FILES['docfile'])
print newdoc.docfile
newdoc.save()
...
...
return render_to_response('processa_immagine.html', {'documents':documents, 'form': form, 'user_id':request.session['user_id'],'graph':graph}, RequestContext(request))
else:
form = DocumentForm() # A empty, unbound form
# Render list page with the documents and the form
return render_to_response('processa_immagine.html', {'documents':documents, 'form': form}, RequestContext(request))
This is my forms:
class DocumentForm(forms.Form):
docfile = forms.FileField(
label='Seleziona un file',help_text='massimo 42 megabytes',
)
This is my models:
class Document(models.Model):
docfile = models.FileField(upload_to='documents')
my page html with form is:
<form method="post" id="myform" enctype="multipart/form-data">
<p>{{ form.docfile.label_tag }} {{ form.docfile.help_text }} </p>
<p>{{ form.docfile }}</p>
<input class="btn btn-small btn-primary" type="button" id="execute" value="Esegui"><br/>
</form>
I hope that someone help me.
Thanks in advance.
This code is very confused. You have defined an Ajax function on your button triggered on the click event. So, when you click the button, that function is triggered, and it tries to submit the form. However, it cannot do so in a way that will make the form valid: the only field in the form is a required FileField, which cannot be submitted via a standard Ajax POST - and even if it could, your Ajax function makes no attempt to actually include it.
The reason why the input version appears to work is that the Javascript does not prevent the default submit action, so the process is this: the Ajax is run, but even before it has a chance to receive a response, the entire page is submitted, and refreshes with the result of the (valid) form submission.

Categories