.submit() without reloading page - php

I am trying do some file upload using jquery. The upload box have to be in the dialog box.
Now I just want to know after I click on the dialog's upload button. How can I submit yet the page do not load.
I tried using this
$('#uploadForm').submit().preventDefault();
It has not action at all.
html
<script>
$( "#dialog-upload" ).dialog({
autoOpen: false,
height: 200,
width: 350,
modal: true,
buttons: {
"Upload": function() {
var bValid = true;
bValid = bValid && checkCSV()
if(bValid){
**$('#uploadForm').submit().preventDefault();**
}
$( "#dialog-upload" ).dialog( "close" );
},
Cancel: function() {
allFields.val( "" ).removeClass( "ui-state-error" );
$( this ).dialog( "close" );
}
},
close: function() {
allFields.val( "" ).removeClass( "ui-state-error" );
$( this ).dialog( "close" );
}
});
</script>
<div id="dialog-upload" title="Upload csv file">
<form>
<fieldset>
<form action='ajax.php' id = 'uploadForm' method='post' enctype='multipart/form-data'>
<input type="text" name="file" id="fileUpload" size = 30 class="text ui-corner-all" />
</form>
</fieldset>
</form>
</div>
php
if (isset($_FILES['file'])) {
echo "success";
}

Use the EVENT delegation for your form submit
$('#uploadForm').submit(function( e ){
e.preventDefault(); // browser 'submit' event behavior prevented
});
Than do:
"Upload": function() {
var bValid = true;
bValid = bValid && checkCSV()
if(bValid){
$('#uploadForm').submit();
}
// ......

You can bind something to the submit event prior to submitting.
$(function() {
$('#uploadForm').submit(function(evt) {
evt.preventDefault();
});
});
Then just call .submit() without the preventDefault() in your original location.

Related

jquery variable in php echo

I have this jquery script (slider):
<script>
$( function() {
$( "#slider-range-max" ).slider({
range: "max",
min: 1,
max: 25,
value: 1,
slide: function(event, ui) {
$("#amount").val(ui.value);
}
});
$( "#amount" ).val( $("#slider-range-max").slider("value") );
});
</script>
This is my html outout:
<input type="text" id="amount" readonly style="border:0; color:#f6931f; font-weight:bold;">
<div id="slider-range-max"></div>
I want the value of my slider stored as a php variable.
To call upon a php code that might have some logic in it, you need to have your html and javascript in a file, then your php code in a different file, like so :
html_file.php (contains only html template and javascript).
html part:
<input type="text" id="amount" readonly style="border:0; color:#f6931f; font-weight:bold;">
<div id="slider-range-max"></div>
Javascript part:
<script>
$( function() {
$( "#slider-range-max" ).slider({
range: "max",
min: 1,
max: 25,
value: 1,
slide: function( event, ui ) {
$( "#amount" ).val( ui.value );
},
change: function(event, ui) {
$.post('php_file.php', {slider_val: ui.value}).done(
function(result) {
//your php code sends result back here.
//do something with result.
console.log(result);
}
);
}
});
$( "#amount" ).val( $( "#slider-range-max" ).slider( "value" ) );
});
</script>
php_file.php (contains the php code and logic).
you then retrieve the value in your php code like so:
<?php
//$slider_val contains the value of your slider
$slider_val = $_POST['slider_val'];
//you can output the value back to your javascript like so
echo $slider_val;
You can send the input value to php like this
HTML
<input type="text" placeholder="Amount" onkeyup="send(this.value)">
SCRIPT
<script>
function send(str) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("value").innerHTML = this.responseText;
}
};
xmlhttp.open("GET", "send.php?value=" + str, true);
xmlhttp.send();
}
</script>
PHP
$value = $_REQUEST["value"];
echo $value;
Try this. Hope it helps to solve your problem.

Pass php variable to window.open in ui-dialog

