update json data into db - php

Alright... this seems complicated for me..
I don't know if it is.
filename: add_types.js
I have some data, which i create into mysql db (is for a back-end system).
through jquery/ json. It work fine.
var last_id = data.last_id;
var fck_editor = data.fck_editor;
var new_data = '<div id="input_highlight'+last_id+'"><strong style="font-size:14px;">Overskrift:</strong> <br />';
new_data += '<input type="text" name="overskrift[]" /><br />';
new_data += '<input type="hidden" name="tekst_id[]" value="'+data.last_id+'" />';
new_data += fck_editor;
new_data += '<img src="/gfx/admin/icons/delete.png" alt="" />Slet';
new_data += '</div><div id="loader'+last_id+'"></div><br />';
$(div_id).append(new_data);
Now I just need to update it (in the same file where it gets outputed)
rejser.php
my data goes out here in a div
<div id="add_here" class="add_here_bg"></div>
I want the ouput from add_types.js to be updated in db when i submit another form in the rejser.php file.
pls inform me, if my question is understandable.

You could use a regular jQuery AJAX-request, which submits the contents of your div to a server-side script:
var content = $('#add_here').html();
$.get(url_of_script, content);
And then have the script add it to the DB. Are you familiar with using PHP/MySQL to do this?
If you want to update this stuff when a form is submitted, try attaching an event listener to the onSubmit event of the form.
Edit:
So, first add the onSubmit attribute to your form:
<form onSubmit="return formSubmit(event);">
Now, you'll have to define this function somewhere - really doesn't matter where you do it, though the <head> section of your page is recommended. External file is, of course, also possible.
function formSubmit(event) {
var content = $('#add_here').html();
// this callback will make sure the form is submitted after having completed the other request
var callback = function() { event.target.submit() };
$.get(url_of_script, content, callback);
// Now, cancel the default event, the callback will take care of the submit afterwards
event.stopPropagation();
}
Haven't tested it, but something like this is supposed to work. Let me know if you need some more help.

Related

AJAX\JQUERY: Update MYSQL database with form data without refreshing

Ok, so I've gotten most of this thing done.. Now comes, for me, the hard part. This is untreaded territory for me.
How do I update my mysql database, with form data, without having the page refresh? I presume you use AJAX and\or Jquery to do this- but I don't quite grasp the examples being given.
Can anybody please tell me how to perform this task within this context?
So this is my form:
<form name="checklist" id="checklist" class="checklist">
<?php // Loop through query results
while($row = mysql_fetch_array($result))
{
$entry = $row['Entry'];
$CID = $row['CID'];
$checked =$row['Checked'];
// echo $CID;
echo "<input type=\"text\" value=\"$entry\" name=\"textfield$CID;\" id=\"textfield$CID;\" onchange=\"showUser(this.value)\" />";
echo "<input type=\"checkbox\" value=\"\" name=\"checkbox$CID;\" id=\"checkbox$CID;\" value=\"$checked\"".(($checked == '1')? ' checked="checked"' : '')." />";
echo "<br>";
}
?>
<div id="dynamicInput"></div>
<input type="submit" id="checklistSubmit" name="checklistSubmit" class="checklist-submit"> <input type="button" id="CompleteAll" name="CompleteAll" value="Check All" onclick="javascript:checkAll('checklist', true);"><input type="button" id="UncheckAll" name="UncheckAll" value="Uncheck All" onclick="javascript:checkAll('checklist', false);">
<input type="button" value="Add another text input" onClick="addInput('dynamicInput');"></form>
It is populated from the database based on the users session_id, however if the user wants to create a new list item (or is a new visitor period) he can click the button "Add another text input" and a new form element will generate.
All updates to the database need to be done through AJAX\JQUERY and not through a post which will refresh the page.
I really need help on this one. Getting my head around this kind of... Updating method kind of hurts!
Thanks.
You will need to catch the click of the button. And make sure you stop propagation.
$('checklistSubmit').click(function(e) {
$(e).stopPropagation();
$.post({
url: 'checklist.php'
data: $('#checklist').serialize(),
dataType: 'html'
success: function(data, status, jqXHR) {
$('div.successmessage').html(data);
//your success callback function
}
error: function() {
//your error callback function
}
});
});
That's just something I worked up off the top of my head. Should give you the basic idea. I'd be happy to elaborate more if need be.
Check out jQuery's documentation of $.post for all the nitty gritty details.
http://api.jquery.com/jQuery.post/
Edit:
I changed it to use jquery's serialize method. Forgot about it originally.
More Elaboration:
Basically when the submit button is clicked it will call the function specified. You want to do a stop propagation so that the form will not submit by bubbling up the DOM and doing a normal submit.
The $.post is a shorthand version of $.ajax({ type: 'post'});
So all you do is specify the url you want to post to, pass the form data and in php it will come in just like any other request. So then you process the POST data, save your changes in the database or whatever else and send back JSON data as I have it specified. You could also send back HTML or XML. jQuery's documentation shows the possible datatypes.
In your success function will get back data as the first parameter. So whatever you specified as the data type coming back you simply use it how you need to. So let's say you wanted to return some html as a success message. All you would need to do is take the data in the success function and place it where you wanted to in the DOM with .append() or something like that.
Clear as mud?
You need two scripts here: one that runs the AJAX (better to use a framework, jQuery is one of the easiest for me) and a PHP script that gets the Post data and does the database update.
I'm not going to give you a full source (because this is not the place for that), but a guide. In jQuery you can do something like this:
<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function() { // DOM is ready
$("form#checklist").submit(function(evt) {
evt.preventDefault(); // Avoid the "submit" to work, we'll do this manually
var data = new Array();
var dynamicInputs = $("input,select", $(this)); // All inputs and selects in the scope of "$(this)" (the form)
dynamicInputs.each(function() {
// Here "$(this)" is every input and select
var object_name = $(this).attr('name');
var object_value = $(this).attr('value');
data[object_name] = object_value; // Add to an associative array
});
// Now data is fully populated, now we can send it to the PHP
// Documentation: http://api.jquery.com/jQuery.post/
$.post("http://localhost/script.php", data, function(response) {
alert('The PHP returned: ' + response);
});
});
});
</script>
Then take the values from $_POST in PHP (or any other webserver scripting engine) and do your thing to update the DB. Change the URL and the data array to your needs.
Remember that data can be like this: { input1 : value1, input2 : value2 } and the PHP will get something like $_POST['input1'] = value1 and $_POST['input2'] = value2.
This is how i post form data using jquery
$.ajax({
url: 'http://example.com',
type: 'GET',
data: $('#checklist').serialize(),
cache: false,
}).done(function (response) {
/* It worked */
}).fail(function () {
/* It didnt worked */
});
Hope this helps, let me know how you get on!

