Jquery Ajax NyroModal Page Reload after Succes - php

I have site running Jquery, Ajax, PHP, and an HTML form. It uses two pages.
Pages...
Example.php & Processexample.php
When you click the edit button on example.php a form pops up in the NyroModal window posting to Processexample.php and allows you to edit customer data that's posted using Ajax.
After user clicks save on Porcessexample.php a SQL update is made and a success message is posted back to the Modal Box (end-user).
Here are the issues...
I can't get the NyroModal window to close after (data) success is called on processexample.php. I tried setting the Timeout in JQ/Javascript below but error occurs.
setTimeout("$.nyroModal.close()", 4000);
How do i get example.php page to display updated data automatically, or have the page reload after #send button is clicked and success is displayed in modal window.
HTML Form Code on processexample.php
<form id="AjaxForm" name="AjaxForm" action="#" method="post">
<input name="submitform" type="hidden" value="1"
<button id="send">Save Client</button>
JS Code on processexample.php --> See bold text in code where issue is.
$(document).ready(function() {
$("#AjaxForm").submit(function() { return false; });
$("#send").on("click", function(e){
var idval = $("#client").val();
var calval = $("#view").val();
var emailval = $("#customer_email").val();
var nameval = $("#customer_name").val();
var phoneval = $("#customer_phone").val();
var msgval = $("#customer_note").val();
var msglen = msgval.length;
var mailvalid = validateEmail(emailval);
if(mailvalid == true && msglen >= 4) {
// if both validate we attempt to send the e-mail
// first we hide the submit btn so the user doesnt click twice
$("#send").replaceWith("<em>sending...</em>");
$.ajax({
type: 'POST',
url: 'saveclient.php',
data: $("#AjaxForm").serialize(),
success: function(data) {
if(data == "true") {
$("#AjaxForm").fadeOut("fast", function(){
$(this).before("<p><strong>Success! Your information has been updated.</strong></p>");
**setTimeout("$.nyroModal.close()", 4000);**
});
}
}
});
}
});
});
</script>

I was able to work this out myself. Use location.reload(); after the success call.

Related

Ajax requests are failing to send after an initial ajax request is made - trying to figure out what is causing a conflict

