On my Code I have this callback
$('#tagList').tagit({
//Every new dag will be pushed in the list array
tagsChanged: function(tagValue,action,element){
list.push(tagValue);
$.ajax({
url: "dostuff.php",
type: "POST",
data:{ items:list.join("::")},
success: function(data){
$('#wrap').append(data);
}
});
}
});
What it does it that each time I add a tag the newly added tag will be pushed in the array and after that it will make an AJAX post request.
And Then i have these field here
<form method = "POST" action = "demo3.php">
News Title <input id = "news_title" type = "text" name = "news_title" /><br>
<label>Insert Some tags </label>
<ul id="tagList" data-name="demo2">
</ul>
<input type = "submit" name = "submit" id = "submit" value = "Post News" />
</div>
</form>
and when I click the submit(it basically reloads the page) the $_POST['items'](This was created on AJAX request everytime a new tag is added) is being erased or removed in the POST global array. and therefore leaving my $_POST global array empty.
Is there anyway I can merge these two? or anyway not to let PHP override or remove the $_POST['items'] ?since I would be needing items for my query
Also I am using a plugin called tagit
If you guys are interested here's my whole code
<!doctype html>
<html>
<head>
<script src="demo/js/jquery.1.7.2.min.js"></script>
<script src="demo/js/jquery-ui.1.8.20.min.js"></script>
<script src="js/tagit.js"></script>
<link rel="stylesheet" type="text/css" href="css/tagit-stylish-yellow.css">
<script>
$(document).ready(function () {
var list = new Array();
$('#tagList').tagit({
//Every new dag will be pushed in the list array
tagsChanged: function(tagValue,action,element){
list.push(tagValue);
$.ajax({
url: "dostuff.php",
type: "POST",
data:{ items:list.join("::")},
success: function(data){
$('#wrap').append(data);
}
});
}
});
});
</script>
</head>
<body>
<div id="wrap">
<div class="box">
<button class = "viewTags">View Tags</button>
<form method = "POST" action = "demo3.php">
News Title <input id = "news_title" type = "text" name = "news_title" /><br>
<label>Insert Some tags </label>
<ul id="tagList" data-name="demo2">
</ul>
<input type = "submit" name = "submit" id = "submit" value = "Post News" />
</div>
</form>
</div>
</body>
</html>
and here's dostuff. php
<?php
$lis = $_POST['items'];
$liarray = explode("::", $lis);
print_r($liarray);
print_r($_POST);
?>
The way PHP handles requests are that every request is completely separated from every other one, this sometimes referred as the share nothing architecture. This is the reason of that the request generated from the <form> to demo3.php doesn't know about the other requests sent by ajax to dostuff.php is this separation. This is not necessarily php specific, it's because the underlying HTTP protocol is stateless.
If you want to include tags into the request generated when your <form> is submitted you need to add those values to the form. For this, the tagit library has a built in way controlled by two config option:
itemName controls what the parameter named (defaults to item)
fieldName controls what the field in the itemName gets called (defaults to tags)
If you initialize your plugin like this (demo without styles):
$('#tagList').tagit({
itemName: 'article',
fieldName: 'tags'
});
Then on submit, the parametes sent down to php should be in $_POST['article']['tags'], the parameter names generated will look like article[tags][]. See the demos of the plugin. (the page source has nicely formatted javasript examples). By default simply calling $('#tagList').tagit(); without all the extra callbacks or configuration should work.
This is how it should show up in the net panel of firebug (never mind the demo4.php not beeing there)
If you want to do it manually you can hook into the submit event of <form> like this:
$('form').on('submit', function(){
var $form = $(this),
tags = $('#tagList').tagit('assignedTags'); // see the docs https://github.com/aehlke/tag-it/blob/master/README.markdown#assignedtags
$.each(tags, function(i, tag){
$('<input type="hidden" name="tags[]">').attr('value', tag).appendTo($form); // using jquery to create new elements
});
});
By using the assignedTags method (with jquery ui calling schema) of the tagit plugin, you can get the tag names, and simply add a new hidden input just before submitting the <form>. Joining them together like this might be a bad idea if your can include any string imaginable even ::.
In the example, i've used separate input for each tag so in your demo3.php they will arrive as an array (ending the name with [] makes php do that).
Related
is it possible to use jquery.post for 2 level what i mean is (the secod $.post depends on the first one )
let's assume that a company have a phone number, name and description (for the sake of this example)
<body>
// retrieving companies that have a name similar (or contains )
// what is written in the input box bellow :
<form method="POST" id="searchForm">
<input type="text" name ="name" id="name">
<input type="submit" value="Find">
</form>
// when the user enter a name in the input and submit the form
// with out refreshing the page (adding return false to the jquery click function)
// we will display all retrieved company code inside <ul>(using loop for example)
<ul id="companies_list">
<li id="company"><input type="hidden" value="[company code goes here ]>
<span>[company name goes here]</span><li>
</ul>
// the user select the desired company name (li item )
// and then without refreshing the page we will display the information
// about the selected company in the company_details area
<div id="company_details">
[here goes the selected company details]
</div>
jquery code :
$(document).ready(function(){
// when the dom is ready start manipulating
$("#searchForm").submit(function(event){
// stop form from being submited normaly
event.preventDefault();
// sendig post data
var name = $("input[type="text"]").val();
var url = "ajax/search.php";
var posting = $.post( url, {name:name} );
posting.done(function(data) {
// assuming the data holds companies list (ie: <li>c1</li><li>c2</li>)
$("#companies_list").html(data);
});
});
// the last part (below) does'not work for me
$("#company").click(function(){
var code = [ company code stored in hidden field]
var url = 'ajax/detail';
var posting1 = $.post(url,{code:code});
posting1.done(function(data){
put the result in the company_details div
$("#company_details").html(data)
});
return false;
});
});
Yes, the third argument to $.post is function that is executed when post successfuly completes. So the code would be:
$(document).ready(function(){
// when the dom is ready start manipulating
$("#searchForm").submit(function(event){
// stop form from being submited normaly
event.preventDefault();
// sendig post data
var name = $("input[type="text"]").val();
var url = "ajax/search.php";
var posting = $.post( url, {name:name}, function(data) {
// assuming the data holds companies list (ie: <li>c1</li><li>c2</li>)
$("#companies_list").html(data);
} )
});
I'm posting dynamically added form elements to PHP via AJAX.
I can see that the serialised form data is posted to the php, but when I try to access the data within it, some of the fields come up NULL i.e. var_dump in the PHP below shows NULL.
this is the Jquery that adds the dynamic elements:
$(function(){
var count=0;
$('#more_edu').click(function(){
count ++;
$('#education_add').append('<br><br><label>University/Institution: </label><input type="text" class="searchbox" id="edu_inst'+count+'" name="edu_inst[]" maxlength="200" value="">);
event.preventDefault();
});
});
and the Jquery posting to php:
function profileSub(){
var myform;
event.preventDefault();
myform = $('form').serialize();
$.ajax({
type: 'POST',
url: 'tutorprofileinput.php',
data: {"form": myform},
success:function(data, response, xhr){
console.log(response);
console.log(data);
console.log(xhr);
},
error:function(){
// failed request; give feedback to user
$('#ajax-panel').html('<p class="error"><strong>Oops!</strong> Try that again in a few moments.</p>');
}
});
}
This is the original form:
<form id="tutor_profile_input" onsubmit="return false;">
<label>University/Institution: </label>
<input type="text" class="searchbox" id="edu_inst" name="edu_inst[]" maxlength="200" value=""> </br></br>
<label>Subject:</label>
<input type="text" class="searchbox" id="edu_subj" name="edu_subject[]" maxlength="200" value=""></br></br>
<label> Level </label>
<select id="edu_level" name="edu_level[]">
and the PHP itself:
<?php
if (isset($_POST['form'])){
$form = $_POST['form'];
var_dump($_POST["edu_inst"]);?>
This is the var dump of the whole $_POST:
location=&price=&tutorname=&edu_inst%5B%5D=Uni1&edu_subject%5B%5D=subje1&edu_level%5B%5D=BA&edu_inst%5B%5D=uni2&edu_subject%5B%5D=subj2&edu_level%5B%5D=BA&bio=%09&exper
The form you've posted has an ID of #tutor_profile_input, where as the one you're appending to in the jQuery function is #education_add - Unless I've misunderstood?
Otherwise I'd look at specifying a more specific target in the AJAX request - You're just targetting $('form') at the moment which could be any form on the page..
Have discovered the answer so thought I would share - The Jquery serialize() function encodes the data into a string, which is then posted to PHP as an array with the key of "form".
In order to deal with this in php I had to first use the urldecode function in PHP to convert the string encoded elements (%5B%5D) from the name attributes. This was because there might be multiple values in these so they were declared in the form as an array ("name="edu_insts[]"). Then use parse_str to split the string into an array.
<?php
$querystring = $_POST['form'];
$querystring = urldecode($querystring);
parse_str($querystring, $params);
$insts = $params['edu_inst'];
echo $insts[0]."<br>";
echo $insts[1]."<br>";
?>
This will create an array named $params with keys corresponding to the form name attributes.
Note that if you have multiple values within the same name, then each one will be placed within an array itself, so with the above text you will have $insts[0] = University 1
and $insts[1] = University 2 etc.
Hope this helps anyone with the same problem.
I am building an application in Code Igniter and am currently building some functionality where a user can approve or deny a request on the page by clicking either a tick or a cross icon on the page. These icons are anchor tags.
The trouble I am having is passing an ID for that individual request to the AJAX form.
I would have no issue implementing this functionality in a form as I would simply use a hidden input field which would have it's value saved in it set from the controller. There can be many of these requests but they would always have their own individual ID as it is looped through in the view.
As I am using anchor tags instead of a form I am not sure where I could store the id for that request in the markup.
Here is the code:
<p><span class="bold">Authorise This Request?: </span></p>
<p>
<img src="/igniter/images/tick.png" />
<img src="/igniter/images/cross.png" />
</p>
</div>
<?php $i++; ?>
<?php } ?>
</div>
<script type="text/javascript">
$(document).ready(function() {
$('.authorise').click(function() {
$.ajax({
type: "POST",
url: 'holiday_request/authoriseRequest',
data: 'check=' + $(this).attr('id'),
success: function(data) {
}
});
return false;
});
});
</script>
As you can see I use the ID of the input field to determine later on whether to allow or deny it. All I want to do is to be able to pass the ID for that request through which is currently in the controller, so adding '&id= blahblahblah' onto the end of the URL variable in the AJAX call.
Is there a way I can do this without having to use a form instead of anchor tags?
You can use HTML5 data-* Attributes
<img src="/igniter/images/tick.png" />
...
Then get the value and add it to ajax data parameter
data: 'check=' + $(this).data('check') + '&id=' + $(this).data('id'),
You can store the ID in Data attribute of the anchor tag.
<img src="/igniter/images/tick.png" />
To get the stored value for allow anchor tag using jquery.
$val_allow = $('#allow').data('val'); // value 10
You can try using $.post and can have custom parameters as you like!
$.post({ 'holiday_request/authoriseRequest' , { check: someId , anotherParam: 1 } ,
function(response)
{
console.log(response);
}
});
So, basicly what I'm trying to achieve:
In index.php
I would enter products code to search for products information and it's images (that query is run in open_first.php, called via ajax post request).
It works just perfect..
When open_first.php is loaded, it displays me some images I can select from (when I click on the image, it's relevant checkbox get's checked containing the image id).
This works too, just fine.
BUT,
If I enter a code in the field: "productCodeCopy" and click on "confirmCodeCopy" -button it reloads the whole page, I mean index.php and everything I've entered is lost and I'm back in the starting point again. I don't understand why it does so. I suppose it has something to do with the fact, that the second ajax request is made from a dynamically created page (open_first.php)?? Do I miss something I should POST too?? Or what's the problem, this is really frustrating me since I've tried to fix this for hours now.
Note:
Jquery is loaded in index.php, open_first.php and open_second.php, I've just ignored that to keep the code simpler.
FILE: index.php (the "starting point")
<!-- head -->
<script type="text/javascript">
$(document).ready(function() {
$("#confirmCode").on('click', function(){
var productCode = $("#productCode").val();
$.ajax({
url: 'open_first.php',
type: "POST",
data: ({code: productCode}),
success: function(data){
$("#found").html(data);
},
error: _alertError
});
function _alertError() {
alert('error on request');
}
});
});
</script>
<!-- body -->
<input type="text" class="textfields" id="productCode" name="productCode" value="YT-6212">
<input type="button" class="admin-buttons green" name="confirmCode" id="confirmCode" value="Search">
<div id="found"></div>
FILE open_first.php
<script type="text/javascript">
$(function() {
$("#foundImage").on('click', function(){
$('#foundImage').toggleClass("foundImage-selected foundImage");
var myID = $('#foundImage').data('image-id');
var checkBox = $('input[id=selectedImages-'+myID+']');
checkBox.prop("checked", !checkBox.prop("checked"));
});
$("#confirmCodeCopy").on('click', function(){
var checkedItems = $('input:checkbox[name="selectedImages[]"]:checked');
// this code here reloads the whole page / view (as in "index.php")
$.ajax({
url: 'open_second.php',
type: "POST",
data: ({checked: checkedItems, copyTo: productCodeCopy, code: "<?php echo $_POST['code']; ?>"}),
success: function(data){
$("#copyToProducts").append(data);
},
error: _alertError
});
/*
// the code below runs just fine when I hit the button "confirmCodeCopy"
alert('Fuu');
return false;
*/
});
function _alertError() {
alert('error');
}
});
</script>
<!--BODY-->
<!-- these are dynamically generated from php, just to simplify we have checkbox that contains value "1" to be posted in ajax -->
<div class="foundImage" id="foundImage" data-image-id="1"><img src="image.jpg"><input type="checkbox" id="selectedImages-1" name="selectedImages[]" value="1" style="display: none;"></div>
<label for="productCodeCopy">Products code</label>
<input type="text" class="textfields" id="productCodeCopy" name="productCodeCopy">
<br /><br />
<label for="confirmCodeCopy"> </label>
<input type="button" class="admin-buttons green" name="confirmCodeCopy" id="confirmCodeCopy" value="Search">
<div id="copyToProducts"></div>
open_second.php only prints out POST variables for now, so nothing special yet.
SOLVED
So ok, I solved it. With dumdum's help.
I removed the line:
$('input:checkbox[name="selectedImages[]"]:checked');
And added this:
var checkedItems = new Array();
var productToCopy = $('#productCodeCopy').val();
$("input:checkbox[name=selectedImages[]]:checked").each(function() {
checkedItems.push($(this).val());
});
Since there was no form element present, it didn't get the field values unless "manually retrieved" via .val() -function.. Stupid me..
I don't know how much this affected but I changed also:
data: ({checked: checkedItems, copyTo: productCodeCopy"})
To
data: {"checked": checkedItems, "copyTo": productToCopy}
So now it's working just fine :) Cool!
WHen you apply event hander to a button or a link to do ajax...always prevent the browser default processing of the click on that element
There are 2 ways. Using either preventDefault() or returning false from handler
$("#confirmCodeCopy").on('click', function(event){
/* method one*/
event.preventDefault();
/* handler code here*/
/* method 2*/
return false;
})
The same is true for adding a submit handler to a form to do ajax with form data rather than having the form redirect to it's action url
your code $('input:checkbox[name="selectedImages[]"]:checked'); is returning undefined making the json data in the ajax call invalid. Check you selector there.
I'm implementing a relatively simple autosave system and I'd like to do so using the Prototype library. I'm using the PeriodicalUpdater request, but it's not working as I'd hoped. In short, I'm trying to, periodically, send a textarea's content via an AJAX request to a PHP page that will save it to a MySQL database. I'm doing something like (abbreviated code):
<html>
<head>
<script type="text/javascript" src="scripts/prototype.js"></script>
<script>
function autosave() {
new Ajax.PeriodicalUpdater('save_message', 'autosave.php',
{
method: 'post',
parameters: {id: $('id').value, save_text: $('myInput').value},
frequency: 5,
decay: 2
});
}
</script>
</head>
<body>
<input type="hidden" id='id' name='id' />
<textarea id='myInput' name='myInput'></textarea>
<script>
autosave();
</script>
</body>
</html>
Then autosave.php will take the form contents and write them to my database. That part is working fine. What is happening, as I discovered, is PeriodicalUpdater is called with the original form input, then is called periodically with that initial form input.
So that was a long setup for a relatively short question: How do I use Prototype (if possible) to periodically make an AJAX request using the current textarea's value?
you could just use Ajax.Request with setinterval,something like this:
document.observe("dom:loaded", function() {
intervalID = window.setInterval("autosave()",500);
});
function autosave() {
new Ajax.Request('autosave.php',
{
method: 'post',
parameters: {id: $('id').value, save_text: $('myInput').value},
});
}
Ajax.Request is the right move, but why not make it more reusable
If you just have one input, or even if you had many I'd advise something like:
<form action="/user/4" method="post">
<input type="text" name="user[name]" value ="John" class="_autosave" />
<input type="hidden" name="user[id]" value ="4" class="uid"/>
<input type="submit" />
</form>
...
$$('input._autosave').each(function(s){
s.observe("change", function(event){
var el = event.element();
var uid = el.next("uid").value;
var r = new Ajax.Request(el.up("form").readAttribute("action"),{
parameters: {el.readAttribute("name"): el.value},
});
});
});
Just place your periodical updater in dom:loaded event. It is used to ensure that all components have been loaded, better than using window.onload event. Just remember, that there is a little bit different between dom:loaded event and native window.onload event, where dom:loaded called when all dom loaded except images and window.onload called when all dom loaded including images file.
document.observe("dom:loaded", function() {
new Ajax.PeriodicalUpdater('save_message', 'autosave.php', {
method: 'post',
parameters: {id: $('id').value, save_text: $('myInput').value},
frequency: 5,
decay: 2
});
});