How do I pass a dynamically created list to the controller to save into the database?

I am working in Concrete5 and am new to the MVC concept. I have a some jquery that creates an unordered list from a textbox in my view. If your familiar with Concrete5 this is the view for the block I am adding the list to. It is basically a list of features for a product. This view needs to save the list to the database base file. Usually this is done pretty simply using a variable that the information gets saved to (aka this is how everything else in the view is saved). The problem I am having is I do not know how to use the controller to pass the unordered list from the view to the controller to the database so that it saves it. Any help and sample code would be appreciated. I'm pretty sure I need to write a php function in my controller to get the list but I am not sure what the code would be.
auto.js
$("#addList").click(function() {
var text = $("#inputList").val() + '<button>x</button>';
if(text.length){
$('<li />', {html: text}).appendTo('ul.featureList')
};
});
$('ul').on('click','button', function(el){
$(this).parent().remove()
});
add/edit.php
<div class="ccm-block-field-group">
<h2><?php echo t('Features') ?></h2>
Right now 'features' is the name of the field in my database file db.xml
The area featureList is where the list get generated into. I know it needs to be changed around a bit to work, just not sure.
<?php echo $form->textarea('features', $features, array());?>
<input type="test" id="inputList" />
<button type="button" id="addList">Add</button>
<ul class="featureList"></ul>
</div>
view.php
echo "<h2>{$proName}</h2>";
echo "{$description}";
echo "<h3>{$features}</h3>";
echo "<h2>{$price}</h2>";
echo "<p>{$priceInfo}</p>";
db.xml
<field name="features" type="X2"></field>
With concrete5 blocks, there are two different situations you could be in:
admin user is editing the block (or adding a new block), and you want to save this data to the database.
public user is viewing the block, but the block view itself has a form (for example, a contact form block) and you want to do something when the public form is submitted (for example, send a notification email to an admin that someone has filled out the form, or store the submission in a database for future review).
If you're talking about situation #1, you need to put some custom code in the controller's save() method. If you're talking about situation #2, you need to create your own action method in the controller, AND you need to actually have a <form> in the view.php file.
UPDATE: Based on the sample code you added to your question, here is the solution:
The only way your data can get back to the server is via a form POST. <li> elements are not form fields, and hence the data in them doesn't get POST'ed with the form. So when you add the new <li> element to the page, you should also add a hidden form field, like so:
var listItemCounter = 0;
$("#addList").click(function() {
listItemCounter++;
var text = $("#inputList").val() + '<button data-id="' + listItemCounter + '">x</button>'; //assign a unique id number to this button, so it knows which hidden field to remove when clicked
if(text.length){
$('<li />', {html: text}).appendTo('ul.featureList');
$('<input type="hidden" name="features[]" value="' + text + '" data-id="' + listItemCounter + '" />').insertAfter('ul.featureList');
};
});
$('ul').on('click','button', function(el){
$('input[data-id="' + $(this).attr('data-id') + '"]').remove(); //remove the hidden field so it does not get POSTed when user saves
$(this).parent().remove();
});
Now, in your block's controller.php file, you will want to add a save() method that will take all of the data from those hidden fields, combine them and put them into the "features" field that you declared in your db.xml file:
public function save($args) {
$args['features'] = implode("\n", $args['features']); //combine all feature items into one string, separated by "newline" characters
parent::save($args);
}
Finally, in your view.php file, you can convert the list of features (which was saved to the database as one string, with each item separated by a "newline" character) like so:
<?php echo nl2br($features); ?>
Or if you want to output it as separate list items, you could do something like this:
<ul>
<?php
$features = explode("\n", $features);
foreach ($features as $feature) {
echo '<li>' . $feature . '</li>';
}
?>
</ul>
You dont pass stuff from the view to the controller. The controller is executed BEFORE the view, so you only pass from controller to view.
Try accessing the stuff you pass from jquery to your application using
$this->getRequest()->getParam('yourParametersName');
inside the controller.
Lucian
I changed around the auto.js file so it is as follows. Seems to work fine.
var listItemCounter = 0;
$("#addList").click(function() {
listItemCounter++;
var text = $("#inputList").val(); //assign a unique id number to this button, so it knows which hidden field to remove when clicked
var buttonDataId = text + '<button data-id="' + listItemCounter + '">x</button>';
if(text.length){
$('<li />', {html: buttonDataId}).appendTo('ul.featureList');
$('<input type="hidden" name="features[]" value="' + text + '" data-id="' + listItemCounter + '" />').insertAfter('ul.featureList');
};
});
$('ul').on('click','button', function(el){
$('input[data-id="' + $(this).attr('data-id') + '"]').remove();//remove the hidden field so it does not get POSTed when user saves
$(this).parent().remove()
});
I left the view the same as what Jordan Lev put. (Thanks!)
Then I changed the controller.php to
public function save($args) {
$args['features'] = implode("\n", $args['features']);//combine all feature items into one string, separated by "newline" characters
parent::save($args);
}
If anyone sees any problems or a better way to put my code please let me know!
My new problem now is once it is saved, if I go to edit the list, it wipes out my past entries and saves the new one. If anyone knows the function I would have to write to show the current list and add to it when editing that would be great. Please give some example code.

