ajax js serialize not reading form elements - php

Have a form that is not being read by serialize() function.
<script type="text/javascript">
function submitTrans1(){
var formData = $('form1').serialize();
var options = {
method:'post',
postBody:'formData',
onCreate: function(){alert(formData)},
onSuccess: function(transport){alert("onSuccess alert \n" + transport.responseText);},
onComplete: function(){alert('complete');},
onFailure: function(){alert('Something went wrong...')}
}
new Ajax.Request('/clients/addTrans/<?=$clientID123?>/',options);
}
</script>
<?php
$datestring = "%Y-%m-%d";
$time = time();
$clid1 = $this->uri->segment(3);
?>
<form name="form1" id="form1">
<div id="addTransDiv" style="display:none">
<div class="">
<label for="transDesc" id="transDesc" value="sadf" class="preField">Description</label>
<textarea cols="40" rows="3" id="transDesc" value="" name="transDesc" class=""></textarea>
</div>
<div class="">
<label for="date" class="preField">Date</label>
<input type="date" id="transDate" name="date" value="<?=mdate($datestring, $time);?>" size="40" class=""/><br/>
</div>
<div class="">
<label for="userfile" class="preField">File</label>
<input type="file" name="transFile" id="userfile" size="20" /><br>
</div>
<input type="button" id="submitTrans" name="submitTrans" value="Submit" onclick="submitTrans1()">
</div>
</form>
Uh, I have an alert in the onSuccess parameter of the Ajax.Request that would ideally alert the variable assigned to the serialized form. However, when it alerts, it alerts nothing. I also have the processing url printing out the $_POST data just in case, but that as well returns an empty array in the responseText, so indeedidly nothing is being posted to the form.
Thx.
Edit1
it seems that the problem might be related to the fact that the form is inside a div. If I remove everything on the page except for the form and js, it works ok. But the form is in a div that is hidden by default and uses another function to be displayed. Is there some kind of magic needed to get form data via serialize if it's in a div?
Edit 2
Tried adding quotes and pound signs and all that other jazz. I am using web developer toolbar, firebug, etc... it isn't throwing any js errors and doesn't afraid of anything.

Try removing the quotes from around the variable name formData in the postBody field.
The web developer toolbar in Firefox is as useful as anything for debugging client-side javascript.
BTW, the snippet contains a few undefined items, like the JS function showTransAdd(), several PHP variables, the PHP function mdate(), and the inclusion of the prototype library.

Change this line:
var formData = $('form1').serialize();
to this:
var formData = $('#form1').serialize();
I had to change several other things to make a working copy, but I'm not sure about what all code you withheld or how your environment may differ. If that doesn't work, I can send you the full code snippet I used.

Erroneous table does the breaking.
I had the form within a table with no tr's or td's (not sure if the last part matters) and upon removing the table tags, everything is working.
The relevant js now looks like:
var formData = $('form1').serialize();
var options = {
method:'post',
postBody:formData,
[...]
I'd like to thank the Academy, and all those that helped me.

Related

using prestashop's 1.7 smarty url tag in a from action property

I'm using prestashop 1.7.2.1 to build a module with a front controller.
what I'm trying to do is to add the smarty{url} tag to the action property of the form. the problem is that once I submit the form all the get parameters that are provided in action property of the from are erased. this is a normal behaviour in html.
this is my code:
<form id="car-type-form" action="{url entity='module' name='tuxinmodcartype' controller='cartypeproducts'}" method="get">
<div id="company-name-input-form-group" class="form-group row">
<label for="company-name-input" class="col-sm-2 col-form-label">Company</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="company-name-input" name="company_name" placeholder="Company" aria-label="Company" required="required"/>
</div>
</div>
...
</form>
In general I can paste that smarty {url} tag to a variable. on submit to add the values of the form fields dynamically to the variable I created and use it to redirect instead of allowing the form to submit.
I just don't know if this is the best solution.
maybe there is something that I missed.
any ideas?
thank you
for now what I did is to add hidden input elements to the form based on the created url string.
I have this on the first line of my template file:
<script type="text/javascript">
var carTypeProductsUrl='{url entity='module' name='tuxinmodcartype' controller='cartypeproducts'}';
</script>
and on the submit function I added the following code:
...
if (isError) {
event.preventDefault();
} else {
$('.hidden-form-params').remove();
var params = carTypeProductsUrl.substr(carTypeProductsUrl.indexOf('?')+1).split('&');
params.forEach((paramStr)=>{
var paramsArray = paramStr.split('=');
const paramKey = paramsArray[0];
const paramvalue = paramsArray[1];
$('#car-type-form').append(`<input type="hidden" name="${paramKey}" value="${paramvalue}" class="hidden-form-params" />`);
});
}
this method feels a bit.. hacky?! :) I just want to make sure this is the way to go

