JQuery Form Plugin, can't receive data in PHP - php

I'm using JQuery Form Plugin for AJAX file uploader.
The (html) form is created dynamically, and looks like this:
<form id="formUpload" action="fileReceiver.php" method="post" enctype="multipart/form-data">
<input type="file" name="fileUpload" multiple>
<input type="submit" value="Upload File to Server">
</form>
Because, the form is created dynamically, I'm using jquery on(). I also need to send a few variables, I'm using data options from the plugin.
The Javascript looks like this:
$(document).on("submit", "form#formUpload", function() {
$(this).ajaxForm({
data: { someVariable : 'someValue' },
complete: function(xhr) {
status.html(xhr.responseText);
}
});
});
I think the form is binded correctly, I could call/alert something from the ajaxForm (jquery form plugin) function through beforeSend or Success options.
Now, the problem is the PHP couldn't get the data I posted in the Javascript.
My PHP is simple like this:
<?php
echo $_POST["someVariable"];
?>
It gives me error "Notice: Undefined index: someVariable blah blah blah"
Any advice? Thx :)

Try adding some variables in hidden input inside form
<input type="hidden" name="someVariable" value="someValue">
and remove $(document).on("submit",... event
You can try
var input = $("<input>").attr("type", "hidden").attr("name", "someVariable").val("someValue");
$('#formUpload').append($(input));
this links may help you
http://www.malsup.com/jquery/form/progress2.html
http://www.malsup.com/jquery/form/file-echo2.php.txt

Well, in case your form is being added dynamically then you'd have to use DOMNodeInserted event instead of submit. That way, whenever there's some addition in DOM your form will be attached to form plugin.
You can replace your function with following --
$(document).on("DOMNodeInserted", "form#formUpload", function() {
$(this).ajaxForm({
data: { someVariable : 'someValue' },
complete: function(xhr) {
// do something
}
});
});
But remember, using DOMNodeInserted event will fire that method whenever there's addition of any kind into DOM. So just put what is essential ( in this case form plugin init for #formUpload ) .

Try to locate if you already added the jQuery Form Plugin...
<script src="jquery.form.js"></script>
Your syntax is definitely correct according to http://malsup.com/jquery/form/#options-object

Related

Ajax request inside ajax request fails - reloads the whole page again

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.

php load data into fancybox when is load with JSON

I have a php page with a fancybox.
I have a a page in php that with jquery shown a fancybox.
When the fancybox is shown I need to load data from database.
Code of the click event:
$("a#addActivitat").click(function(){
var retorn;
$.getJSON('aplicacio/agendaLoadData.php?action=loadIdAct',function(data){
retorn = data;
});
alert(retorn);
});
The alert is undefined
the code of fancybox:
<div id="agendaAddAct">
<form method="post" action="" target="workFrame" id="actionform">
<p>
<input type="text" name="idRel" id="idRel"/>
</p>
<input type="button" value="Afegir activitat" class="btnsubmit" id="afegirActivitat"/>
</form>
</div>
I need that the value returned of php call is loaded in the idRel input.
And the code of the agendaLoadData that is called with JSON:
$var = new facanabbdd();
echo json_encode($var->getMaxValueRel());
You are not using $.getJSON correctly. Keep in mind that Ajax requests are asynchronous (Ajax does after all mean Asynchronous JavaScript and XML).
Therefore your retorn variable will not be filled with the value obtained from the Ajax call.
What you should do instead is update your DOM when you receive the data (ie. in your callback function)
$("a#addActivitat").click(function(){
$.getJSON('aplicacio/agendaLoadData.php?action=loadIdAct', function(data){
$('#idRel').val(data.value);
});
});
Provided your returned JSON document is like
{
"value": 42
}
If you put your alert inside the success handler, it will alert the data, if data is returned from your server. Try it like this:
$("a#addActivitat").click(function(){
$.getJSON('aplicacio/agendaLoadData.php?action=loadIdAct',function(data){
$("#idRel").val(data);
var retorn = $.parseJSON( data );
alert(retorn);
});
});
I found the error:
code of php page:
$("a#addActivitat").click(function(){
$.getJSON('aplicacio/agendaLoadData.php?action=loadIdAct',
function(data){
$('#idRel').val(data);
});
});
And code of agendaLoadData
echo json_decode("43");
The error was that I call the function json_encode and I need to call the function json_decode.

What does jquery .ajaxsubmit pass?

I am trying to use jquery's form plugin from http://www.malsup.com/jquery/form/#ajaxSubmit and .ajaxsubmit to submit my data in a form however I am not really sure what .ajaxsubmit is passing and how I can read this in my php file.
I have a validate function
function validate(formData, jqForm, options) {
alert('About to submit: \n\n' + queryString);
return true;
}
that shows queryString which is
first=testfirstname&last=testlastname&age=90
when I use .ajaxsubmit, nothing happens as listed in my script below.
$(document).ready(function() {
var options = {
target: '#output1',
beforeSubmit: validate,
success: showResponse
};
//submission
$('#myForm').submit(function() {
$(this).ajaxSubmit(options);
return false;
});
});
My form is
<form action="comment.php" method="post" id="myForm">
I was wondering what format is the data being sent, would I do something with
$_REQUEST['first'];
and also how would I also pass in an addition value from the $_SESSION?
Thanks
As far as I know, the jQuery plugin actually sends the plugin data as POST-data to PHP (similar to setting method="post" on your <form> tag). You can access it like this:
$_POST['name_of_field_in_form'];
The name_of_field_in_form is just the name of a field, for example if you have this code <input name="email" type="text" />, you could access it via $_POST['email'];.
About your second query, not sure what you mean, but you can use session_start(); to create a session and after that $_SESSION acts like a 'normal' array.

AJAX (jQuery) Response

Suppose all forms in your application has this structure:
<div id="result_messages"></div>
<form action="/action">
<!-- all the form -->
</form>
A submit button for this form looks like this:
<input type="button" onclick="$.post( '/action', $(form).serialize(), function (data) {
$('#result_messages').html( data ); // At this point the 'data' is an standard HTML with a message
});" />
BUT, But not always the response is a message... how to detect when data is a message or not??????:
<input type="button" onclick="$.post( '/action', $(form).serialize(), function (data) {
if (isMessage( data ))
$('#result_messages').html( data );
else
doActionWith( data );
});" />
Using JSON maybe a solution:
{ response_type : 'message', data: 'all_data_here' }
{ response_type : 'nomessage', data: 'all_data_here' }
Other solution is to put a special STRING at the begin of data:
<!--message--><ul><li>form was processed</li></ul>
Have you other ideas? what do you think about this solutions?
what do you think about this solutions?
<input type="button" onclick="$.post( "/action", $(form).serialize(), function (data) {
That will fall over. The quote before /action will terminate the onclick attribute value
Inline JS is nasty. Bind your event handlers from external scripts.
If JS is not available, this won't work. Write a form that works (with a regular submit button) and then progressively enhance with JS.
form is undefined, that should be this.form
/action is repeating yourself. Write more reusable code: this.form.action
Using JSON maybe a solution
Yes. Use a structured data format instead of a blob of code to shove into the page.
What are the options, other than simple html output? json?
If so, you can send an object back and check it in the callback.

Autosaving Form Input Using Prototype and PHP

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
});
});

Categories