I'm trying to figure out a way to load 1 single tab(tabs by jQuery) without reloading all the others.
The issue is that I have a submit button and a dropdown that will create a new form, and when on this new form 'OK' or 'CANCEL' is clicked, it has to get the original form back.
The code to load a part of the page that I found is this:
$("#tab-X").load("manageTab.php #tab-X");
But now I would like to know how to use this in combination with the $_POST variable and the submit-button
Clarification:
I have a .php(manageTab.php) which contains the several tabs and their contents
I have in each of these tabs a dropdown containing database-stored information(code for these dropdowns is stored in other pages)
for each of these dropdowns, there exists a submit button to get aditional information out of the DB based on the selection, and put these informations in a new form for editing
this new form would ideally be able to be submitted without reloading everything except the owning tab.
Greetings
<script>
$(document).ready(function() {
$("#form1").submit(function(){
event.preventDefault();
$.post('data.php',{data : 'dummy text'},function(result){
$("#tab-X").html(result);
});
});
});
</script>
<form id="form1">
<input id="btn" type="submit">
</form>
I am not totally understand your question, but as per my understanding you can't load one tab with form submit. Its normally load whole page.
What you can do is, use ajax form submit and load the html content as per the given sample code.
$.ajax({
url: url, // action url
type:'POST', // method
data: {data:data}, // data you need to post
success: function(data) {
$("#tab_content_area").html(data); // load the response data
}
});
You can pass the html content from the php function (just need to echo the content).
AJAX is what you are looking for.
jQuery Ajax POST example with PHP
Also find more examples about ajax on google.
Example: Let me assume you have a select menu to be loaded in the tab.
You will need to send a request to your .php file using jquery, and your php file should echo your select menu.
In your jQuery,
<script>
$.post(url, { variable1:variable1, variable2:variable2 }, function(data){
$("#tab-X").html(data);
//data is whatever php file returned.
});
});
$("#form_id").submit(function(){
return false;
});
</script>
I mean whatever your options are, you will need to do the following in your .php file,
Echo that html code in your PHP script.
echo "<select name='".$selector."'>
<option value='".$option1."'>Option1</option>
<option value='".$option2."'>Option2</option>
<option value='".$option3."'>Option3</option>
</select>";
This would be returned to jQuery, which you may then append wherever you want.
Related
I have a dropdown selector on a page that allows a user to select a template type (for example, "human" or "dog").
Based on what template is selected, different fields will need to populate below the dropdown (for example, text fields for "parents names" or a dropdown list for "breed") that are unique to each template.
I will have a button that the user will click once the data fields are put in that will output data to an "output div" section of the same page when clicked (no POSTing data as it's not being saved). The output will have different output logic based on the selected template (for example, "I'm a human named X" or "I'm a dog, my breed is Y").
My real program will be more complex and each template will have a php class that stores all of the logic. Since I will be dealing with both php objects and variables gathered by jquery, what's the best way to let them interact?
For 1., I know I can do something easy like -
var selected_template = $('#my-template-dropdown :selected').text();
if (selected_template == 'Human'){
$('#my-fields').html('<?php echo HumanTemplate::render_fields(); ?>');
}
which is easy enough, but for 2. I need to pass variables from jquery to php, then return output back to jquery.
I would like some advice on the easiest way to do this before I start down the wrong path.
HTML
Allow the user to select the template type:
<form>
<select id="my-template-dropdown" name='template'>
<option value="dogs">Dogs</option>
<option value="humans">Humans</option>
</select>
</form>
<div id="my-fields"><div>
<div id="output"><div>
jQuery
Any time the user changes the template selection, request new content to display via AJAX, and insert it on the current page so the page does not have to refresh:
$('#my-template-dropdown').on('change', function() {
var template = $(this).val();
$.ajax({
url: 'http://your-site/path/to/' + template,
success: function(resp) {
$('#my-fields').html(resp);
}
});
});
PHP
http://your-site/path/to/template simply generates the HTML you want to display for that template, eg (just an example, don't know if this is suitable for your app):
if ($template == 'humans') {
echo HumanTemplate::render_fields();
} else if ($template == 'dogs') {
echo DogTemplate::render_fields();
}
For part 2, assuming all the logic you refer to is in the template rendered by PHP, you could then handle it with jQuery. This is pretty crude, you probably need something more sophisticated (eg a full template which you swap variables into?), but you get the idea:
$('#output').on('click', 'button', function(e) {
e.preventDefault();
// fields in your template which the user will fill
var species = $('#species').val(),
title = $('#title').val();
// Probably better to have this text as a template in your source
$('#output').html("I'm a " + species + ' named ' + title);
});
NOTE the gotcha in the event handler. Event handlers will only attach to elements that exist at the time the handler is defined. Since the content is injected after page load, an event handler like $('#button).on('click', function() {... would have no effect when clicking a button inserted via AJAX. The syntax here attaches to the parent #output div, which does exist at page load, and filters for clicks on a button. See the jQuery event delegation docs for more info.
Another option would be to POST the submitted data to some PHP controller, which generates and returns the output. This way all your logic is in the one place. For example, here the user's click will query the same PHP file which generated the initial template, this time including the values the user has entered. It could then generate the required output and return it, to be inserted on the page. You'd need to update the PHP so it can determine which of these cases it is handling (eg hidden field?); alternatively if you wanted to keep those separate you could hit another PHP file all together.
$('#output').on('click', 'button', function(e) {
var template = $('#my-template-dropdown').val(),
$form = $('form'),
data = $form.serialize(); // Values from all fields user has entered
$.ajax({
url: 'http://your-site/path/to/' + template,
data: data,
success: function(resp) {
$('#output').html(resp);
}
});
});
The best way to pass data from jQuery to PHP, is by using AJAX.
Mozilla has an excellent guide on getting started, that i recommend you follow.
An example of how you can achieve what you are requesting, is by trying the following:
var selected_template = $('#my-template-dropdown :selected').text();
var ajaxurl = 'ajax.php',
data = {'select_template': selected_template };
$.post(ajaxurl, data, function (response) {
console.log(response);
});
On the PHP end (Ajax.php in my example) It could look something like this
if(isset($_POST['select_template'])) {
// do something with the input from jQuery
$selected_template = $_POST['select_template'];
// return the result back to the client
echo $seleted_template;
}
?>
$selected_template will be sent back to the client, and response in the AJAX function will be whatever the server returned. So the console.log(response) should display whatever was being sent to the server
You can have a look to the function wp_localize_script.
This function make available PHP datas to JS files on the page load through the wp_enqueue_scripts action.
This will not work like an Ajax request and only populate data for a specific handle on page load. But you can mix this method with ajax in the same script.
Hope it helps even it doesn't seems to fit to your case.
As your class not fires on page load, you can use the action wp_ajax_{custom _action} and wp_ajax_nopriv_{custom_action} . For example, that's usually used to populate multiple dropdown, each time an event is trigger by the user, a php function returns result the js script.
I've got this problem that the form refreshes on submit, i dont want it to refresh but i do want it to submit. any of you know what i could do ?
click this link to an older post about this.
<form method="post" id="radioForm">
<?
foreach($result as $radio):
printf('
<button type="submit"
href="#radio"
name="submitRadio"
value="'.$radio['id'].'">
Go!
</button>
');
endforeach;
?>
</form>
<script type="text/javascript">
$('#radioForm').submit(function(event) {
event.preventDefault();
$.ajax({
url:'index.php',
data:{submitRadio:[radiovalue]},
type:'POST',
success:function(response) {
/* write your code for what happens when the form submit */
});
});
</script>
</div>
Use submit() handler and pass the value of your button to your other script
First set the id on the form.
<form method="post" id="formId">
Then bind a listener
$( "#formId" ).submit(function( event ) {
event.preventDefault();
//This is where you put code to take the value of the radio button and pass it to your player.
});
To use this you need jQuery.
You can read more about this handler here: http://api.jquery.com/submit/
This is the default behavior of a HTML <form> on submit, it makes the browser POST data to the target location specified in the action attribute and loads the result of that processing to the user.
If you want to submit the form and POST the values behind the scenes without reloading the page, you have to disable the default behavior (the form submit) and employ the use of AJAX. This kind of functionality is available readily within various JavaScript libraries, such as a common one called jQuery.
Here is the documentation for jQuery's AJAX functionality http://api.jquery.com/jquery.ajax/
There are lots of tutorials on the interwebs that can introduce you to the basic use of jQuery (Including the library into your HTML pages) and also how to submit a form via AJAX.
You will need to create a PHP file that can pick up the values that are posted as a result of the AJAX requests (such as commit the values to a database). The file will need to return values that can be picked up within your code so that you know if the request was un/successful. Often the values returned are in the format JSON.
There are lots of key words in this answer that can lead you on your way to AJAX discovery. I hope this helps!
use ajax like this of jquery
$('form').submit(function(event) {
event.preventDefault();
$.ajax({
url:'index.php',
data:{submitRadio:[radiovalue]},
type:'POST',
success:function(response) {
/* write your code for what happens when the form submit */
}
});
});
This might look as the dumb question, but I hope it's not.
I have a PHP file delete.php that will delete selected users (it is not ready yet, but I will write it after I finish my HTML model).
So, on my HTML model I have the following:
<li><button class="sexybutton">
<span><span><span class="add">Add</span></span></span>
</button></li>
This sexybutton is the button styling I've downloaded. So, how to make it post the selected user list to a PHP file without putting a <form> tag inside (it will brake all the structure otherwise and will not be valid)?
I could use jQuery (or JS), but I still do not know how to do this. If PHP would have something like "onclick" function :)
Thank you in advance.
You can send an ajax request without a form, like this :
$('.sexybutton').on('click', function() {
var users = $.map( $('li.users'), function(el) {
return $(el).text();
});
$.ajax({
url : 'delete.php',
data: users
});
});
just create the data you need, and send it ?
<form id="your_form">
<ul>
<li><button class="sexybutton" onclick="$('#your_form').submit();">
<span><span><span class="add">Add</span></span></span>
</button></li>
</ul>
</form>
explanation:
wrap your existing code with form element, give some unique id to your form (e.g. your_form) and then add attribute onclick to your button and fill it with some jquery syntax (or pure javascript if you wish):
$('#your_form').submit();
this will do the submit job.
Do you know a way to display a php result inside a div dynamically, without refreshing the page?
For example, we have 2 divs: one on the top half of the page and one on the bottom of the page. The top one contains a form with 3 input fields. You type some values inside, then press a button. When you press the button, the bottom div displays the values without refreshing the page.
You can't do it with pure PHP because PHP is a static language. You have to use Javascript and AJAX. I recommend using a library like Zepto or jQuery to make it easy to implement like this:
<form>
<input name="search" />
<input type="submit" />
</form>
<div id="div2"></div>
<script>
// When the form is submitted run this JS code
$('form').submit(function(e) {
// Post the form data to page.php
$.post('page.php', $(this).serialize(), function(resp) {
// Set the response data into the #div2
$('#div2').html(resp);
});
// Cancel the actual form post so the page doesn't refresh
e.preventDefault();
return false;
});
</script>
You can accomplish it using AJAX. With Ajax you can exchange data with a server, make asynchronous request without refreshing the page.
Check this out to see how it can be implemented using Jquery:- http://api.jquery.com/jQuery.ajax/
I'm dabbling in JQuery, and have run up against an issue I'm not quite able yet to figure out. Here is the context:
I have a HTML form, utilising MySQL & PHP, used to edit a CMS post. This post would have a list of attachments (eg. images for a gallery, or downloadable files). Using JQuery, the user can click on these list item elements and edit the details of each attachment in a revealed div (eg. delete image, add capton, etc).
Currently when the user opts to delete an attachment, I simply fade its opacity and provide a new option to the user to 'undo' the delete. Upon submission of the complete parent form (the CMS post), I want to gather all the attachments still marked for deletion, and submit their GUID's to the PHP script that is doing all the rest of the post updating for me.
Option A:
Is it possible to submit a JQuery array to a PHP script alongside the data being sent naturally to the action script by the form inputs?
Option B:
Is it possible to fill / empty a (hidden) form input array dynamically with JQuery, which could then be submitted naturally to the action script with everything else?
I am currently at the stage where I am filling a Javascript array with the necessary GUIDs, but now don't know what to do with it.
//populate deleted attachments array
$(document).ready(function() {
$('#post-editor').submit(function() {
var arrDeleted = [];
$('.deleted-att').each(function(){
arrDeleted.push({guid: $(this).attr("data-guid")});
});
//do something with array
});
});
JSON.stringify the arrDeleted and put them in a hidden field in the form, that will be submitted.
$('#post-editor').submit(function() {
var arrDeleted = [];
$('.deleted-att').each(function(){
arrDeleted.push({guid: $(this).attr("data-guid")});
});
$('#post-hidden').val(JSON.stringify(arrDeleted));
});
Somewhere in your html:
<form id="post-editor">
<input type="hidden" id="post-hidden" name="post-hidden" />
<!-- ... other fields ... -->
</form>
Then json_decode($_POST['post-hidden']) on the server to get the array.
create a hidden field in your form..put the arrDeleted value in your input through jquery
and post the form..use json_decode() to get the posted value...
<input type="hidden" id="hidden"/>
JQUERY
$(document).ready(function() {
$('#post-editor').submit(function() {
var arrDeleted = [];
$('.deleted-att').each(function(){
arrDeleted.push({guid: $(this).attr("data-guid")});
});
$('#hidden').val(JSON.stringify(arrDeleted));
});
});
The easiest to do what you want would be to add a hidden input field to your HTML form
Then in jQuery do something like this
$('form').submit(function() {
$('#hidden_id_field').val( arrDeleted.join(',') );
});
arrDeleted in this case being your array you've already setup. It would sent a comma separated list then in your PHP you split up the values and act as you want.
Usually I just do AJAX and send JSON to my app. But the above approach will work if you really want to go about it like that. And it has the advantage of not actually deleting anything on the server until you submit the form.
You may be looking to do this with a traditional form submit and refresh, but if you're willing to submit the request asynchronously, you can use jQuery to submit the form and serialize the array of deleted items:
var form = $('#post-editor');
form.submit(function() {
var arrDeleted = [];
$('.deleted-att').each(function(){
arrDeleted.push({ // The format $.serializeArray produces.
name: "deleted",
value: $(this).attr("data-guid")
});
});
var formData = form.serializeArray();
// Add values to existing form data
formData = formData.concat(arrDeleted);
$.ajax({
url: form.attr('action'),
data: formData
// Other ajax options
});
});
On the PHP side, referring to $_REQUEST['deleted'] will return an array of GUIDs.