jquery .post elements created with append - php

I have a code with input field, and with clicking on add it adds new input field with new name:
/* multiply recepient */
var number = 1;
$('a.plus').live('click', function() {
number += 1;
$('.multiple').append('<p><input type="text" name="recepient_' + number + '"></p>');
});
this works fine. But then I want to post entered values with $.post() and only the first input fileld is posted, the original one, all created with append are note posted... Here is my post function:
$('input.submit').live('click', function() {
var postdata = $('form#form1').serialize();
$.post('result.php', postdata, function(data) {
$('div.result').html(data);
});
return false;
});
any ideas?

ok, found the error - has to be outside of .....

Related

Jquery click value check not working

I have a function that on click add/removes stuff from a SQL database.
I do a condition to check if it is refering to an add or remove and execute the code.
the add function works perfectly, but the remove not and its the same code, am i missing something obvious? And is this the best way to do this?
jquery:
//add card from list
$("#listcards a").click(function() {
if($(this).attr('add').length > 1) {
var value = $(this).attr('add');
$.post('searchc.php',{add:value}, function(data){
$("#add_result").html(data);
});
return false;
}
});
//remove card from list
$("#listcards a").click(function() {
if($(this).attr('rem').length > 1) {
var value = $(this).attr('rem');
$.post('searchc.php',{rem:value}, function(data){
$("#add_result").html(data);
});
return false;
}
});
html code:
<form id="listcards" method="post">
<input type='hidden' id='lcard' name='lcard' value=''>
<div>
bla bla -> imagem no + ? ou por algum efeito css+ | -<br>
coiso coiso + | -<br>
</div>
</form>
Do i also need to be in a form for the POST or a div would work too?
You've got two click handlers for the same elements, which could be causing a problem. You don't need to run both sets of code for each <a> element. Instead give the elements a class to show exactly what they do, and then limit your selectors to those elements
HTML:
+ | <a href="" class="remove" rem="bla bla">
Script:
$("#listcards a.add").click(function() {
var value = $(this).attr('add');
$.post('searchc.php',{add:value}, function(data){
$("#add_result").html(data);
});
return false;
});
//remove card from list
$("#listcards a.remove").click(function() {
var value = $(this).attr('rem');
$.post('searchc.php',{rem:value}, function(data){
$("#add_result").html(data);
});
return false;
});
You can use it like thisi will give only remove functionality. And oif possible add ajax.
$("#listcards .rem").click(function() {
var value = $(this).text();
if($(this).length()>1) {
$.post('searchc.php',{rem:value}, function(data){
$("#add_result").html(data);
});
return false;
}});
Suppose you don't have any card when you're loading this page 1st time. Then you click add new & a new card get's added to your html.
Now for this newly added card, the "remove" method doesn't get bind as that was loaded on page load (when this new card element was not present). Hence your remove method is not working for newly added cards.
So to make it work, you need to bing the remove method on new cards too. You can do that by keeping you remove part in a js function which you would call in "add" part after putting new card into html.
function removeCard(){
// first unbind the click event for all cards if any & then bind it
$("#listcards a").off('click');
//remove card from list
$("#listcards a").click(function() {
if($(this).attr('rem').length > 1) {
var value = $(this).attr('rem');
$.post('searchc.php',{rem:value}, function(data){
$("#add_result").html(data);
});
return false;
}
});
}
And you add part should be like this:
//add card from list
$("#listcards a").click(function() {
if($(this).attr('add').length > 1) {
var value = $(this).attr('add');
$.post('searchc.php',{add:value}, function(data){
$("#add_result").html(data);
removeCard(); // adding remove method here
});
return false;
}
});
Follow up your code,
$("#listcards a").click(function() {
var action = $(this).attr("add") ? "add" : "rem";
var value;
if(action == "add")
value = $(this).attr('add');
if(action == "rem")
value = $(this).attr('rem');
var param = {};
param[action] = value;
$.post('searchc.php',param, function(data){
$("#add_result").html(data);
});
});
Use onclick function to do this
It can help you out
+
-<br>
function addthis(addthis) {
if(addthis.length > 1) {
alert(addthis);
// $.post('searchc.php',{add:addthis}, function(data){
// $("#add_result").html(data);
// });
return false;
}
}
function removethis(remthis) {
if(remthis.length > 1) {
alert(remthis);
// $.post('searchc.php',{reb:remthis}, function(data){
// $("#add_result").html(data);
// });
return false;
}
}