I am using a ui-dialog and want to pass a php variable to a url if the Delete button is clicked. I have looked at a large number of other answers to similar questions but nothing seems to quite fit what I am trying to do.
The code below works correctly for the link shown, but doesn't work when I try to pass the php variable to the url.
This code works fine
$( function() {
$( "#dialog-message" ).dialog({
modal: true,
buttons: {
"Delete": function() {
window.open('https://example.com/page.php?id=');
},
Cancel: function() {
$( this ).dialog( "close" );
}
}
});
});
I have tried using this but it doesn't work
window.open('https://example.com/page.php?id=<?php echo $id?>')
Try add ";" at the end.
<?php echo $id;?>
Assuming your above code is in .php file, try below code:
<script>
$( function() {
$( "#dialog-message" ).dialog({
modal: true,
buttons: {
"Delete": function() {
window.open("https://example.com/page.php?id=<?php echo $id; ?>");
},
Cancel: function() {
$( this ).dialog( "close" );
}
}
});
});
</script>
You can assign pageid in input hidden fields like below.
After you need to get this fields value using val() function.
<input type="hidden" value="<?php $id; ?>" id="pageId" />
$( function() {
var PageId = $('#pageId').val();
$( "#dialog-message" ).dialog({
modal: true,
buttons: {
"Delete": function() {
window.open('https://example.com/page.php?id='+PageId);
},
Cancel: function() {
$( this ).dialog( "close" );
}
}
});
});

"return false" doesn't work for jQuery post form submission when script is loaded from external source