I have a form with multiple types of ajax calls.
- general form update that saves all input fields
- per-field uploads
- per-upload deletion
The per-field and per-upload ajax calls are targeted by the class name of the button that is clicked. So there are only 3 scripts in the page.
Each of the scripts work. When the page loads fresh, I can complete any of the form update, field upload, or upload deletion actions.
However, after I have completed an initial action, subsequent actions don't work.
Example:
If I click the "save" button to update the form, this causes the per-field upload and per-upload deletion buttons not to work.
If I click the "per-field" upload, the upload works, but then I'm not able to delete anything.
If I click a "per-upload" delete button, I can no longer upload anything.
But in each case, I am still able to click "save" to update the form.
Here's a visual of how the page is set up:
When a file or image is uploaded to a field, it appears in a container div within the field's markup. The uploaded asset comes with a 'delete' button allowing the user to remove the upload.
Here's the basic HTML of the page
<form id = "form" action = "/process.php" method = "post">
<div class="field">
<label class="field-label">
<span class="field-label-text">Upload 1</span>
<input type="file" data-name="answer1" name="files_answer1[]" />
</label>
<!-- destination for ajax response messages -->
<div id="ajax-message-answer1" class="ajax-field-message"></div>
<!-- upload button -->
<button type="button" class="ajax-button" data-field="answer1" data-type="files">Upload</button>
<!-- container div for uploads -->
<div class="assets" id="assets-answer1">
<div class="asset file">
Name of file
<label class="asset-action">
<!-- deletion button to remove asset -->
<button type="button" data-asset="asset1" data-parent="answer1" class="ajax-delete" value="asset1" onclick="return confirm('You are about to delete this item. Press OK to proceed.')">Delete</button>
</label>
</div><!-- .asset.file -->
</div><!-- .assets -->
</div><!-- .field -->
.... more fields of the same kind ...
<button type = "submit" id = "save">Save</button>
</form>
JS
There are several other scripts in the page, such as jQuery, jQuery UI, Bootstrap, and some custom ones for generating slugs, etc. But I'm thinking these aren't to blame since the problem began only when I started running more than one Ajax request in the page. Here's the JS:
Form Update script
<script type="text/javascript">
$(document).ready(function() {
// process form
$('#form').submit(function(eform) {
// stop regular form submission
eform.preventDefault();
// set variables
var form = $('#form');
// serialize form data
var fdform = form.serializeArray();
// make request
$.ajax({
url: '/account/ajax.php',
type: 'post',
data: $.param(fdform),
dataType: 'json',
success: function(data) {
// get URL for redirect if supplied
if (data.redirect) {
window.location.href = data.redirect;
} else {
// replace with updated template from response
$('#form').html(data.html);
// place template js in specified div
$('#ajax-js').html(data.js);
}
},
error: function(report) {
console.log(report.responseText);
}
});
}); // .click
}); // .ready
</script>
Per-Field Upload script
<script>
$(document).ready(function() {
$(".ajax-button").click(function() {
var fdUpload = new FormData();
// get field info from the clicked button
var field = $(this).data('field');
var uploadType = $(this).data('type');
var input = $('#' + field)[0];
var container_id = '#assets-' + field;
var button_id = '#button-' + field;
// add each file to uploads array
$.each(input.files, function(i, upl) {
// add each file to target element in fdUpload
fdUpload.append(uploadType + '[]', upl);
});
// make request
$.ajax({
url: '/account/ajax.php',
type: 'post',
data: fdUpload,
dataType: 'json', // returns success(data) as object
contentType: false,
processData: false,
success: function(data) {
// put received html in container
$(container_id).html(data.html);
// put received js in #ajax-js
$('#ajax-js').append(data.js);
// clear file input after upload completes
input.value = '';
if (!/safari/i.test(navigator.userAgent)) {
input.type = '';
input.type = 'file';
}
},
error: function(report) {
console.log(report.responseText);
}
});
});
});
</script>
Per-Upload Deletion script
<script>
$(document).ready(function() {
$(".ajax-delete").click(function() {
var fdDelete = new FormData();
// get asset info from clicked button
var asset = $(this).data('asset');
var parent = $(this).data('parent'); // answer
var container_id = '#assets-' + parent;
var button_id = '#delete-' + asset;
var message_id = '#ajax-message-' + asset;
// make request
$.ajax({
url: '/account/ajax.php',
type: 'post',
data: fdDelete,
dataType: 'json',
contentType: false,
processData: false,
success: function(data) {
// put received html in container
$(container_id).html(data.html);
// put received js in #ajax-js
$('#ajax-js').html(data.js);
// retrieve and display response status
$(message_id).html(data.status);
$(message_id).addClass('show');
},
error: function(report) {
console.log(report.responseText);
}
});
});
});
</script>
Summary
Again, each ajax request works when activated after a fresh page load. But after the form has been updated or after an upload or deletion, the upload and deletion no longer fire.
The 'error' callback doesn't display anything in console when this failure occurs.
Do you see a conflict somewhere in the scripts? Maybe the scripts need function names defined? Or is it a problem that the returned response object is called 'data' in each script?
I haven't been working with Ajax very long, so I'd really appreciate your help. I've been banging my head on this all day.
You're using $(".ajax-...").click(...) but in ajax success handler you're updating HTML code for container, thus loosing any attached click handlers for elements in this container.
If you switch to using $("#form").on('click', '.ajax-...', ...) then you'll catch click events even after directly replacing HTML.
jQuery.on() documentation

Submitting form with AJAX without button