this is regarding Jquery/JS, if i change element's HTML - will i be able to perform other Jquery/JS action on it

I have a a script that on click do a ajax call connect to the database get imagename and set the image name inside an < -img - > with the right path also it adds a hidden checkbox after it and then echo it.
i then take the ajax message returned and put it as div's HTML. my question is will i be able to preform more action on the inserted content..
The main goal is to be able to click on the image as if it were a checkbox(this part is already sorted for me) however no matter what i try i cant have a .click function works..
Here is the code.
This is the PHP part that echos the images.
if($_POST['updateIgallery'] == 'ajax'){
global $wpdb;
$table_name= $wpdb->prefix . "table_T";
$imagecounter = 1;
$toecho = '';
$currentselected = $wpdb->get_row("query");
preg_match_all('/\/(.+?\..+?)\//',$currentselected ['image_gal'],$preresualts); // images are stored with /image/.
foreach ($preresualts[1] as $imagename){
$toecho .= '
<img rel="no" id="JustantestID" class="JustaTestClass" src="'.site_url().'/wp-content/plugins/wp-ecommerce-extender/images/uploads/'.$imagename.'">
<input name="DoorIMGtoDeleteIDcheck'.$imagecounter.'" style="display:none;" name="DoorIMGtoDelete['.$imagecounter.']" value="/'.$imagename.'/" type="checkbox">
';
$imagecounter++;
}
echo $toecho;
}
This is the ajax part that send and receive and insert the HTML to the div:
$.ajax({
type: "POST",
url: "/wp-content/plugins/wp-ecommerce-extender/DB_Functions.php",
data: { updateIgallery: "ajax", CurrentDoorIDnum: $('#dooridforgallery').val()}
}).success(function(insertID) {
$("#ImgGalleryID").html(insertID);
});
This so far works what i am having trouble with is the following:
$("#JustantestID").click(function() {
//DoorImageGallery($(this).attr('id')); // the function i will use if the alert actually works
alert("kahdaskjdj");
return true;
});
I hope the question and the code is understandable.
Thanks in advanced.
When you replace element's html, all the elements inside it are removed and gone. That means the event handlers attached to them are removed as well.
You could try attaching an event handler to a higher level element that is static and permanent on your page. Without more info I am going to use document:
$(document).on( "click", "#yaniv", function() {
alert("kahdaskjdj");
});
$('img.JustaTestClass').bind('click', function() {
var checkbox = $(this).siblings('input[type=checkbox]');
if (!checkbox.is(':checked')) checkbox.attr('checked', true);
else checkbox.attr('checked', false);
});
Since the elements are dynamically inserted into the DOM with ajax, you have to delegate events to a parent element that actually exists when binding the click handler, which in this case looks to be #ImgGalleryID
$('#ImgGalleryID').on('click', '#yaniv', function() {
DoorImageGallery(this.id);
alert("kahdaskjdj");
});

