i have old code, that has jquery v1.9.
now for some new edit, i need to submit form without refreshing page using ajax. but it dose not work.
and when i change version of jquery, old script dose not work.
my code is here:
days.php:
<script>
$(document).ready(function(){
$('#formSubmit').click(function(){
$.post("day2.php",
{name: $('#name').val()},
function(data){
$('#response').html(data);}
);});});
</script>
<div>
<input type="text" id="name">
<button id="formSubmit">send</button>
<textarea id="response"></textarea>
</div>
and day2.php:
$name = $_POST['name'];
echo "response: " +$name;
i dont know where is problem!
try:
echo "response: " . $name;
instead of:
echo "response: " +$name;
Actual problem is in second file where in
echo "response: " +$name;
you have used + as string concatenation operator instead of '.'
so actual code is like this
echo "response: " .$name;
Related
I have this block of HTML:
<div class="box-body" id="mcontent">
<?php
if (isset($_POST["id"])){
$id = $_POST["id"];
$query=mysqli_query($con,"select complain from tbcomplains where cid = '$id';");
if (mysqli_num_rows($query) > 0){
while($row=mysqli_fetch_assoc($query)){
echo $row["complain"];
}
}
}
echo "<br /> <p />";
echo "<p> Copy this link and paste in the mail for user's responses <br />";
echo "http://" . $_SERVER['HTTP_HOST']. $_SERVER['REQUEST_URI'];
?>
</div>
Which is replaced with this Ajax call, I include the the script below:
$('a').on('click', function(e){
var rex = e.target.id; //$('#this').data('id');
$('#mcontent').load("doload.php", {id:$('#' + rex ).data("id")});
});
The above code works perfectly. Issue is, how do I force this part of HTML to execute after the Jquery has finished.
I want this part of the PHP/HTML to execute:
echo "<br /> <p />";
echo "<p> Copy this link and paste in the mail for user's responses <br />";
echo "http://" . $_SERVER['HTTP_HOST']. $_SERVER['REQUEST_URI'];
Thank you in anticipation.
Knowing the fact that Javascript is a client-side language, you won't be able to "force" PHP to wait for an AJAX response.
The only possibility to modify your existing DOM after the AJAX call would be to use javascript when the query has responded.
Sorry for the overly complicated title, not sure how else to describe it. So, here is what I have.
I am dynamically creating div's for each of a databases row content to act as a frame work for a gui. That part works. It generates a new div and properly displays it for each row of the db and propagates the requested data. When you click on the generated gui it sends the data to another page for processing which is displayed in another div. This all works. What I am having trouble with is on the page which receives the send form data from the gui. It either displays the entirety of the db's contents from the requested or if I add a where to the select statement the fetch request doesn't seem to fire off at all.
<?php
$con=mysqli_connect("localhost","base","password","util");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "SELECT * FROM recipes";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result)) {
echo"
<script>
$(document).ready(function() {//start document ready
$('#front').click(function (e){
e.preventDefault();
$.ajax({
type: 'POST',
url: 'http://localhost/pages/receivingpage.php',
data: $(\"f2\").serialize(),
success: function(d){
$(\"#content-disp\").html(d);
}
});
});
});//end document ready
</script>
<div id=\"covera\">
<div id=\"holder\" class=\"holder\">
<div id=\"disp\" class=\"disp\">
<div class=\"click diagonal panel\">
<div id=\"front\" class=\"front\">
<form id=\"" . $row['recipe'] ."\" name=\"f2\">
<input type=\"hidden\" name=\"recipe\" value=\"" . $row['recipe'] ."\">
<h2>" . $row['recipe'] ."<br></h2>
</form>
</div>
<div class=\"back\">
<div class=\"pad\">
<h2>" . $row['recipe'] ."</h2>
<p>" . $row['id'] ."</p>
<p>Number of Servings " . $row['servings'] ."</p>
</div>
</div>
</div></div></div></div>";
}
mysqli_close($con);
?>
Here is the code for the receiving page. The gui code is on the main page and the receiving page is located in a div within the main page but within no other div.
If I add a where to the select statement the fetch request doesn't seem to fire off at all. The echo 2 will display but the requested result wont.
$r = $_POST["f2"];
$sql = "SELECT * FROM recipes WHERE recipe ='".$r."'";
$result = mysqli_query($con,$sql);
echo " 2 ";
while ($row = mysqli_fetch_array($result)) {
echo " " . $row['recipe'] ." ";
}
mysqli_close($con);
?>
You are closing your mysqli_connect() in the while loop, try moving the line mysqli_close($con); after the while loop in the second php script.
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
Hi i wannna get variable $_POST by link to self pages. Example :
<?PHP
$var = 'PIG';
echo "<a href='test.php?var=$var'>link</a>";
if (isset($_POST['var']))
{
echo $_POST['var']);
}
?>
it links to own pages. (test.php)
It not works, who can help me please. Thanks
A link cannot POST data, only GET.
In contrast to the GET request method where only a URL and headers are
sent to the server, POST requests also include a message body. This
allows for arbitrary length data of any type to be sent to the server.
Basically, a POST requires two requests, 1) the server receives the "normal" request, with an extra header value indicating that more data needs to be sent. At that point, the server sends an acknowledge and 2) the client sends the POST body. This behavior cannot be achieved only with a link.
However, there are solutions to this and I have seen some technique, among others, outputting a form with an autosubmit, something like
<form name="frm" method="post" action="http://your.domain.com/path/to/page.php?param1=1¶m2=2">
<input type="hidden" name="foo" value="bar" />
</form>
<script type="text/javascript">
document.forms["frm"].submit();
</script>
which would result into calling page.php with these arguments
$_GET = array('param1' => '1', 'param2' => '2');
$_POST = array('foo' => 'bar');
Note that this is a simple "redirect" method, but you can create <a> elements to actually trigger some hidden form like that instead of using the standard link. (untested code)
A simple link
<script type="text/javascript">
function dopost(url, params) {
var pe = '';
for (var param : params) {
pe += '<input type="hidden" name="'+param+'" value="'+params[param]+'" />';
}
var frmName = "frm" + new Date().getTime();
var form = '<form name="'+frmName+'" method="post" action="'+url'">'+pe+'</form>';
var wrapper = document.createElement("div");
wrapper.innerHTML = form;
document.body.appendChild(wrapper);
document.forms[frmName].submit();
}
</script>
This is probably what you need, actually.
Items in the query string are available via $_GET, not $_POST, since they are not actually POSTed. If you want to POST then you must either use a form with a method of post, or you must perform a XHR as POST.
Unfortunately, you really can't do that. If you need to use an anchor to submit a value, then you will need to access the variables through $_GET or $_REQUEST.
If it has to be a $_POST (if you are set in that design decision, because $_GET actually makes a lot more sense there), you can use a form and the style the submit button to make it look very much like a link. Put this code in a text editor and check it out.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<style type="text/css">
.button {border:none;background-color:#FFFFFF}
.button:hover{ color:blue; }
</style>
</head>
<body>
<form action="test.php">
<input type="hidden" name="var" value="<?php echo $val; ?>" />
This kinda looks like a link:
<input type="submit" value="link" class="button" />
</form>
</body>
</html>
If you have multiple links and you don't want to rewrite all of them, just add one fake form like this:
<form id="fakeForm" method="post">
<input type="hidden" name="post_key" value="post_value" />
</form>
and set up proper jquery:
$('a').click(function(event){
event.preventDefault();
$('#fakeForm').attr('action',$(this).attr('href')).submit();
});
In this case, when you click on any link, the landing page receives the post_value variable.
Note that if the link is clicked with other than left click (or js is disabled), the link works properly, but the value isn't passed!
This code below demonstrates T30's idea works.
My rationale for passing via $_POST is to prevent certain variables from being exposed in the url which is accomplished here. However, they would still be exposed via "view source".
<?php
/*
This demonstrates how to set $_POST from a link in .php without ajax based on the idea from http://stackoverflow.com/a/27621672/1827488. The rationale for doing so is to prevent certain variables ('userid') from being exposed in the url via $_GET. However, there does not seem to be a way to avoid those variables being exposed by 'view source'.
*/
echo "<!DOCTYPE html><html lang='en'><head><title>Test Data Link</title></head><body>";
// only one hidden form
echo "<form class='hiddenForm' method='post'>
<input class='hiddenFormUserid' type='hidden' name='userid'/>
</form>";
// as many links as you need
echo "<p><a class='hiddenFormLink' href='?following=1' data-userid=101>Following</a> • <a class='hiddenFormLink' href='?followers=1' data-userid=101>Followers</a></p>";
echo "<p><a class='hiddenFormLink' href='?following=1' data-userid=102>Following</a> • <a class='hiddenFormLink' href='?followers=1' data-userid=102>Followers</a></p>";
echo "<p><a class='hiddenFormLink' href='?following=1' data-userid=103>Following</a> • <a class='hiddenFormLink' href='?followers=1' data-userid=103>Followers</a></p>";
echo "<script src='https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js'></script>";
echo "<script type='text/javascript'>
console.log('jq');
$('.hiddenFormLink').click(function(e){
console.log('data-userid=' + $(this).attr('data-userid') + ', value=' + $('.hiddenFormUserid').val());
e.preventDefault();
$('.hiddenFormUserid')
.val($(this).attr('data-userid'));
$('.hiddenForm')
.attr('action',$(this).attr('href'))
.submit();
});
</script>";
if (isset($_GET["following"]) || isset($_GET["followers"])) {
if (isset($_GET["following"])) {
echo "followed by ";
} else {
echo "followers of ";
}
if (isset($_POST["userid"])) {
echo $_POST["userid"]."<br>";
} else {
echo "no post<br>";
}
} else {
echo "no get<br>";
}
echo "</body></html>";
$_POST["userid"] = "";
?>
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>