jquery: how to open an url in new tab with passing post data to that url

I have a php file localhost/~user/sample.php file which gets data from post method.
<?php
$you = $_POST["ids"];
$start= $_POST["start"];
echo $you."--".$start;
I want to write a jquery code which will open the url "localhost/~user/sample.php" in a separate window on button click inside my html page and also pass the arguments required for it.
I can use get method in php, but the number of variables are more
I would probably go for using a form, like so:
<form action="sample.php" method="post" target="_blank">
<input type="hidden" name="name1" />
<input type="hidden" name="name2" />
...
<input type="hidden" name="name20" />
<input type="submit" value="Go to page">
</form>
This is the most cross-browser JS-failsafe basic html version way of achieving this task that I can think of...
If you need to dynamically add form fields to the form, I believe you will find this question: Jquery - Create hidden form element on the fly handy. Copying the modified answer:
$('<input type="hidden" name="myfieldname" value="myvalue">').appendTo('form');
One way would be to dynamically create a hidden form and then submit it, make sure you encode the input:
var params = [['someKey0', 'someValue0'], ['someKey1', 'someValue1'], ['someKey2', 'someValue2'], ['someKey3', 'someValue3']];
var inputs = $.map(params,function(e,i){
return '<input type="hidden" name="'+e[0]+'" value="'+encodeURIComponent(e[1])+'"/>';
});
var form ='<form action="sample.php" id="hidden-form" method="post" target="_blank">'+inputs.join('')+'</form>';
$('#hidden-div').html(form);
$('#hidden-form').submit();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="hidden-div"></div>
Try this....
<form id="myForm" action="sample.php" method="post">
<?php
echo '<input type="hidden" name="'.htmlentities($you).'" value="'.htmlentities($start).'">';
?>
</form>
<script type="text/javascript">
document.getElementById('myForm').submit();
</script>
if you send request with javascript to any php page; it sends a request and gets the respose to the page which has sent request and you continue process your data at your first page. So if you want to open your sample.php and also send your post data within; you must send your data with something like php form.
Submitting forms: http://www.w3schools.com/php/php_forms.asp
If you want to use js post, you can do something like below:
teams.php:
data = { teams : ['Real Madrid','Barcelona','etc']};
var response = null;
$.ajax({
url : 'mypostfile.php',
type : 'POST',
data : data
})
.done(function(resp){ response = resp; //it returned from php echo })
.fail(function(){ console.log('fail'); //post process failed. });
mypostfile.php:
if(isset($_POST['teams'])){
$teams = $_POST['teams'];
echo $teams[0]; //response : Real Madrid
}
Hope it helps.

HTML editor embedded in admin page

I'm working on a simple webpage for a company and the company wants to be able to edit the content themselves from time to time. However they have no programing knowledge and therefore I want to use an embedded HTML editor, I have chosen jQuery TE.
The problem is that I only know how to use this as a form, e.g.:
<form id = "wyForm" method="post" action="test.php">
<textarea class="editor"name = "testText">Hi</textarea>
<input type="submit" class="wymupdate" />
</form>
Then I would convert the textarea to an editor with jQuery:
<script> $('.editor').jqte() </script>
This makes it possible to send the result to a .php page that updates the database. However many times I don't want to use a textfield or a form, but just a simple object that I convert to an editor in the same way. But how do I save the change in that case?
Catch the form submit event and copy the content to a hidden field.
<form id = "wyForm" method="post" action="test.php">
<div class="editor" name="testText">Hi</div>
<input type="submit" class="wymupdate" />
<input type="hidden" id="editorHiddenField" />
</form>
...
$('#wyForm').submit(function() {
$('#editorHiddenField').val($('.editor').html());
});
You may need to use an API to get the content instead (I'm not familiar with the plugin), but the concept is sound.
Edit - If you don't want to use a form at all:
<div class="editor></div>
<button id="SaveButton">Save</button>
...
$(document).ready(function() {
$('#SaveButton').click(function(e) {
e.preventDefault();
$.post('savepage.php', { data: $('.editor').html() }).done(function() { alert('saved!'); });
});
});

JQuery-AJAX post workflow

EDIT
Forgot a couple of improtant points.
I am doing this to eliminate the page from having to refresh and therefore jumping back up to the top of the page.
The success function of the ajax function will kick back an entire new div id="comments" to replace the existing one with either an error msg or the new comment with all other below it.
END EDIT
I have been trying to this jquery-ajax function under wraps unsuccessfully. I have X number of posts on a page with each having a form for inserting comments under each post. I think I am pretty close and have tried to debug it using firebug, but honestly I don't really know what I am looking at or for in firebug.
All code is below, any help would be much appreciated!
HTML form and structure (because of the repetative forms, I feel I should use the parent jquery selection method, rather than iterating each post-comment partition in my output script)
<div id="content_body_right">
<div id="activity">
....this is the area for each post....
</div>
<div id="comments">
<p class="comments_label">' . $reply_count . ' Comment</p>
<div id="comment1">
<div id="comment_user_img">
' . $imgOutputReply . '
</div>
<div id="comment_user">
<p class="user_text_comment">' . $firstNameReply . ' ' . $lastNameReply . '</p><p class="date_text_comment">' . $date_timeReply . '</p>
<p class="message_text_comment">' . $messageReply . '</p>
</div>
</div>
<div id="add_comment">
<form id="formAddComment" action="dashboard.php" enctype="multipart/form-data" method="post">
<div id="add_comment_left">
<textarea id="comment" name="comment" cols="75" rows="2">Add a Comment...</textarea>
</div>
<div id="add_comment_right">
<input id="userID" name="userID" type="hidden" value="' . $userID . '" />
<input id="actID" name="actID" type="hidden" value="' . $actID . '" />
<input id="btnComment" name="btnComment" type="submit" value="" title="Add Comment" />
</div>
</form>
</div>
</div>
</div>
OK, now the JQuery markup
<script type="text/javascript">
$(document).ready(function(){
$("#formAddComment").submit( function(e) {
e.preventDefault();
var form = $(this);
var div_add_comment = form.parent();
var div_comments = div_add_comment.parent();
$.ajax({
type: "POST",
data: form.serialize(),
url: "includes/comment.php",
success: function(msg){
$div_comments.html(msg);
}
});
return false;
});
});
</script>
Lastly the external php script (NOTE: I will only post the initial lines where i localize the data feed into php vars.)
if(isset($_POST['actID'])){
$actID = mysql_real_escape_string($_POST['actID']);
$userID = mysql_real_escape_string($_POST['userID']);
$comment = mysql_real_escape_string($_POST['comment']);
............other processing here...........
}
I am suspicious of my jquery script mostly.
Thanks again,
I dropped the general structure into a jsfiddle at http://jsfiddle.net/cori/JsLWq/, and when I submit the form I do indeed get an ajax POST to the non-existant http://fiddle.jshell.net/cori/JsLWq/show/includes/comment.php due to the relative ajax url, so that's not the problem as far as I can tell. What I do think is the problem is that you're mixing your variable naming rules.
You start off naming your variables like plain-old javascript objects
var form = $(this);
var div_add_comment = form.parent();
var div_comments = div_add_comment.parent();
but then in your success handler you switch to the fairly-common $x convention, often used to indicate that a variable is a jQuery instance:
$div_comments.html(msg);
however at that point there is no variable $div_comments; only div_comments. If you submit the form in http://jsfiddle.net/cori/JsLWq/1/, which has an ajax error handler, and look at your firebug console, you'll see that you get a ReferenceError because $div_comments is undefined.
EDIT
Incorporating kgarrigan's suggestions, if in your php you loop over the forms you want to create, and keep track of your position using an index, you could rename your forms with the index, so your form php/html code would look something like:
<form id="formAddComment-' . $index . '" action="dashboard.php" enctype="multipart/form-data" method="post">
so you would end up with form elements with ids like formAddComment-1.
Then in your jquery you would select all the forms using the startsWith selector and bind the submit event to them, thusly:
$('[id^="formAddComment"]').submit( function(e) {
// do your ajax
});
That way each form will have it's own submit handler.
jquery works with selectors. When you write $(something) something is the selector. It can be an id, a class name, a variable, html elements. So instead of
$("#formAddComment").submit( function(e) {
You could use
$(".someclassName").submit( function(e) {
just like css, use # for id, . for class. Just make sure you add the class attribute to your form with the same name. You could also try
$("form").submit(function(e) {
which should select any form elements. I think the rest of your function should work fine with this change, since you are using 'this' and parent() instead of any direct references.
In firebug, click on console, then on all. When you click on the button to trigger your ajax call you should see a line pop up, probably with a loading icon that shows a post request being sent. You should be able to click on the tabs to see what data is being posted and what response is given as well as a response status code...
In your edit, you say the success function will send out a new div id="comments" to replace the existing one, but as you have it written now, I believe it will just add a div id="comments" inside the existing one. Don't know if this would cause your problem though.
If you have multiple forms on the same page, with the same id's this will cause the problem. Especially the # formAddComment id, which is attached to the submit () call. If there are multiple of these ids, this won't work

Calling a PHP function from an HTML form in the same file

I'm trying to execute a PHP function in the same page after the user enters a text and presses a submit button.
The first I think of is using forms. When the user submits a form, a PHP function will be executed in the same page. The user will not be directed to another page. The processing will be done and displayed in the same page (without reloading).
Here is what I reach to:
In the test.php file:
<form action="test.php" method="post">
<input type="text" name="user" placeholder="enter a text" />
<input type="submit" value="submit" onclick="test()" />
</form>
The PHP code [ test() function ] is in the same file also:
<?php
function test() {
echo $_POST["user"]; // Just an example of processing
}
?>
However, I still getting a problem! Does anyone have an idea?
This cannot be done in the fashion you are talking about. PHP is server-side while the form exists on the client-side. You will need to look into using JavaScript and/or Ajax if you don't want to refresh the page.
test.php
<form action="javascript:void(0);" method="post">
<input type="text" name="user" placeholder="enter a text" />
<input type="submit" value="submit" />
</form>
<script type="text/javascript">
$("form").submit(function(){
var str = $(this).serialize();
$.ajax('getResult.php', str, function(result){
alert(result); // The result variable will contain any text echoed by getResult.php
}
return(false);
});
</script>
It will call getResult.php and pass the serialized form to it so the PHP can read those values. Anything getResult.php echos will be returned to the JavaScript function in the result variable back on test.php and (in this case) shown in an alert box.
getResult.php
<?php
echo "The name you typed is: " . $_REQUEST['user'];
?>
NOTE
This example uses jQuery, a third-party JavaScript wrapper. I suggest you first develop a better understanding of how these web technologies work together before complicating things for yourself further.
You have a big misunderstanding of how the web works.
Basically, things happen this way:
User (well, the browser) requests test.php from your server
On the server, test.php runs, everything inside is executed, and a resulting HTML page (which includes your form) will be sent back to browser
The browser displays the form, the user can interact with it.
The user submits the form (to the URL defined in action, which is the same file in this case), so everything starts from the beginning (except the data in the form will also be sent). New request to the server, PHP runs, etc. That means the page will be refreshed.
You were trying to invoke test() from your onclick attribute. This technique is used to run a client-side script, which is in most cases Javascript (code will run on the user's browser). That has nothing to do with PHP, which is server-side, resides on your server and will only run if a request comes in. Please read Client-side Versus Server-side Coding for example.
If you want to do something without causing a page refresh, you have to use Javascript to send a request in the background to the server, let PHP do what it needs to do, and receive an answer from it. This technique is basically called AJAX, and you can find lots of great resources on it using Google (like Mozilla's amazing tutorial).
Here is a full php script to do what you're describing, though pointless. You need to read up on server-side vs. client-side. PHP can't run on the client-side, you have to use javascript to interact with the server, or put up with a page refresh. If you can't understand that, there is no way you'll be able to use my code (or anyone else's) to your benefit.
The following code performs AJAX call without jQuery, and calls the same script to stream XML to the AJAX. It then inserts your username and a <br/> in a div below the user box.
Please go back to learning the basics before trying to pursue something as advanced as AJAX. You'll only be confusing yourself in the end and potentially wasting other people's money.
<?php
function test() {
header("Content-Type: text/xml");
echo "<?xml version=\"1.0\" standalone=\"yes\"?><user>".$_GET["user"]."</user>"; //output an xml document.
}
if(isset($_GET["user"])){
test();
} else {
?><html>
<head>
<title>Test</title>
<script type="text/javascript">
function do_ajax() {
if(window.XMLHttpRequest){
xmlhttp=new XMLHttpRequest();
} else {
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var xmlDoc = xmlhttp.responseXML;
data=xmlDoc.getElementsByTagName("user")[0].childNodes[0].nodeValue;
mydiv = document.getElementById("Test");
mydiv.appendChild(document.createTextNode(data));
mydiv.appendChild(document.createElement("br"));
}
}
xmlhttp.open("GET","<?php echo $_SERVER["PHP_SELF"]; ?>?user="+document.getElementById('username').value,true);
xmlhttp.send();
}
</script>
</head>
<body>
<form action="test.php" method="post">
<input type="text" name="user" placeholder="enter a text" id="username"/>
<input type="button" value="submit" onclick="do_ajax()" />
</form>
<div id="Test"></div>
</body>
</html><?php } ?>
Without reloading, using HTML and PHP only it is not possible, but this can be very similar to what you want, but you have to reload:
<?php
function test() {
echo $_POST["user"];
}
if (isset($_POST[])) { // If it is the first time, it does nothing
test();
}
?>
<form action="test.php" method="post">
<input type="text" name="user" placeholder="enter a text" />
<input type="submit" value="submit" onclick="test()" />
</form>
Use SAJAX or switch to JavaScript
Sajax is an open source tool to make
programming websites using the Ajax
framework — also known as
XMLHTTPRequest or remote scripting —
as easy as possible. Sajax makes it
easy to call PHP, Perl or Python
functions from your webpages via
JavaScript without performing a
browser refresh.
That's now how PHP works. test() will execute when the page is loaded, not when the submit button is clicked.
To do this sort of thing, you have to have the onclick attribute do an AJAX call to a PHP file.
in case you don't want to use Ajax , and want your page to reload .
<?php
if(isset($_POST['user']) {
echo $_POST["user"]; //just an example of processing
}
?>
Take a look at this example:
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<?php
// define variables and set to empty values
$name = $email = $gender = $comment = $website = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = test_input($_POST["name"]);
$email = test_input($_POST["email"]);
$website = test_input($_POST["website"]);
$comment = test_input($_POST["comment"]);
$gender = test_input($_POST["gender"]);
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<h2>PHP Form Validation Example</h2>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Name: <input type="text" name="name">
<br><br>
E-mail: <input type="text" name="email">
<br><br>
Website: <input type="text" name="website">
<br><br>
Comment: <textarea name="comment" rows="5" cols="40"></textarea>
<br><br>
Gender:
<input type="radio" name="gender" value="female">Female
<input type="radio" name="gender" value="male">Male
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
<?php
echo "<h2>Your Input:</h2>";
echo $name;
echo "<br>";
echo $email;
echo "<br>";
echo $website;
echo "<br>";
echo $comment;
echo "<br>";
echo $gender;
?>
</body>
</html>
You can submit the form without refreshing the page, but to my knowledge it is impossible without using a JavaScript/Ajax call to a PHP script on your server. The following example uses the jQuery JavaScript library.
HTML
<form method = 'post' action = '' id = 'theForm'>
...
</form>
JavaScript
$(function() {
$("#theForm").submit(function() {
var data = "a=5&b=6&c=7";
$.ajax({
url: "path/to/php/file.php",
data: data,
success: function(html) {
.. anything you want to do upon success here ..
alert(html); // alert the output from the PHP Script
}
});
return false;
});
});
Upon submission, the anonymous Javascript function will be called, which simply sends a request to your PHP file (which will need to be in a separate file, btw). The data above needs to be a URL-encoded query string that you want to send to the PHP file (basically all of the current values of the form fields). These will appear to your server-side PHP script in the $_GET super global. An example is below.
var data = "a=5&b=6&c=7";
If that is your data string, then the PHP script will see this as:
echo($_GET['a']); // 5
echo($_GET['b']); // 6
echo($_GET['c']); // 7
You, however, will need to construct the data from the form fields as they exist for your form, such as:
var data = "user=" + $("#user").val();
(You will need to tag each form field with an 'id', the above id is 'user'.)
After the PHP script runs, the success function is called, and any and all output produced by the PHP script will be stored in the variable html.
...
success: function(html) {
alert(html);
}
...
This is the better way that I use to create submit without loading in a form.
You can use some CSS to stylise the iframe the way you want.
A php result will be loaded into the iframe.
<form method="post" action="test.php" target="view">
<input type="text" name="anyname" palceholder="Enter your name"/>
<input type="submit" name="submit" value="submit"/>
</form>
<iframe name="view" frameborder="0" style="width:100%">
</iframe>

Categories