Jquery - Changing URL used in load()

I'm using the following to auto refresh the contents of a div.
$(document).ready(function() {
$("#log").load("test.php?q=" + $('#sq').val());
var refreshId = setInterval(function() {
$("#log").load("test.php?q=" + $('#sq').val());
}, 1000);
$.ajaxSetup({ cache: false });
});
This seems to work fine. I have a text field with the name 'sq' and anything entered in there is searched for by test.php.
My page also has 2 other form fields.
A checkbox and another text field. The checkbox has the id 'chk' and the text field 'txt'.
What I would like to do is change the URL being used by load() if the checkbox is ticked and a value is entered in the text field. Obviously this will also need to include 'sq'.
Can some one point me in the right direction.
The URL with out the check box being ticked is : ( is it is now )
test.php?q=VALUE_FROM_sq
With the checkbox ticked it needs to be :
test.php?s=1&txt=VALUE_FROM_txt&q=VALUE_FROM_sq
Then test.php can use $_REQUEST to get the values passed.
My network box only supports php4 so that does limit me some..
Can some one point me in the right direction. Thanks
Just add some logic in the code:
$(document).ready(function() {
$.ajaxSetup({ cache: false });
var refreshId = setInterval(LoadLog, 1000);
LoadLog();
});
function LoadLog() {
var sq = $('#sq').val();
var text = $("#txt").val();
var url = "test.php?q=" + encodeURIComponent(sq);
if ($("#chk").is(":checked") && text.length > 0)
url += "&s=1&txt=" + encodeURIComponent(text);
$("#log").load(url);
}
You could save the URL in a separate variable and update it on the changed event of the checkbox.
var url = "test.php?q=VALUE_FROM_sq"
$(document.body).on('change', '#chk', function (event) {
if ($(this).is(':checked')) {
url = "test.php?s=1&txt=VALUE_FROM_txt&q=VALUE_FROM_sq"
} else {
url = "test.php?q=VALUE_FROM_sq"
}
}

Building a form dynamically

I have a drop down menu, that a user selects a criteria from, based on the criteria a form gets built.
What I am trying to do now is make sure they cannot build the same for twice, so for example, if the users selects appearance from a dropdown, I do not want them to be able to select appearance from the dropdown, while that form is built.
Does that make sense? Currently here is my code,
$('img.toggleadd').live({
click: function() {
var rowCount = $("#advanced_search > table > tbody > tr").length;
f(rowCount < 3) {
$.ajax({
url: site_url + 'ajax/row/empty',
success: function(data) {
console.log($(this));
$('#advanced_search table').append(data);
}
});
}
}
});
and the PHP
public function row($name) {
if ($this->input->is_ajax_request()) {
return $this->load->view('search/rows/'.$name);
}
}
$name relates to the name of a view which contains the corresponding form elements for the selected value.
As Jared mentioned, the solution could be something as simple as a boolean value indicating whether or not a request is in progress...
Take this code for example -
var request_in_progress = false;
$("#selector").on('change',function(){
if (!request_in_progress){
request_in_progress = true;
$.ajax('/path_to_ajax_module.php',{'data':data},function(response){
// handle the AJAX response
request_in_progress = false; // AJAX request complete.
},'json');
}
});

How do i change this into JSON?

How can I send multiple values to be picked up like this using JSON?
foreach($_POST['listItem'] as $key => $values){
list($eventDate, $eventTitle) = $values;
}
At the moment the values are sent as follows. But this doesn't appear to work properly as it is only sending some of the string. I also can't figure out where/how to send the caltitle value.
This is sending me crazy. Any help would be great.
var txt = $("#listbox");
var caltitle = copiedEventObject.title
var dtstart = $.fullCalendar.formatDate(copiedEventObject.start, 'yyyyMMdd');
var txt = $('#listbox');
txt.append("<li class ='listItem'> " + dtstart + "</li>")
// remove the element from the "Draggable Events" list
$(this).remove();
}
});
$('#calendarform').submit(function(e) {
var form = $(this);
var listItems = $('.listItem');
listItems.each(function(index){ //For each event do this:
var listItem = $(this);
$("<input type='hidden'/>").val(listItem.text()).appendTo(form).attr('name', 'listItem[' + index + ']');
});
//Get text information from elements
});
EDIT:
(using JSON)
$('#calendarform').submit(function(e) {
var form = $(this);
var going_to_be_json = [];
list.each(function(i, item) {
going_to_be_json.push({
'id':'test',
'title': 'test'
});
});
$('#stuff').val( JSON.stringify(going_to_be_json) );
});
Prepare the data into an array of objects then convert that array to JSON using JSON.stringify() and set the hidden form value to said string (or use XHR to submit it to the server).
Here is a very limited example of how to prepare the data:
var going_to_be_json = [];
list.each(function(i, item) {
going_to_be_json.push({
'id':item.id,
'title': item.title,
'date': (new Date()).now()
});
});
hidden_form_element.val( JSON.stringify(going_to_be_json) );
and on the server
<?php
$json_data_string = $_POST['hidden_form_field_containing_json_data']; // sanitize however
$array_data = json_decode($json_data_string);
More can be ready about JSON (Javascript Object Notation) from json.org and the Tag Wiki (although the tag wiki just shows you more examples and links)
it seems you needed a little more direction. I was hoping you wouldn't just copy and paste what I had and you would read and attempt to understand what it is doing....
$('#calendarform').submit(function(e) {
var form = $(this),
listItems = $('.listItem'),
data = [],
hidden = $('<input />'); // create a hidden field for the form.
// or just select the hidden form element from the page
hidden[0].type = 'hidden'; // set the type
hidden[0].name = 'some_name_for_php_to_recognize'; // and name
listItems.each(function(i,el){
data.push({'index': i, 'text': $(el).text()});
});
hidden.val(JSON.stringify(data));
$(this).append(hidden); // not needed if the hidden element is already in the DOM
});
send it with jQuery Post or Get method and fetch it by php you can send multiple values
use $.post or $.get