I have these two forms:
<form id='EnableBackgroundCrossfadeForm' action='BgCFenable.php' method='post'>
<input id='BgCFenable' class='DisableD_Button' type='submit' value='Enable'>
</form>
and:
<form id='DisableBackgroundCrossfadeForm' action='BgCFdisable.php' method='post'>
<input id='BgCFdisable' class='DisableButton' type='submit' value='Disable'>
</form>
And this is the external POST.js file:
$("#BgCFdisable").click(function(){
$("#BgCFLog").animate({"max-height":"100px"}, 300);
$("#BgCFLog").html("<img src='Resources/Images/Loader02.gif'/>");
$.post($("#DisableBackgroundCrossfadeForm").attr("action"),
$("#DisableBackgroundCrossfadeForm").serializeArray(),
function(data){
if(data == "DISABLED"){
$("#BgCFLog").html("Background Crossfading disabled!");
$( "#BgCFdisable" ).attr("disabled", "disabled");
$( "#BgCFdisable" ).switchClass( "DisableButton", "DisableD_Button", 1000, "easeInOutQuad" );
$( "#BgCFenable" ).removeAttr("disabled");
$( "#BgCFenable" ).switchClass( "DisableD_Button", "EnableButton", 1000, "easeInOutQuad" );
}
});
$("#DisableBackgroundCrossfadeForm").submit(function(){
return false;
});
});
$("#BgCFenable").click(function(){
$("#BgCFLog").animate({"max-height":"100px"}, 300);
$("#BgCFLog").html("<img src='Resources/Images/Loader02.gif'/>");
$.post($("#EnableBackgroundCrossfadeForm").attr("action"),
$("#EnableBackgroundCrossfadeForm").serializeArray(),
function(data){
if(data == "ENABLED"){
$("#BgCFLog").html("Background Crossfading enabled!");
$( "#BgCFdisable" ).removeAttr("disabled");
$( "#BgCFdisable" ).switchClass( "DisableD_Button", "DisableButton", 1000, "easeInOutQuad" );
$( "#BgCFenable" ).attr("disabled", "disabled");
$( "#BgCFenable" ).switchClass( "EnableButton", "DisableD_Button", 1000, "easeInOutQuad" );
}
});
$("#EnableBackgroundCrossfadeForm").submit(function(){
return false;
});
});
The main idea is that this work perfect if I put the script between <script></script> tags at the end of my INDEX.php file (where I have the forms) in the body. With other words this works just if the jQuery script is "internal" and not loaded from and external *.js file.
If is loaded externally, submiting the form will redirect me to the BgCFenable.php/BgCFdisable.php instead of remaining on the INDEX.php page, where I need the resulted data to be displayed.
How can I make this work loading the script externally without redirecting on submission?
I figured it out in the end.
Those are the forms:
<form id='EnableBackgroundCrossfadeForm' onsubmit='return EnableBGCF();'>
<input id='BgCFenable' class='DisableD_Button' type='submit' value='Enable' disabled='disabled'>
</form>
and:
<form id='DisableBackgroundCrossfadeForm' onsubmit='return DisableBGCF();'>
<input id='BgCFdisable' class='DisableButton' type='submit' value='Disable'>
</form>
And this is the external .js file:
function EnableBGCF() {
$("#BgCFLog").animate({"max-height":"100px"},300);
$("#BgCFLog").html("<img src='Resources/Images/Loader02.gif'/>");
$.ajax({type:'POST', url: 'BgCFenable.php', data:$('#EnableBackgroundCrossfadeForm').serialize(), success: function(response) {
$('#BgCFLog').html("Background Crossfading <span style='color: #c9e52d'>enabled!</span>");
$( "#BgCFdisable" ).removeAttr("disabled");
$( "#BgCFdisable" ).switchClass( "DisableD_Button", "DisableButton", 1000, "easeInOutQuad" );
$( "#BgCFenable" ).attr("disabled","disabled");
$( "#BgCFenable" ).switchClass( "EnableButton", "DisableD_Button", 1000, "easeInOutQuad" );
}});
return false;
}
function DisableBGCF() {
$("#BgCFLog").animate({"max-height":"100px"},300);
$("#BgCFLog").html("<img src='Resources/Images/Loader02.gif'/>");
$.ajax({type:'POST', url: 'BgCFdisable.php', data:$('#DisableBackgroundCrossfadeForm').serialize(), success: function(response) {
$('#BgCFLog').html("Background Crossfading <span style='color: #e52d58'>disabled!</span>");
$( "#BgCFdisable" ).attr("disabled","disabled");
$( "#BgCFdisable" ).switchClass( "DisableButton", "DisableD_Button", 1000, "easeInOutQuad" );
$( "#BgCFenable" ).removeAttr("disabled");
$( "#BgCFenable" ).switchClass( "DisableD_Button", "EnableButton", 1000, "easeInOutQuad" );
}});
return false;
}
Now it's working. Thanks for help anyway!
You need to pass in the event for the click and prevent default so the form doesn't submit..
So, on:
$("#BgCFdisable").click(function(){...
You need to do:
$("#BgCFdisable").click(function(e){
e.preventDefault();...
Same, on:
$("#BgCFenable").click(function(){...
You need to do:
$("#BgCFenable").click(function(e){
e.preventDefault();...

Why is jquery dialog-message refreshing my page unwantedly (inside form)

i am trying to embed a simple jquery dialog-message into a form. The dialog should only show some additional information and not interact with the form in any way except beeing called via a button from inside the form.
My problem is the following: If the dialog is called from inside the form the whole page gets refreshed instantly, not showing the dialog at all and clearing all form fields. If the button is outside the form everything is working just fine.
The dialog content is being loaded via templates like this:
<script>
$(function() {
var dlg = $( "#dialog-message" ).dialog({
autoOpen: false,
width: '80%',
closeOnEscape: false,
modal: true,
buttons: {
Ok: function() {
$( this ).dialog( "close" );
}
},
open: function() {
// Content laden...
$("#dialog-message").load('template.html', function() {}).dialog()
}
});
$( "#opener" ).click(function() {
$( "#dialog-message" ).dialog( "open" );
});
});
</script>
The form integration:
<form method="post" name="post" action="index.php?site=bewerbung">
<table width="100%" border="0" cellspacing="1" cellpadding="2" bgcolor="$border">
...
</tr>
<tr bgcolor="$bg1">
<td height="25"> </td>
<td><input class="input" type="checkbox" name="rules" id="rules" value="1" /><button id="opener">Regeln</button></td>
</tr>
</table>
</form>
Your button submits the form, so you need to prevent the default button action via JavaScript:
$("#opener").on('click', function(e) {
dlg.dialog("open");
e.preventDefault();
});
You don't mentioned what jQuery (UI) version you are using. My code above is for the newer versions.
Here's the demo.
Generally for Buttons and Submit-inputs: you can prevent the refreshing of the page, if you place "return false;" on the end of your function. In your case
$( "#opener" ).click(function() {
$( "#dialog-message" ).dialog( "open" );
return false;
});

jQueryUI Dialog with ajax-injected html selector

All code below is a stand-alone working example (greatly simplified) of what I am trying to do. If anyone copy/pastes the below code blocks into 3 separate files, the code is fully self-contained-- just remember to reference/include test5.js and the jquery libraries in script tags at top of document.
SUMMARY: HTML div injected via Ajax not opening in the jQuery UI dialog widget.
Objective: On document load, jquery-ajax injects an html form (ultimately, it will retrieve appropriate form values from DB which is the reason for ajax). A div with id="clickme" is injected with the html. Clicking the div should open the dialog.
Problem: The jQueryUI .dialog does not appear. I put an alert box inside the click event, and that fires. But the dialog remains elusive.
Therefore, problem appears to be the fact that the HTML is injected. What am I missing?
HTML: index.php
<div id="putit_here">
</div>
JAVASCRIPT/JQUERY: test5.js
$(function() {
var pih = $('#putit_here');
$.ajax({
type: "POST",
url: "ajax/ax_test5.php",
data: 'contact_id=1',
success:function(data){
pih.html(data);
var etc1 = $( "#editThisContact_1" );
/* *****************************************************************
Moving Dialog up >here< was correct answer.
********************************************************************
etc1.dialog({
autoOpen: false,
height: 400,
width: 600,
modal: true,
buttons: {
Cancel: function() {
$( this ).dialog( "close" );
}
},
close: function() {
alert('DialogClose fired');
}
}); //end .Dialog
****************************************************************** */
}
}); //End ajax
/* **** This is where I had it previously ***** */
etc1.dialog({
autoOpen: false,
height: 400,
width: 600,
modal: true,
buttons: {
Cancel: function() {
$( this ).dialog( "close" );
}
},
close: function() {
alert('DialogClose fired');
}
}); //end .Dialog
$(document).on('click', '#clickme', function(event) {
alert('HereIAm...');
$( "#editThisContact_1" ).dialog( "open" );
}); //End #clickme.click
}); //End document.ready
AJAX - ax_test5.php
$rrow = array();
$rrow['contact_id'] = 1;
$rrow['first_name'] = 'Peter';
$rrow['last_name'] = 'Rabbit';
$rrow['email1'] = 'peter.rabbit#thewarren.nimh.com';
$rrow['cell_phone'] = '+1.250.555.1212';
$r = '
<div id="editThisContact_'.$rrow['contact_id'].'" style="display:none">
<p class="instructions">Edit contact information for <span class="editname"></span>.</p>
<form name="editForm" onsubmit="return false;">
<fieldset>
<span style="position:relative;left:-95px;">First Name:</span><span style="position:relative;left:10px;">Last Name:</span><br />
<input type="text" id="fn_'.$rrow['contact_id'].'" value="'.$rrow['first_name'].'" name="fn_'.$rrow['contact_id'].'">
<input type="text" id="ln_'.$rrow['contact_id'].'" value="'.$rrow['last_name'].'" name="ln_'.$rrow['contact_id'].'"><br /><br />
<span style="position:relative;left:-120px;">Email:</span><span style="position:relative;left:30px;">Cell Phone:</span><br />
<input type="text" id="em_'.$rrow['contact_id'].'" value="'.$rrow['email1'].'" name="em_'.$rrow['contact_id'].'">
<input type="text" id="cp_'.$rrow['contact_id'].'" value="'.$rrow['cell_phone'].'" name="cp_'.$rrow['contact_id'].'">
</fieldset>
</form>
</div>
';
echo $r;
EDIT:
Updated question to move dialog definition inside AJAX success callback. Did not completely solve problem, though. The dialog now appears if I change the autoOpen flag to true, but that is not how the script must work. The dialog still does not open upon clicking the (injected) #clickme div.
EDIT 2:
My bad. At first I thought it didn't work, but then found that my live test and posted SO question varied in one line: how the .dialog("open") was being called. In live code, it was still using the var: etc1.dialog("open") -- but in post above the selector was fully referenced: $('#editThisContact_1').dialog("open"). The posted syntax was correct. Thanks gents, and also itachi who got me to check chrome console.
You are trying to initialize a dialog on an element before the element exists. You need to initialize the dialog on "#editThisContact_1" after your ajax call comes back successfully.
Like this:
....
success:function(data){
pih.html(data);
//now your DIV is actually there so init the dialog
var etc1 = $( "#editThisContact_1" );
etc1.dialog({
autoOpen: false,
height: 400,
width: 600,
modal: true,
buttons: {
Cancel: function() {
$( this ).dialog( "close" );
}
},
close: function() {
alert('DialogClose fired');
}
}); //end .Dialog
}

Categories