I'm trying to send a form with AJAX and without submit button. Everything works just fine with submit button, but if I try to submit the form by clicking something else it won't work.
I searched for an answer for quite a while, but didn't find anything useful so far.
function ajaxSubmit(){
var showHideForm = jQuery('#dashboard-hki-subjects-form').serialize();
$.ajax({
type:"POST",
url: "/wp-admin/admin-ajax.php",
data: showHideForm,
success:function(data){
$('#formMessage').html(data);
}
});
return false;
}
$('.show-hide-subject-button').click(function(){
var subject = $(this).attr('subject');
$('#hide-subject').attr('value',subject);
});
$('#dashboard-hki-subjects-form').submit(ajaxSubmit);
I'm using Wordpress, so the AJAX is handeled with admin-ajax.php.
What if you just use an enter key handler...
Try this:
<input type="text" name="txt"/>
$('#txt').keydown(function (e){
if(e.keyCode == 13){
console.log('you pressed enter!'); //prints to the browser console...
ajaxSubmit(); //the function you described in your question...
}
})
You have to bind the ajaxSubmit() to whatever there is you're clicking, otherwise there simply will be nothing on your page to trigger it. E.g., if you want your form to be submitted whenever you click on the .show-hide-subject-button element, you have to call ajaxSubmit() explicitly:
$('.show-hide-subject-button').click(function(){
var subject = $(this).attr('subject');
$('#hide-subject').attr('value',subject);
ajaxSubmit();
});

ajax php post on clicking outside div

