Wordpress jQuery to PHP data transfer - php

everyone. I'm a relatively new developer with limited experience in jQuery AJAX and PHP. I'm working on a Wordpress plugin that is very much a learning exercise for me as well.
Basic description: On my plugin's admin page, I have a bunch of forms that will be displayed as modal windows (using jQuery UI) and when filled out, will submit their fields to a separate PHP file for processing. That file will accept the data and prepare it for insertion into the wpdb table I have set up.
Plugin Admin page (PHP):
<div id="form1" title="My Awesome Form">
<form id="frmNewCom">
<fieldset>
<table>
<tr>
<td><label for="name">Community Name</label>
<td><input type="text" name="newComName" id="newComName" />
</tr>
<tr>
<td><label for="lefthead">Left Column Header</label></td>
<td><input type="text" name="newComLefthead" id="newComLefthead" /></td>
</tr>
<tr>
<td><label for="righthead">Right Column Header</label></td>
<td><input type="text" name="newComRighthead" id="newComRighthead" /></td>
</tr>
</table>
</fieldset>
</form>
</div>
jQuery UI code for form ($pcal is my no-conflict thing):
$pcal('#form1').dialog({
autoOpen: false,
height: 275,
width: 400,
modal: true,
buttons: {
"Add Living Option": function() {
// Functionality for submit
},
Cancel: function() {
$pcal(this).dialog("close");
}
},
close: function() {
// close function
}
});
Now here's the problem. I'm not really sure what to do from this point. I've read a bunch of stuff about using .post() and .serialize(), and I've gotten myself very confused at this point.
Do you guys have some insight into the proper javascript/jQuery to PHP handling you could lend? I've asked this on the Wordpress forum as well, but I've always found good advice here, so thought I'd ask. Any and all help is appreciated.

A very simple example would be :
$pcal.post("test.php", $pcal("#frmNewCom").serialize(), function() {
// this will run once returned from PHP
alert('thanks');
$pcal(this).dialog("close");
});
This posts the form (id = frmNewCom) in a serialized format (newComName=1&newComLefthead=2&newComName=3 where 1,2 and 3 are the values entered in your form) using .post() and .serialize()
then in test.php you would access your values like this :
$newComName = $_POST['newComName'];
$newComLefthead = $_POST['newComLefthead'];
$newComName = $_POST['newComName'];
// insert into table
The above is a) untested and b) does not contain any prevention against SQL injection should you want to store this in a DB

Related

Tagging system with dynamic input

Right now I'm trying to combine the bootstraps tagging-system with a dynamic input field code. I want for every dynamic generated field/div a tag-inputfield.
like this way:
Topic1: Title
Description: it's about a title
Tags: hello, boring, title
Topic2: it's a title again
Description: it's a description again
Tags: idk, help
(...) and so on.
My jquery file for adding additional fields looks like this:
$(document).ready(function () {
var maxGroup = 10;
$(".addMore2").click(function() {
$(".tagging").css("display", "none");
if ($('feld2').find('.fieldGroup').length < maxGroup) {
var fieldHTML = '<div class="form-group fieldGroup">' +
$(".fieldGroupCopy").html() + '</div>';
$('feld2').find('.fieldGroup:last').after(fieldHTML);
} else {
alert('Maximum ' + maxGroup + ' groups are allowed.');
}
});
//remove fields group
$("feld2").on("click", ".remove", function () {
$(this).parents(".fieldGroup").remove();
});
});
The not working part is this one:
When I click on my "add" button:
see here
it makes a copy of the this part:
<div class="form-group fieldGroupCopy" style="display: none;">
<table>
<tr>
<td class='first_td'><label for="titel"><b>Titel:</b></label></td>
<td><input type="text" name="description[]" class="form-control" placeholder="Title"/></td>
<td>-</td>
</tr>
<tr>
<td><b>Beschreibung:</b></td>
<td><textarea type="text" name="description[]" class="form-control" placeholder="Beschreibung des Themas"/></textarea></td>
</tr>
<tr>
<td><label for="Tags"><b>Tags</b></label></td>
<td colspan='2'>
div class="form-group">
<input type="text" name='tags_WiBe[]' placeholder='Add Tags' data-role="tagsinput" class="form-control" />
</div>
</td>
</tr>
</table>
</div>
But the tagging-system does not work within the copied fields.
Its only working outside of the div "form-group fieldGroup".
see here
Everytime I enter a tag the form wants to submit, but thats not what I want.
Please help me...
edit:
Here is a jsfiddle to show the problem more clearly.
https://jsfiddle.net/t5vrLsur/#&togetherjs=pbAhjTR1t1
I know it's not the most beautiful structure.
Don't be too hard on me. :(
The thing is that the plugin itself take care about the first initialisation on DOM ready. In your case, you want to run it after each adding card.
You can do this by simple run the plugin initialisation in the new card context.
Also, you have to remove the data-role attribute from the input in the template because, as we said, this attribute meant to initialise the plugin automatically but in the template's case we will do it manually after we will load the card.
So here are the relevant lines:
// wrap the html with jQuery so you could delete the inputtags wrapper later
var fieldHTML = $('<div class="form-group fieldGroup">' + $(".fieldGroupCopy").html() + '</div>');
$('feld2').find('.fieldGroup:last').after(fieldHTML);
// initialise again
fieldHTML.find('input').tagsinput();
Working demo
http://output.jsbin.com/dabijac/
Also, you have couple of jQuery references in your code which cause problem. You have either remove it or using use $.noConflict to keep them.

