I have to admit that I don't really know how to explain this "problem" that I have nor was I able to find a good title for this thread. Anyway, I will try to be clear because I'm not sure if I could add a JSFiddle or code snippet.
Let's start with the project. I'm working on some kind of DVD Library to be used on a local network only. There's a page that allow a user to add new films to the database. To do this, I use the Allocine API (A French equivalent to IMDB) to gather films informations. The user can enter a film title (Or part of it) and perform a search. All the corresponding films from Allocine will then appear.
If the user click on one of them, a modal window opens embedding a form that will allow the user to add the needed informations before sending the form. The form is then sent using AJAX and the result appear in the same modal window.
The problem come when I want to add a second film. If I don't reload the page before trying to submit the form another time, the value from the first film will be sent instead of them from the second one and that is driving me crazy.
Here's the javascript code used to send the form.
$("body").on( "click", "#AddFilmButton", function() {
var formDatas = $('#FormAjoutFilm').serialize();
$.ajax({
url : 'Functions.php',
type : 'POST',
data : 'Action=AddFilm&' + formDatas,
cache: false,
dataType : 'html',
success : function(result, statut){
$(result).modal();
},
});
});
You may notice that I'm watching a button click event instead of a form submit event. That's because when I used the form submit event, the page was refreshed all the time, no matter if I was using preventDefault or not.
I'm starting to wonder if the sent value are not reset exactly because I have used this workaround. Could it be just that ?
What other piece of code would be useful to help you understand my problem ?
EDIT : just like #intale suggested, I have multiple form in the DOM because of this modal system. I made some progress with it. First, I can now use a proper event handler and I'm watching the form submit event as preventDefault now works.
In the success function, I have added this line : $('#FormAjoutFilm').remove();
It works almost as intended in that the datas are submitted only every other time. :p
Still, it's better than the previous behavior and I need to fix it now.
Thanks for anyone who contributed so far. If you know why I need to send the form two times to get it work, let me know. This is what I have now. :)
$("body").on( "submit", "#FormAjoutFilm", function(e) {
e.preventDefault();
var formDatas = $('#FormAjoutFilm').serialize();
alert(formDatas);
$.ajax({
url : 'Functions.php',
type : 'POST',
data : 'Action=AddFilm&' + formDatas,
cache: false,
dataType : 'html',
success : function(result, statut){
$('#FormAjoutFilm').remove();
$(result).modal();
},
});
});
Second Edit : It looks like it's finally solved after a cache clearing. Thanks for everyone who contributed. :)
Try reseting the form after the data is sent:
success : function(result, statut){
$('#FormAjoutFilm')[0].reset();
$(result).modal();
}
This will prevent your serialize function from getting the first submit data
Related
I have several forms on a page that submit values from radio buttons using jquery/ajax. All works fine when a Submit button is used, but I would like to eliminate the Submit button. I tried using onClick to submit. However, trying it this way causes the forms to get submitted prior to the processing script picking them up. I would very much appreciate advice (and example if possible). Thank you, Brian
Script:
$(document).ready(function() {
// process the form
$('form').submit(function(event) {
// get the form data
var formData = $(this).serialize();
// process the form
$.ajax({
type : 'POST', // define the type of HTTP verb we want to use (POST for our form)
url : 'process.php', // the url where we want to POST
data : formData, // our data object
dataType : 'json' // what type of data do we expect back from the server
})
// using the done promise callback
.done(function(data) {
if (data.success) {
// success.
// hide form container
$("#"+data.message).hide();
$("#"+data.message+"hr").hide();
}
// log data to the console so we can see
//console.log(data);
// here we will handle errors and validation messages
});
// stop the form from submitting the normal way and refreshing the page
event.preventDefault();
});
});
Form:
<method="post" action="process.php" enctype="multipart/form-data">
<input type="radio" name="answer" value="yes" onClick="onClick="this.form.submit()">
Your syntax for onclick is wrong, but putting onclick attributes on elements is an outdated way of doing things in any case.
You probably want to handle the change event rather than click, since the selection of the radiobutton happens after the click, so if you submit the form right away the radiobutton might not be selected yet (I'm not sure, I'd have to experiment, but change is probably more foolproof).
$(document).ready(function() {
$('input[type=radio]').change(function(event) {
//the rest of your code goes here
//you don't need event.preventDefault() anymore
});
});
Edit: $(this) won't refer to the form anymore of course, just replacing it with $('form') should do the trick.
I am implementing my own Like/Unlike system for my website. The PHP part is already done and all working, but I'm trying to make the Like/Unlike process all asynchronous with jQuery's AJAX methods.
What I'm trying to achieve is let an user press the like button and then the like button will become yellow (like being pressed) and the URL will change to unlike and when clicked, the user will basically unlike the item and the button will get its original color again.
The liking part is already working, but I'm failing to toggle between these two.
This is what I've been trying:
HTML/TWIG:
<li><span class="glyphicon glyphicon-thumbs-up" {% if S_IMAGE_LIKED == true %}style="color: #f0c36d;" title="Unlike"{% else %}title="Like"{% endif %} data-placement="right"></span></li>
jQuery:
$('[data-image-action="likeUnlike"]').click(function(e){
var likeHref = $(this).attr('href');
var likeUnlike = (likeHref.indexOf('unlike') != -1) ? 'unlike' : 'like';
var unLikeUrl = likeHref.replace(!likeUnlike, likeUnlike); // This is wrong, but how else do I do this?
var thumbColor = (likeUnlike == 'like') ? '#f0c36d' : '#eee';
$(this).attr('href', unLikeUrl);
$('.image-options .glyphicon-thumbs-up').attr('data-original-title', ucfirst(likeUnlike));
$('.image-options .tooltip-inner').text(ucfirst(likeUnlike));
$('.image-options .glyphicon-thumbs-up').css('color', thumbColor);
$.ajax({
type: 'GET',
url: likeHref,
success: function(data){
// console.log(data); return;
var response = $.parseJSON(data);
if ('error' in response)
{
display_alert(response.error, 'danger', 3000, 'top');
return;
}
$('.likeCount').text(response.likeCount);
}
});
e.preventDefault();
return false;
});
After refreshing the page, the logic works great enough with the Twig if statements, but I want to achieve the same without having to reload the page.
So again in summary:
User clicks Like
Glyphicon turns yellow, title changes to Unlike and URL changes to unlike
User now clicks Unlike
Glyphicon turns light greyish, title changes to Like and URL changes to like
How can I achieve this? What's wrong in my code?
// This is wrong, but how else do I do this?
likeHref.replace(!likeUnlike, likeUnlike);
Basically you want to replace the current state with its reverse (which is not what the boolean NOT does for us :-) ). The current is likeUnlike, so do
var unlikeLike = (likeUnlike == 'like') ? 'unlike' : 'like';
Now, since replace does take a regular expression, we can simply match both possible wordings and replace them with the new:
var unlikeHref = likeHref.replace(/(un)?like/g, unlikeLike);
There's a lot happening in your code. Try to isolate the bits and pieces.
Firstly, your problem does not seem to have anything to do with the ajax request, unless that's throwing an exception for some reason. Changing the link url and the icon style when a user clicks on it should be simple though.
My suggestion on how proceed in debugging, step by step:
Check the browser console (eg. firebug) for any js exceptions
Ignore the ajax request and just focus on toggling the link url and icons style in the click event.
Check the value of the href attribute and all the other variables that are being set.
What is returning ucfirst, upper case first string?
Also, you will want to prevent the user clicking on the like/unlike link while the ajax request is in progress.
I hope I could help with this.
1 - I have a web page, in that page there are many external links
2 - When user click on any external link then a popup should be come with the message that page has been modified by dynamic action or it not.
3 - How can I check the page status using JavaScript / jQuery?
Thanks in advance.
you can go for "onhaschange" event of window/body on change simply set some flag which you can check on click of link to show whether page is changed or not.
Add some state variable to javascript, like:
wasModified = false;
Subscribe on click event of every external link or whatever you want to react on, like that:
$('.external-link-class-selector').click(function(){
wasModified = true;
//in case click mean it was modified and you should notify user
alert('Page was modified');
});
see
$.ajax({
url: "",
type: "post",
dataType: "" ,
data: ,
}).done(function() {
//sucess
});
make a function in Javascript including above function and Post values by this method to the same page and append success message on the page.
I'm currently in the midst of creating a generator which echoes a random line from a .txt file. All is well and good however I need to have this certain part of the page which echoes the random line refresh when a button is clicked. I've tried multiple methods to no avail and I'm running out of ideas - I'm still quite new to JavaScript/AJAX and have no idea on how to go about it. Any help would be brilliant, thanks!
Use Jquery Ajax to get contents from the file and display the contents into a div
$.ajax({
type: "GET",
url: "yourfilename.txt"
}).done(function( msg ) {
$("#YOURDIVID").html(msg.d);
});
Bind click event of your button
$(function(){
$("#YOURBUTTONID").on("click",function(){
//do your work
});
});
Refreshing logic can be wrapped into a function and called on click of button OR you can use javascript settimeout method.
I use the following script to catch the click on a second submit-button and send the data via ajax to fancybox. The script works fine, but only the first time. If you close fancybox and want to open it again, the firefox-console says that $.fancybox is undefined and nothing happens.
$(document).ready(function(){
$(':submit').click(function(){
var value = $(this).attr('id');
if (value == 'preview') {
$.fancybox.showLoading();
$.ajax({
type : 'POST',
cache : false,
url : '/mypath/index.php',
data : $('#myform').serializeArray(),
success : function(data) {
$.fancybox(data)
}
});
return false;
}
});
});
Maybe it has to do with the other scripts used on the site: These are Datepicker, Bassistance Validate and Tooltip and some custom-scripts. I created a small demopage just with a form and a small destination /mypath/test.php and had no problems.
Edit: Deleted, no good idea. If the problem would have been caused by the .ready it wouldn't work on the testpage.
Edit2: Solved. The problem was, that I called jquery and the ui in the header of the target-site url : '/mypath/index.php'. I deleted the code and now it runs!