I want to post something after writing it into a textarea without clicking any button but on clicking outside the textarea..How can I achieve that?? My code...
<form action="javascript:parseResponse();" id="responseForm">
<textarea align="center" name="post" id="post">Write something</textarea>
<input type="button" id="submit" value="submit" />
</form>
AJAX:
$('#responseForm').submit(function({$('#submit',this).attr('disabled','disabled');});
function parseResponse(){
var post_status = $("#post");
var url = "post_send.php";
if(post_status.val() != ''){
$.post(url, { post: post_status.val()}, function(data){
$(function(){
$.ajax({
type: "POST",
url: "home_load.php",
data: "getNews=true",
success:function(r)
{
$(".container").html(r)
},
})
})
document.getElementById('post').value = "";
});
}
}
I want to remove the button...and when an user clicks outside the textarea it will automatically submit the information...The whole body outside the textarea will act as the submit button...when user writes any info on the textarea...How can I achieve that??
Try the following:
$(document).on("click", function(e) {
var $target = $("#YOUR_ELEMENT");
if ($target.has(e.target).length === 0) {
your_submit_function();
}
});
You could also attach your submit function to the blur event for improved functionality:
$(document).on("click", function(e) {
var $target = $("#YOUR_ELEMENT");
if ($target.has(e.target).length === 0) {
your_submit_function();
});
$("#YOUR_ELEMENT").on("blur", function() {
your_submit_function();
});
You can attach a click handler to the entire document, and then cancel the event if the user clicked inside the text area. Something like this might do the trick:
$( document ).on( "click", function( ev ) {
if( $( ev.target ).index( $( "#post" )) == -1 ) {
// User clicked outside the text area.
}
} );
I use code similar to this to accomplish essentially the same thing (check when a user clicked outside of something). This is a copy and paste (slight alterations) of that code, and I haven't tested for your purposes. Essentially, it adds a handler to the entire document for the click event, then only executes the code if the element clicked on was not your textarea.

jquery click function inside form submit function

I have a form with number of submit type as images. Each image has a different title. I need to find out the title of the clicked image. But my click function inside form submit is not working.
My form is:
<form action='log.php' id='logForm' method='post' >
<?
for($j=1;$j<=5;$j++)
{
?>
<input type="image" src="<?=$img;?>" title="<?=$url;?> id="<?="image".$j?> class="images" />
<?
}
?>
</form>
Jquery:
$("#logForm").submit(function(e)
{
$(".advt_image").click(function(event) {
var href=event.target.title;
});
var Form = { };
Form['inputFree'] = $("#inputFree").val();
// if($("#freeTOS").is(":checked"))
Form['freeTOS'] = '1';
$(".active").hide().removeClass('active');
$("#paneLoading").show().addClass('active');
var url="http://"+href;
$.post('processFree.php', Form, function(data)
{
if(data == "Success")
{
$("#FreeErrors").html('').hide();
swapToPane('paneSuccess');
setTimeout( function() { location=url }, 2500 );
return;
}
swapToPane('paneFree');
$("#FreeErrors").html(data).show();
});
return false;
});
How can I get the title value of clicked image inside this $("#logForm").submit(function())?
How can I use the id of clicked image for that?
You can use event.target property
$("#logForm").submit(function(e)
alert($(e.target).attr('title'));
});
http://api.jquery.com/event.target/
[UPDATE]
I just realized it wouldn't work. I don't think there is a simple solution to this. You have to track the click event on the input and use it later.
jQuery submit, how can I know what submit button was pressed?
$(document).ready(function() {
var target = null;
$('#form :input[type="image"]').click(function() {
target = this;
alert(target);
});
$('#form').submit(function() {
alert($(target).attr('title'));
});
});
[Update 2] - .focus is not working, but .click is working
http://jsfiddle.net/gjSJh/1/
The way i see it, you have multiple submit buttons. Instead of calling the function on submit, call it on the click of these buttons so you can easily access the one the user chose:
$('input.images').click(function(e) {
e.preventDefault(); //stop the default submit from occuring
alert($(this).attr('title');
//do your other functions here.
});
// Runtime click event for all elements
$(document).on('vclick', '.control', function (e) { // .control is classname of the elements
var control = e.target;
alert(e.currentTarget[0].id);
});
if you are not getting proper message in alert, just debug using Firebug.
Check following code you can get the title of clicked image.
Single click
$(document).ready(function()
{
$('#logForm').submit(function(e){
$(".images").click(function(event) {
alert(event.target.title);
});
return false;
});
});
Double click
$(document).ready(function()
{
$('#logForm').submit(function(e){
$(".images").dblclick(function(event) {
alert(event.target.title);
});
return false;
});
});
add following ondomready in your rendering page
$(document).ready(function(){
$("form input[type=image]").click(function() {
$("input[type=image]", $(this).parents("form")).removeAttr("clicked");
$(this).attr("clicked", "true");
});
});
Now in your form's submitt action add follwing behaviour and yupeee!... you got it!....
$("#logForm").submit(function(e)
{
var title = $("input[type=image][clicked=true]",e.target).attr("title");
.....
.....
});

Ajax call not working on enter keypress, works only for click function

I have a ajax method of calling data from php file, i learned it from one of a blog, now it works file for submit button click function, but when i press enter the variables get shown in address bar and ajax process is not executed, Can any one please help me doing it on a press enter method....
This is my code:-
<script type='text/javascript'>//<![CDATA[
$(window).load(function(){
$(document).ready(function() {
$("input[name='search_user_submit']").click(function() {
var cv = $('#newInput').val();
var cvtwo = $('input[name="search_option"]:checked').val();
var data = { "cv" : cv, "cvtwo" : cvtwo }; // sending two variables
$("#SearchResult").html('<img src="../../involve/images/elements/loading.gif"/>').show();
var url = "../elements/search-user.php";
$.post(url, data, function(data) {
$("#SearchResult").html(data).show();
});
});
});
});//]]>
</script>
I have tried it by taking an if condition along with keypress event still its not working:-
if (e.keyCode == 13) { // Do stuff }
else { // My above code }
//In this also it seems that i am doing something wrong.
Can anybody please enlighten me oh how to do it.
My input field is:-
<input type="text" name="searchuser_text" id="newInput" maxlength="255" class="inputbox MarginTop10">
My submit button is:-
<input class="Button" name="search_user_submit" type="button" value="Search">
You can try with event.preventDefault(); for enter keypress.
Thanks.
When you type enter there is executed default onSubmit handler for a form. You can use submit jquery function to handle both enter and click on submit button.
$("form").submit(function() {
var cv = $('#newInput').val();
var cvtwo = $('input[name="search_option"]:checked').val();
var data = { "cv" : cv, "cvtwo" : cvtwo }; // sending two variables
$("#SearchResult").html('<img src="../../involve/images/elements/loading.gif"/>').show();
var url = "../elements/search-user.php";
$.post(url, data, function(data) {
$("#SearchResult").html(data).show();
});
return false;
});
return false in this function will prevent submit of the form.

Categories