Create another div and variable onChange using jQuery - php

below is a code that gets the value of the selected option and shows the php file in the div. How can I add another file and another div (secondfile) to be displayed ?
$('#firstresult').empty().addClass("loading")
.load(val + '.php', { value: val }, function(){
$("#firstresult").removeClass("loading");
}));
$('#secondresult').empty().addClass("loading")
.load(val + 'b.php', { value: val }, function(){
$("#secondresult").removeClass("loading");

To show a loading image, you could add a class before load() and remove upon load() complete.
JS
Changes to the lines that begin $('#firstresult') and $('#secondresult').
$('#firstresult').empty().addClass("loading")
.load(val + '.php', { value: val }, function(){
$("#firstresult").removeClass("loading");
}));
$('#secondresult').empty().addClass("loading")
.load(val + '.php', { value: val }, function(){
$("#secondresult").removeClass("loading");
}));
CSS
.loading { height:24px; background:#fff url('loading.gif') 50% 50% no-repeat; }

Create / Append div in results div as child and load content from php script to it:
$(document).ready(function() {
$('#termid').change(function() {
var val = $(this).val();
$('results').append('<div id="result' + val '"></div>');
$('#result' + val).load(val + '.php',
{
value: val
});
});
});
not tested

Related

HTML form submit not working after being loaded with ajax

so I am loading a portion of a page using jquery/ajax.
On the page the user sees, there is a "menu" where they select the date of the signup form they want to see. All the forms are hosted on another page, each one inside a div id'd with the respective date of the form. When the user clicks and item on the menu, there is an ajax call that displays the correct form on the user's page, pulling it from the other page by it's parent div and id.
The plugin I am using for the signup forms (it is a Wordpress site) has the page reload when you click Sign up, which then takes you to a form to fill out. I have it so that the user's page does not reload, but via ajax shows the form. This all works great - the only problem now is when the user clicks to submit the form. This should be a normal form submit not using ajax, as I am not sure how to modify the plugin code to utilize it. For some reason, the form is never actually submitted although the user's page does reload.
*NOTE: I am currently using the same exact signup form for each date, but once it is functional it will be a different signup form for each. This should not effect any functionality.
link to page user sees: summitsharks.net/volunteer-signup-page
link to page forms are hosted on: summitsharks.net/formhost
jquery/ajax code:
;(function($){
var ahref1;
$(document).ready(function(){
$(document).on('click', '.entry-content li a', function(e){
e.preventDefault();
ahref1 = $(this).attr('href');
$('#formloader').load('/formhost ' + ahref1);
return false;
});
});
$(document).ready(function(){
$(document).on('click', '.entry-content #formloader a', function(e){
e.preventDefault();
var ahref2 = $(this).attr('href');
$('#formloader').load(ahref2 + ' ' + ahref1);
return false;
});
});
})(jQuery);
PHP code of file that (I think) handles form submit:
http://pastebin.com/PeXB4Afi
I am looking for a solution that successfully signs the user up. If somebody knows how to alter the plugin code to accept ajax submission, or normal submission that actually works, either one is perfectly fine with me.
Thanks a lot for looking through and thanks in advance for your help!
The form is expected to be posted from it's original URL, including the HTTP GET parameters ?sheet_id=1&task_id=1&date=2016-06-30. Updating the form's action attribute to make it post to the proper URL can be done by changing
$('#formloader').load(ahref2 + ' ' + ahref1);
to
$('#formloader').load(ahref2 + ' ' + ahref1, function() {
$('#formloader form').attr("action", ahref2 + ' ' + ahref1 );
});
However, using AJAX to post the form, this can be skipped:
var ahref = $(this).attr('href') + ' ' + ahref1;
$('#formloader').load( ahref, function() {
$("#formloader form").on('submit', function(e) {
e.preventDefault();
$.ajax( {
url: ahref,
type: 'POST',
data: $.param( formdata( $(this) ) ),
success:function(data,status,jqXHR) { $("#formloader").html( data ) }
});
return false;
})
})
The utility method formdata (see code snippet below) converts jQuery's serializeArray() result to a proper hash.
In the working example below, I've moved the installation of form click handlers into the .load completion handler, rather than relying on jQuery to fire a second document ready event after injecting the form.
;jQuery(function($) {
$('.entry-content li a').off('click').on('click', function(e) {
var ahref1 = $(this).attr('href');
$('#formloader').load( "/formhost " + ahref1, function() {
$('.entry-content #formloader a').off('click').on('click', function(e) {
e.preventDefault();
var ahref = $(this).attr('href') + ' ' + ahref1;
$('#formloader').load( ahref, function() {
$("#formloader form").on('submit', function(e) {
e.preventDefault();
$.ajax( {
url: ahref,
type: 'POST',
data: $.param( formdata( $(this) ) ),
success:function(data,status,jqXHR) { $("#formloader").html( data ) }
});
return false;
})
});
return false;
});
});
return false;
});
});
function formdata(form) {
var data = {};
for ( var i in d = form.serializeArray() )
data[d[i].name] = d[i].value;
return data;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
UPDATE: Here is a code snippet that can be pasted in the browser's Javascript console:
$ = jQuery;
$('.menu-volunteermenu-container li a').off('click').on('click', function (e) {
loadFormSelector($(this).attr('href'));
return false;
});
$('#formloader').on('load', function(){console.log("FORMLOADER UPDATD")});
function loadFormSelector(ahref1)
{
console.log("Loading form selector");
$('#formloader').load('/formhost ' + ahref1, function ()
{
console.log('form selector loaded');
$('.entry-content #formloader a').off('click').on('click', function (e)
{
e.preventDefault();
loadForm(ahref1, $(this).attr('href') );
return false;
});
});
}
function loadForm(ahref1, ahref2)
{
var ahref = ahref2 + ' ' + ahref1;
console.log('Loading form', ahref);
$('#formloader').load(ahref, function () {
console.log('form loaded', arguments);
$('#formloader form').on('submit', function (e) {
e.preventDefault();
$.ajax({
url: ahref,
type: 'POST',
data: $.param(formdata($(this))),
success: function (data, status, jqXHR) {
$('#formloader').html( $(data).find( ahref1 ) )
}
});
return false;
});
$('#formloader a').on('click', function () {
loadFormSelector(ahref1);
});
return false;
});
}
function formdata(form) {
var data = {
};
for (var i in d = form.serializeArray())
data[d[i].name] = d[i].value;
return data;
}
It is refactored to show the 2-layer approach more clearly.

Ajax image using jquery form.js

I am working with this piece of code. Here I am using jQuery, Jquery form.js, and jQueryUI. The task is to upload an image in the upload folder and store the path of the image along with its position which is set by users (jQueryUI draggable is used for this). It works just fine. But I don't know exactly how it works.
Can anyone explain to me how we are grabbing the dragged position set by users and how the whole thing is working all together. If you need to see the PHP script I can share thattoo. Thanks
$(document).ready(function () {
/* Uploading Profile BackGround Image */
$('body').on('change', '#bgphotoimg', function () {
$("#bgimageform").ajaxForm({
target: '#timelineBackground',
beforeSubmit: function () {},
success: function () {
$("#timelineShade").hide();
$("#bgimageform").hide();
},
error: function () {
}
}).submit();
});
/* Banner position drag */
$("body").on('mouseover', '.headerimage', function () {
var y1 = $('#timelineBackground').height();
var y2 = $('.headerimage').height();
$(this).draggable({
scroll: false,
axis: "y",
drag: function (event, ui) {
if (ui.position.top >= 0) {
ui.position.top = 0;
} else if (ui.position.top <= y1 - y2) {
ui.position.top = y1 - y2;
}
},
stop: function (event, ui) {}
});
});
/* Bannert Position Save*/
$("body").on('click', '.bgSave', function () {
var id = $(this).attr("id");
var p = $("#timelineBGload").attr("style");
var Y = p.split("top:");
var Z = Y[1].split(";");
var dataString = 'position=' + Z[0];
$.ajax({
type: "POST",
url: "image_saveBG_ajax_bg.php",
data: dataString,
cache: false,
beforeSend: function () {},
success: function (html) {
if (html) {
$(".bgImage").fadeOut('slow');
$(".bgSave").fadeOut('slow');
$("#timelineShade").fadeIn("slow");
$("#timelineBGload").removeClass("headerimage");
$("#timelineBGload").css({
'margin-top': html
});
return false;
}
}
});
return false;
});
});
$("body").on('click', '.bgSave', function () {
var id = $(this).attr("id");
var p = $("#timelineBGload").attr("style");
var Y = p.split("top:");
var Z = Y[1].split(";");
var dataString = 'position=' + `Z`[0];
You are getting the position here just before the ajax post to the PHP script, it is crudely getting the 'top' CSS attribute from the inline style on #timelineBGload element.
If you inspect the DOM when dragging #timelineBGload UIDraggable updates the top (and left) as you move it around

Jquery Mockjax X-editable

I am trying to use X-editable select2 to allow users to insert tags under images. I have got it to create the tags, you can click and box pops up to edit. It will also append the new tag to the page. But, the problem is, it will not fire the mockjax/ajax call at all.
I have included the mockjax.js file in my header, jquery file is linked. I do not get any response in my browser console. I have tested mockjax on other parts of my site and they all fire correctly, just this one doesn't seem to work.
If I use something like this it works and sends the data to the console:
Working HTML code:
<p class="text-center itemName">click to edit this text</p>
Working jQuery code:
$('.itemName').editable({
type: 'text',
pk: 1,
url: 'update.php',
send: 'always'
});
Non-working jQuery:
$.fn.editable.defaults.mode = 'popover';
$('.tags').editable({
placement: 'right',
select2: {
tags: ['cake', 'cookies'],
tokenSeparators: [",", " "]
},
display: function(value) {
$.each(value,function(i){
// value[i] needs to have its HTML stripped, as every time it's read, it contains
// the HTML markup. If we don't strip it first, markup will recursively be added
// every time we open the edit widget and submit new values.
value[i] = "<span class='label'>" + $('<p>' + value[i] + '</p>').text() + "</span>";
});
$(this).html(value.join(" "));
}
});
$('.tags').on('shown', function() {
var editable = $(this).data('editable');
value = editable.value
$.each(value,function(i){
value[i] = $('<p>' + value[i] + '</p>').text()
});
});
$('[id^="tags-edit-"]').click(function(e) {
e.stopPropagation();
e.preventDefault();
$('#' + $(this).data('editable') ).editable('toggle');
});
$.mockjax({
type: 'text',
pk: 1,
url: 'update.php',
send: 'always'
});
update.php:
<?php
/*
Script for update record from X-editable.
*/
//delay (for debug only)
sleep(1);
/*
You will get 'pk', 'name' and 'value' in $_POST array.
*/
$pk = $_POST['pk'];
$name = $_POST['name'];
$value = $_POST['value'];
/*
Check submitted value
*/
if(!empty($value)) {
/*
If value is correct you process it (for example, save to db).
In case of success your script should not return anything, standard HTTP response '200 OK' is enough.
for example:
$result = mysql_query('update users set '.mysql_escape_string($name).'="'.mysql_escape_string($value).'" where user_id = "'.mysql_escape_string($pk).'"');
*/
//here, for debug reason we just return dump of $_POST, you will see result in browser console
print_r($_POST);
} else {
/*
In case of incorrect value or error you should return HTTP status != 200.
Response body will be shown as error message in editable form.
*/
//header('HTTP 400 Bad Request', true, 400);
echo "This field is required!";
}
?>
OP Found solution, here it is.
$.fn.editable.defaults.mode = 'popover';
$('.tags').editable({
placement: 'top',
select2: {
tags: ['cookies', 'pie','cake'],
tokenSeparators: [","]
},
display: function(value) {
$.each(value,function(i){
value[i] = "<span class='tagBox'>" + $('<p>' + value[i] + '</p>').text() + "</span>";
});
$(this).html(value.join(" "));
}
});
$('.tags').on('shown', function() {
var editable = $(this).data('editable');
value = editable.value
$.each(value,function(i){
value[i] = $('<p>' + value[i] + '</p>').text()
});
});
$("#content").on("click", '[id^="tags-edit-"]', function(e) {
e.stopPropagation();
e.preventDefault();
$('#' + $(this).data('editable') ).editable('toggle');
});
$('.tags').on('save', function(e, params) {
var itemId = $(this).attr('data-pk');
var dataString = 'value='+ params.newValue +'&id='+ itemId;
$.ajax({
type: 'POST',
data: dataString,
url: 'update.php',
send: 'always'
});
});

jquery and ajax to load php content

I have a <div class="container"> which will display content from separate php files located in a content folder, that are linked to individual <a> tags presented in a <ul>. Once a link from the list is clicked a loading graphic(processing...)class="process" will display in the container and the php file called upon will display.
HTML(watered down):
<div class="container"></div>
<ul id="yourIdeas">
<li>one</li> <!--content/one.php-->
<li>two</li>
<li>three</li>
<li>four</li>
</ul>
the container/loading graphic, styling etc... is all fine.
JQUERY:
(function() {
var typ = {
loading: $('<div />', { class: 'process' }),
area: $('.container')
}
var file = $('ul#yourIdeas li a').attr('href');
var thePage = $('content/' + file + '.php');
$('ul#yourIdeas li a').on('click', function() {
$.ajax({
url: 'thePage',
beforeSend: function() {
typ.area.append(typ.loading);
},
success: function(data) {
typ.area.html(data);
}
});
});
});
I cannot get the Jquery/Ajax to perform this task;
When a ul#yourIdeas li a is clicked, it grabs the href and associates it to the designated php file, which then loads the 'processing...' in the container, followed by displaying the content of the chosen php file in the container.
I can get it to work if i specifically ask for each link separately;
CODE:
var typ = {
loading: $('<div />', { class: 'process' }),
area: $('.container')
}
$('ul#yourIdeas li a#two').on('click', function() {
$.ajax({
url: 'content/two.php',
beforeSend: function() {
typ.area.append(typ.loading);
},
success: function(data) {
typ.area.html(data);
}
});
});
But i would like to have the one script to encompass all links and files, if possible.
Thanks in advance for any help.
You must move file and thePage variables inside your click function:
(function() {
var typ = {
loading: $('<div />', { class: 'process' }),
area: $('.container')
};
$('ul#yourIdeas li a').on('click', function(e) {
e.preventDefault();
var file = $(this).attr('href');
var thePage = 'content/' + file + '.php';
$.ajax({
url: thePage,
beforeSend: function() {
typ.area.append(typ.loading);
},
success: function(data) {
typ.area.html(data);
}
});
});
});

Only fetch output when element is not being dragged

How could I change the code below so that when an element is being being dragged the script will stop fetching the output file until that element was released?
$(document).ready(function() {
//$(".draggable").draggable();
$(".draggable").draggable({ containment: '#container', scroll: false });
$(".draggable").draggable({ stack: { group: '#container', min: 1 } });
$("*", document.body).click(function (e) {
var offset = $(this).offset();// get the offsets of the selected div
e.stopPropagation();
var theId = $(this).attr('id');// get the id of the selceted div
$("#result").text(this.tagName + " id=" + theId + " (" + offset.left + "," + offset.top +")");
//post x,y to php (and the id of the elemnt)
$.post("http://localhost/index.php", "id=" + theId + "&x=" + offset.left + "&y=" + offset.top);
});
var req = function () {
$.ajax({
url: "out.php",
cache: false,
success: function(html){
$("#stuff").empty().append(html);
var css_attr = html.split(",");
$('#1').css('left', css_attr[0] + 'px').css('top', css_attr[1] + 'px');
},
complete: function(){
req();
}
});
};
req();
});
Note: This script is dependent on the following JavaScript sources:
jquery.js
http://jqueryui.com/latest/ui/ui.core.js
http://jqueryui.com/latest/ui/ui.draggable.js
http://jqueryui.com/latest/ui/ui.droppable.js
Anything Helps...Thanks.
Draggables has options to allow you to associate functions with the start and stop of the drag. (see http://api.jquery.com/, click jQuery UI at the top for docs). So you can use that and perhaps have a global boolean that gets set when the drag starts and unset when the drag ends. Have your req() function check this boolean and exit if it's set. Something like:
var halt_request = 0;
$(".draggable").draggable({
containment: '#container',
scroll: false,
start: function(){ halt_request = 1; },
stop: function(){ halt_request = 0; }
});
...
var req = function () {
if (halt_request) {
sleep(10); // so you're not looping too quickly
req();
return;
}
$.ajax({
url: "out.php",
...
And better yet, instead of having req() call itself, have it use setTimeout. Have the timeout as a global and have the start/stop functions clear/set the timeout.
You can even take kbosak's idea a bit further:
var req = function () {
...
$(".draggable").draggable({
containment: '#container',
scroll: false,
stop: req
});
In other words, create a draggable that calls the function "req" when dragging stops.
Also, you can also totally rewrite this in a more standard form:
function req () {
...
and it will be the exact same thing. Also, you can do:
$(function() {
instead of:
$(document).ready(function() {
and you can merge your two draggable calls. So ... if I were writing it, the final code would be:
function req () {
...*insert code for req here*...
};
$(function() {
$(".draggable").draggable({
containment: '#container',
scroll: false,
stack: { group: '#container', min: 1 },
stop: req
});
$("*", document.body).click(function (e) {
var offset = $(this).offset();// get the offsets of the selected div
e.stopPropagation();
var theId = $(this).attr('id');// get the id of the selceted div
$("#result").text(this.tagName + " id=" + theId + " (" + offset.left + "," + offset.top +")");
//post x,y to php (and the id of the elemnt)
$.post("http://localhost/index.php", "id=" + theId + "&x=" + offset.left + "&y=" + offset.top);
});
req();
});
Maybe you can associate it with the mouseup event?
http://docs.jquery.com/Events/mouseup#fn
Instead of associating the draggable object directly with the AJAX call, associate it with a trigger which you can use to activate the mouseleave.

Categories