Request new page with ajax and open it in new page

I'm having problem trying to request new page(s) from CodeIgniter using JQuery Ajax and open them in a new blank page
The following is the example scenario of current code which is working,
1.) User select the customer's receipt by checkbox
<input type='checkbox' class='customer_id' value='<?php echo $entry->customer_id;?>'>
2.) Javascript read the customer(s) id then send those data to CodeIgniter. Once return data is received, fire callback function to display them target div
var data;
var counter = 1;
$(.customer_id:checked).each(function(){
data['customer_' + counter] = $(this).val();
})
$.post('finance/getReceipt', data, function(){
$('#some_target_div').html(data);
}
3.) CodeIgniter retrieve customer data from db and generate page
function getReceipt(){
$counter = 1;
while ($this->input->post('customer_' + $counter)){
$where['customer_id'] = $this->input->post('customer_' + $counter);
$data += $this->getCustomerReciept($where);
}
$this->load->page('finance/receipt', $data);
}
But now I need to convert this code to make it open a new blank page with a print button
The purpose of this is because I want to generate a formatted receipt and display in a new blank page with a print button. I know that there are several plugin that I can print a div but this is the request from my client. So, that's isn't a solution for me.
Any suggestion or comment will be great. Thank in advance.
I think the easiest way would be to create an auxiliar form to post your data to a new page instead of using $.post So, this would be the code:
var data;
var counter = 1;
$(.customer_id:checked).each(function(){
data['customer_' + counter] = $(this).val();
});
$('<form action="finance/getReceipt" method="POST" target="_blank" style="display:none">' +
'<input type="hidden" name="data1" value="value-data1" />'
).appendTo("body").submit().remove();
Just change your data1 param to the one you want, or add more if you want.
And that's it. The magic is in using a _blank target for the form.
Hope this helps. Cheers
PS: The other way would be creating a new window with window.open and assign its content with javascript.

Form is removed from AJAX response

I'm trying to add a table row with ajax/jquery that has a form element in it. Everything works just fine if I set it without the ajax, but somehow everything inside the <form> tag is just completely lost.
I'm not sure where I'm losing the form (jquery's .html() is effectively the same as innerHTML right? If that's the case I suspect that's where I'm losing it).
Anyway, here's some code:
var worow = document.getElementById('worow_' + row);
var wotable = document.getElementById('tbl_workorders');
// add a new row to the table underneath our existing row.
var newrow = wotable.insertRow(worow.rowIndex+1);
var x = newrow.insertCell(0);
// set up the row a little bit
x.colSpan = 13;
x.style.padding = '10px';
x.style.backgroundColor = '#ccc';
x.align = "center";
x.innerHTML = '<img src="/images/loading.gif" />';
// a little ajax cuz we're cool that way
$.post("getwotrans.php",
{
workorder: row
},
function(response)
{
// set the value of the row = response object from the AJAX
$(x).html(response);
});
And in getwotrans.php: (paraphrased)
<table>
<thead><tr><td>blahblah</td></tr></thead>
<tbody><form><tr><td><input></td></tr></form></tbody>
</table>
So what happens is I'll run the javascript function to add the row, and the row is added fine and I see the table headers, but the 'form' inside the tbody is just not there.
I had some simliar problem. I used a hidden form and javascript to copy the values of the row clicked to the hidden form elements and then submit the form via javascript. Maybe that's an idea.
a form cannot be a child element of tbody
What happens when you put the form outside of the table?
<form><table>
<thead><tr><td>blahblah</td></tr></thead>
<tbody><tr><td><input></td></tr></tbody>
</table></form>
Just curious if this will fix the issue or not? It is odd that this would happen without something equally odd to fix it!

Categories