php mysql not saving data when button clicked and run $.ajax function

I have this
"fsField" is the class of all elements in the form. So whenever the user blurs to another field it submits the form using the function autosave() - given below. It saves data when the user blurs but when the user clicks the button with class "save_secL" to go to next page it does not save.
$('.fsField').bind('blur', function()
{
autosave();
}
});
but when i use this code
$('.save_secL').click(function()
{
var buttonid = this.id;
{
var answer = confirm("You have left some questions unanswered. Click OK if you are sure to leave this section? \\n Click CANCEL if you want stay in this section. ");
if(!answer)
{
var spl_items = valid().split(',');
$(spl_items[0]).focus();
return false;
}
else
{
$('#hidden_agree').append('<input id="secLuseragreed" name="secL_user_agreed" value="unanswered" type="hidden" />');
autosave();
window.location= buttonid+".php"
}
}
else
{
$('#hidden_agree').append('<input id="secLuseragreed" name="secL_user_agreed" value="answered all" type="hidden" />');
autosave();
window.location= buttonid+".php"
}
}
});
**autosave_secL.php is the php source thats saving the data in the database. I ran it independently and it does save data okay. **
function autosave()
{
var secL_partA_ques_1_select = $('[name="secL_partA_ques_1_select"]').val();
var secL_partA_ques_1 = $('[name="secL_partA_ques_1"]:checked').val();
var secL_partA_ques_2_select = $('[name="secL_partA_ques_2_select"]').val();
$.ajax(
{
type: "POST",
url: "autosave_secL.php",
data: "secL_partA_ques_1_select=" + secL_partA_ques_1_select + "&secL_partA_ques_1=" + secL_partA_ques_1 + "&user_id=<?php echo $row_token[user_id]?>" + "&updated_by=<?php echo $member."-".$key;?>",
cache: false,
success: function()
{
$("#timestamp").empty().append('Data Saved Successfully!');
}
});
}
**
valid() is a validation function that checks if any field is empty and returns a value if there is an empty field.**
function valid()
{
var items = '';
$('.fsField').each(function()
{
var thisname = $(this).attr('name')
if($(this).is('select'))
{
if($(this).val()=='')
{
var thisid = $(this).attr('id')
items += "#\"+thisid+\",";
$('[name=\"'+thisname+'\"]').closest('td').css('background-color', '#B5EAAA');
}
}
else
{
$('[name=\"'+thisname+'\"]').closest('td').css('background-color', '');
}
});
return items;
}
Can anyone please help? i am stuck for a day now. Can't understand why it saves when the user goes field to field but does not save when button is clicked with validation.
Tested with Firefox. this line appears in red with a Cross sign beside when the button(save_secL class) is clicked. I am using a ssl connection.
POST https://example.com/files/autosave_secL.php x
Here is the modified code trying to implement the solution
$('#submit_survey_secL').click(function()
{
if(valid() !='')
{
var answer = confirm("You have left some questions unanswered. Are you sure you want to Submit and go to Section B? ");
if(!answer)
{
var spl_items = valid().split(',');
$(spl_items[0]).focus();
return false;
}
else
{
$('#hidden_agree').append('<input id=\"secLuseragreed\" name=\"secL_user_agreed\" value=\"unanswered\" type=\"hidden\" />');
autosave(function(){
window.location= "part1secM.php?token=1&id=4"
});
}
}
else
{
$('#hidden_agree').append('<input id=\"secLuseragreed\" name=\"secL_user_agreed\" value=\"unanswered\" type=\"hidden\" />');
autosave(function(){
window.location= "part1secM.php?token=1&id=6"
});
}
});
function autosave(callback)
{
var secL_partL_ques_1_select = $('[name="secL_partL_ques_1_select"]').val();
var secL_partL_ques_1 = $('[name="secL_partL_ques_1"]:checked').val();
var secL_partL_ques_2_select = $('[name="secL_partL_ques_2_select"]').val();
$.ajax(
{
type: "POST",
url: "autosave_secL.php",
data: "secL_partL_ques_1_select=" + secL_partL_ques_1_select + "&secL_partL_ques_1=" + secL_partL_ques_1 + "&user_id=<?php echo $row_token[user_id]?>" + "&updated_by=<?php echo $member."-".$key;?>",
cache: false,
success: function()
{
$("#timestamp").empty().append('Data Saved Successfully!');
if($.isFunction(callback))
{
callback();
}
}
});
}
I don't understand why this doesn't work as callback should totally work. Firebug does not show POST https://example.com/files/autosave_secL.php in red any more but it shows that it has posted but I think the callback is not triggering for some reason
$('.save_secL').click(function() {
//...
//start autosave. Note: Async, returns immediately
autosave();
//and now, before the POST request has been completed, we change location...
window.location= buttonid+".php?token=$row_token[survey_token]&$member=$key&agr=1"
//....and the POST request gets aborted :(
Solution:
function autosave(callback)
{
//...
$.ajax(
{
//...
success: function()
{
$("#timestamp").empty().append('Data Saved Successfully!');
if($.isFunction(callback))
callback();
}
});
}
//and
autosave(function(){
window.location= buttonid+".php?token=$row_token[survey_token]&$member=$key&agr=1"
});
By the way, your autosave function is pretty hard for your server. Did you consider using localStorage + a final POST request containing all data?
I got the solution.
It might be one of the several. scr4ve's solution definitely helped. So here are the points for which I think its working now.
Moved "cache: false, " and removed "async:false" before url: in the ajax autosave function. Before I was putting it after "data: "
Added a random variable after autosave_secL.php/?"+Match.random()
Added scr4ve's solution so that POST is completed before redirect

Categories