html element id not getting after load it from ajax page

I am trying to load value of state field after change suburb dropdown. The suburb dropdown is coming from an ajax page after blur postcode text field. my jquery code is
$("#zip").blur(function(){
$.post("get_suburb_admin.php",{zip:$(this).val()}, function(d){
$("#suburb_cnt").html(d.suburb);
},'JSON');
});
$("#suburb").change(function(){
$.post("get_state.php",{suburb:$(this).val()}, function(a){
$("#state").val(a);
});
});
Html structure is
<tr>
<td>Suburb :</td>
<td id="suburb_cnt"><input type="text" name="suburb" id="suburb" value="<?php echo $row['suburb'];?>" /></td>
</tr>
<tr>
<td>Postcode :</td>
<td><input type="text" name="zip" id="zip" value="<?php echo $row['zip'];?>" /></td>
</tr>
<tr>
<td>State :</td>
<td id="state_cnt"><input type="text" name="state" id="state" value="<?php echo $row['state'];?>" /></td>
</tr>
But it is not responding after on change the suburb dropdown which is coming from ajax page. I am giving what is coming from ajax page here
$sql=mysql_query("SELECT town,region FROM au_postcode WHERE postcode='".$_REQUEST['zip']."'");
$arr=array();
$arr['suburb']='<select name="suburb" id="suburb">';
while($row=mysql_fetch_array($sql)){
$arr['suburb'].='<option value="'.$row['town'].'">'.$row['town'].', '.$row['region'].'</option>';
}
$arr['suburb'].='</select>';
echo json_encode($arr);
also suburb data is not getting after the form submit with method post.
$_REQUEST['suburb'] = nothing, after form submit
how can I solve it, pls help
try this
$("#suburb").change(function(){
var suburbVal = $(this).val();
$.post("get_state.php",{suburb:suburbVal}, function(a){
$("#state").val(a);
});
});
and same for #zip blur event
DOM prepares element on every page load/refresh but when you add thing dynamically to your page (without refreshing it) it does not re initiates DOM to go and detect that. So you have to notify javascript that find your element NOW. For which you can use/bind LIVE Method (for jQuery 1.7) or ON Method (for later versions of jQuery).
Here`s a simple example for CLICK event in jQuery.
$("#myButton").click(function(){
/*TO DO*/
});
and its another version (you can use LIVE/ON as per your jQuery`s Version)
$("#myButton").live("click", function(e){
/*TO DO*/
});
All the Best :)
I did not bind html element of suburb. You can do this by changing:
$("#suburb").change(function(){
$.post("get_state.php",{suburb:$(this).val()}, function(a){
$("#state").val(a);
});
});
to:
$("body").on("change","#suburb",(function(){
$.post("get_state.php",{suburb:$(this).val()}, function(a){
$("#state").val(a);
});
});

update list with jquery & ajax [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
i make a list with php & jquery which shows every row in my database.
i want to add this list an update button. when user clicks on a row, the row will expand and the button will become visible. and the text on that row will go in a textbox.
and my question is, how can i update the text when user click on the button in that row? first i thought, i could put a form in every row.. but i think that's a terrible solution.
can you suggest me an example or source for what i want to do?
Questions asking for code must show the code you've tried. Since you didn't give any code, I'll give a high-level answer:
Attach an event handler to the button (or probably actually to the table and use delegation).
In the the event handler, use jQuery traversal functions to find the row to which the button belongs.
Once you have a reference to the row, use jQuery traversal functions to find the inputs in the row.
Get the values and use ajax to update the database.
This is essentially what you need to do
jsFiddle (all working except AJAX)
Review the above jsFiddle and you can see how the first part of your question will work.
The values will be updated in the database via AJAX, and the code block is present in the jsFiddle example, but jsFiddle cannot demonstrate AJAX so you can't see it in action there.
However, if you copy/paste the following into two files (three if you break out the javascript into its own file), and edit it to match your own database, then you can see it in action.
Two files are required:
One: index.php (or whatever you wish to call it)
Two: my_php_processor_file.php (if change this name, must also change in the AJAX code block in the javascript
HTML:
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.9.1/jquery-ui.min.js"></script>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.9.1/themes/base/jquery-ui.css" />
<style>
</style>
<script type="text/javascript">
//Global var goes here:
editRow = 0;
$(document).ready(function() {
$('#msgbox').dialog({
autoOpen:false,
width:400,
modal:true,
buttons: {
Submit: function() {
var mfn = $('#mfn').val();
var mln = $('#mln').val();
var mem = $('#mem').val();
$('table').find('tr').eq(editRow).find('.fname').val(mfn);
$('table').find('tr').eq(editRow).find('.lname').val(mln);
$('table').find('tr').eq(editRow).find('.email').val(mem);
/*
//Now do the ajax transfer to the server
$.ajax({
type: 'POST',
url: 'my_php_processor_file.php',
data: 'user_id=' +editRow+ '&first_name=' +mfn+ '&last_name=' +mln+ '&email_addy=' +mem,
success:function(recd){
$('#alert').html(recd);
$('#alert').dialog('open');
}
}); //END ajax code block
*/ //Now, close the dialog -- doesn't happen automatically!
$(this).dialog('close');
}, //END Submit button
Cancel: function() {
$(this).dialog('close');
} //END Cancel button
} //END all buttons
}); //END msgbox div (dialog)
$('.editbutt').click(function() {
editRow = $(this).parents('tr').index();
//alert(editRow);
var fn = $(this).parents('tr').find('td').eq(0).find('.fname').val();
var ln = $(this).parents('tr').find('td').eq(1).find('.lname').val();
var em = $(this).parents('tr').find('td').eq(2).find('.email').val();
$('#mfn').val(fn);
$('#mln').val(ln);
$('#mem').val(em);
$('#msgbox').dialog('open');
}); //END editbutt
$('#alert').dialog({
autoOpen:false,
modal:true
});
}); //END document.ready
</script>
</head>
<body>
<table id="tbl">
<tr>
<td>
First Name
</td>
<td>
Last Name
</td>
<td>
Email
</td>
</tr>
<tr>
<td>
<input type="text" class="fname" id="fn1">
</td>
<td>
<input type="text" class="lname" id="ln1">
</td>
<td>
<input type="text" class="email" id="em1">
</td>
<td>
<input class="editbutt" type="button" value="Edit Row">
</td>
</tr>
<tr id="tr2">
<td id="td2a">
<input type="text" class="fname" id="fn2">
</td>
<td id="td2b">
<input type="text" class="lname" id="ln2">
</td>
<td id="td2c">
<input type="text" class="email" id="em2">
</td>
<td id="td2d">
<input class="editbutt" type="button" value="Edit Row">
</td>
</tr>
</table>
<div id="msgbox">
<h2>Edit User</h2>
First Name: <input id="mfn" type="text"><br/>
Last Name : <input id="mln" type="text"><br/>
Email Addy: <input id="mem" type="text"><br/>
</div>
<div id="alert"></div>
</body>
</html>
PHP Processor File: my_php_processor_file.php
<?php
$fn = $_POST['first_name'];
$ln = $_POST['last_name'];
$em = $_POST['email_addy'];
$uid = $_POST['user_id'];
/*
//This is where you use the security features of PHP to strip_slashes, and
//protect html_entities, etc. to guard your database against SQL injection
//attacks, etc. SEE THESE POSTS:
http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php
http://www.tizag.com/mysqlTutorial/mysql-php-sql-injection.php
http://blogs.msdn.com/b/brian_swan/archive/2010/03/04/what_2700_s-the-right-way-to-avoid-sql-injection-in-php-scripts_3f00_.aspx
*/
//Now, update the database:
$success = mysql_query("UPDATE `users` SET `email`='$em', `first`='$fn', `last`='$ln' WHERE `user_id` = '$uid'");
//Now, return a message or something
if (mysql_affected_rows() == -1) {
$output = '<h2>Sorry, database update failed</h2>';
}else{
$output = '<h2>Update successful</h2>';
}
echo $output;

How to resolve strange conflict between form post and ajax post?

On the one page, I am trying to use ajax to edit existing values. I am doing this by using jQuery Inline Edit and posting away the new data, updating the record and returning with success.
This is working fine.
Next I have implemented the ability to add new records, to do this I have a form at the end of the table, which submits post data then redirects back to the original page.
Each of them work individually, but after I have used the form to add a new record, the inline editing stops to work. If I close the webpage and reopen it, it works fine again until I have used the form and it goes of the rails again.
I have tried a number of solutions, clearing session data, giving the form a separate name, redirecting to an alternative page (which does work, but is not ideal as I want the form to redirect back to the original location ).
Here is a sample of the view form data:
<?php foreach($week->incomes as $income):?>
<tr>
<td><?php echo $income->name;?></td>
<td width="70" style="text-align:right;" class="editableSingle income id<?php echo $income->id;?>">$<?php echo $income->cost;?></td>
</tr>
<?php endforeach;?>
<?php echo form_open('budget/add/'.$week->id.'/income/index', 'class="form-vertical" id="add_income"'); ?>
<tr>
<td>
<input type="text" name="name" class="input-small" placeholder="Name">
<input type="text" name="cost" class="input-small" placeholder="Cost">
</td>
<td>
<button type="submit" class="btn btn-small pull-right"><i class="icon-plus "></i></button>
</td>
</tr>
<?php echo form_close(); ?>
This is the javascript initialisation code:
$(function(){
$.inlineEdit({
income: 'budget/update_income/',
expense: 'budget/update_expense/'
},
{
animate: false,
filterElementValue: function($o){
if ($o.hasClass('income')) {
return $o.html().match(/\$(.+)/)[1];
}
else if ($o.hasClass('expense')) {
return $o.html().match(/\$(.+)/)[1];
}
else {
return $o.html();
}
},
afterSave: function(o){
if (o.type == 'income') {
$('.income.id' + o.id).prepend('$');
}
if (o.type == 'expense') {
$('.expense.id' + o.id).prepend('$');
}
},
colors: { error:'green' }
});
});
If I can provide any more information to clarify what I have attempted etc, let me know.
Temporary Fix
It seems I have come up with a work around, not ideal as I still am not sure what is causing the issue.
I have created a method called redirect.
public function redirect(){
redirect('');
}
am now calling that after the form submit which has temporarily allows my multiple post submits to work.
please try and see by replacing the jquery sign.
$ should be replaced by jQuery then it will create new instance to work fine
I heard somewhere that jquery wont work if you put the form inside the table tag.
It need to be outside the table as in:
<form>
<table>
...
</table>
</form>
jQuery does not bring the contents of a form element if inside a table element on an ajax load
After testing it, i've discover that it is partialy true, (aka un-reliable)... It's the reason why i stopped using tables.

Adding array of textbox using javascript into html

Is something wrong with my code?
<script>
function add(){
/* Get your form */
form = document.getElementById("test");
/* Create your input element */
input = document.createElement("input");
input.type="text";
input.name="array['artists']";
/* Append to form */
form.appendChild(input);
alert("done");
}
</script>
<table>
<tr>
<td align="right">Artist/s:</td>
<td><form id="test" enctype="multipart/data-form" method="post">
<input type="text" name="artists"/>
<input type="button" onclick='javascript: add()'/></form></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="Submit"></td>
</tr>
</table>
Im trying to add another textbox below another but nothing happened. What should i do?
Seems to be working for me too.
When I first put it into an html file, Internet Explorer wouldn't let me run the javascript because the html file was local to my computer. Try another browser if that's what you're using. Or just click yest to allow it in IE if that's the case.
Seems to be working - fiddle
I just put a call to add() inside a setTimeout so it would execute a second after the page loads.
Are you just missing the call to add()?
edit: I didnt originally see the onclick bound. new working fiddle2
Works for me as well. Try testing in another browser..
Your HTML-formatting is not right. This is why the input-box (TextBox) is added after the 'add'-button and not underneath it as you would like.
You can try the following code:
var table = document.getElementById("tableAddRows");
var row = document.createElement("tr");
var td1 = document.createElement("td");
var td2 = document.createElement("td");
td2.appendChild(input);
row.appendChild(td1);
row.appendChild(td2);
table.appendChild(row);
Add an id to the table (in the sample "tableAddRows").
Also, I added the Submit-button in a different table, like so (there are neater solutions):
<table>
<tr>
<td colspan="2"><input type="submit" value="Submit"></td>
</tr>
</table>
Also place the form-element around both tables.
I would also suggest to use JSRender or jQuery Templates to achieve your purpose.
Here's the sample code, if your still trying to figure it out.

Categories