I've coded some jquery & AJAX to call a PHP function I made that goes and gets some API data and brings it without refreshing the page. It appends, so you can have multiple searches without losing results.
What I need to do now is, I want to give the user the ability to change his mind on any one of the results. Maybe a little "X" at the end of each row. They click the "X" and that particular result is gone.
I've googled this, but I don't know what I'm looking for. Send me in the right direction, please?
Here's what I've got, so you know what I'm looking for:
<script src="http://code.jquery.com/jquery-1.5.js"></script>
<form method="post" action="ajax.php" id="searchForm">
<input type="text" name="isbn" placeholder="Search..." />
<input class="myaccount" id="doSearch" name="doSearch" type="submit" value="Search" />
</form>
<form name="buyback" method="post" action="isbn.php">
<table id="result" class="myaccount" border=0 cellspacing=5 cellpadding=4>
<tr><td>
<strong>ISBN:</strong>
</td><td>
<strong>Price:</strong>
</td>{if $userlevel == 5}<td>
<strong>Full FCB Price</strong>
</td>{/if}
</tr>
</table>
<input name="doBuy" type="submit" value="Buy"><br>
</form>
<script>
// attach a submit handler to the form
$("#searchForm").submit(function(event) {
// stop form from submitting normally
event.preventDefault();
// get some values from elements on the page:
var $form = $( this ),
term = $form.find( 'input[name="isbn"]' ).val(),
//term = "isbn",
url = $form.attr( 'action' );
$.post( url, { doSearch: "Search", isbn: term } ,
function( data ) {
var content = $( data );
$( "#result" ).append( content );
}
);
});
</script>
EDIT:
Yes, it just returns data in this format:
<tr><td>
{$isbn}
<INPUT TYPE=hidden NAME="buy_isbn" VALUE="{$isbn}">
</td><td>
{$userPrice}
<INPUT TYPE=hidden NAME="buy_price" VALUE="{$userPrice}">
</td></tr>
This really depends on what type of html is returned by the ajax call. But you could wire up a .live() event that removes whatever you need to get rid of.
$('.removeItem').live('click', function(e) {
// remove whatever you want. maybe the previous element?
$(this).closest('tr').remove();
});
// clicking that link will remove everything returned by the ajax.php call
var content = $(data);
content.append("<a class='removeItem'>X</a>");
$("#result").append(content);
or you could just add the anchor into the results that are generated by your ajax.php file.
EDIT:
You could just use the live event and modify your html like this:
<tr><td>
{$isbn}
<INPUT TYPE=hidden NAME="buy_isbn" VALUE="{$isbn}">
</td><td>
{$userPrice}
<INPUT TYPE=hidden NAME="buy_price" VALUE="{$userPrice}">
</td><td>
X
</td></tr>
Related
I have to one public_page.php page and one action.php page. If a user press submit button in public_page.php it sends information to action.php page by jquery post method. After successful processing the action.php page sends one tr data which should be replaced in table of public_page.php.
page: public_page.php
<div id="result"></div>
<table>
<thead><tr><th>S/N</th><th>Name</th><th>Address</th><th>Mobile</th><th>Action</th></tr></thead>
<tbody>
<tr id="1"><td>1</td><td>Mr.X</td><td>Japan</td><td>95684256</td><td><a class="edit" href="">Edit</a></td></tr>
<tr id="5"><td>1</td><td>Mr.Y</td><td>USA</td><td>123856641</td><td><a class="edit" href="">Edit</a></td></tr>
<tr id="8"><td>1</td><td>Mr.Z</td><td>UK</td><td>456862043</td><td><a class="edit" href="">Edit</a></td></tr>
</tbody>
</table>
jquery code (without $(document).ready line here):
$("body").on("click",".edit",function(event){
event.preventDefault();
var url = 'action.php';
var trid = $(this).closest('tr').attr('id');
$.post(url,
{
trid: trid,
},function(data){
$("#result").html(data).show();
});
});
after that the data of table row is come in '#result' div for editing. Let. tr id=5 (Mr.Y) is now for editing. So here it is comes in #result div as follows:
<div id="result">
<form id="5000">
Name:<input type="text" name="name" value="Mr.Y" /><br />
Address:<input type="text" name="adrs" value="USA" /><br />
Mobile:<input type="text" name="mobile" value="123856641" /><br />
Age:<input type="text" name="age" value="30" /><br />
<input type="submit" value="Submit" />
</form>
</div>
Now when user edit the information and press Submit, it sends the form information to action.php page by jquery. what is doing action.php page, after getting trid (which is actually id of database row that is to be edited) it process the data and produce callback data for public_page.php like this:
page: action.php
echo '<div class="success_msg">Data Updated Successfully!</div>';
echo '<div class="trid">5</div>';
echo '<div class="trcontent"><tr id="5"><td>1</td><td>Mr.Y</td><td>Tokeyo</td><td>123856641</td><td><a class="edit" href="">Edit</a></td></tr></div>';
and jquery code of public_page.php process the data like this:
var url = 'action.php';
var id = $(this).closest('form').attr('id');
var form_id = "#"+id ;
var data = $(form_id).serializeArray();
$.post(url,
data,function(callbackdata){
var msg = $(callbackdata).filter(".success_msg").html();
var trid = $(callbackdata).filter(".trid").html();
var trdata = $(callbackdata).filter(".trcontent").html();
$("#result").html(msg).show();
$('#'+trid).replaceWith(trdata);
});
as per query code, it should replace the tr which id is 5. But although it is replacing the tr but not in tabular format, it is replacing as text format like this:
page: public_page.php
<div id="result"></div>
<table>
<thead><tr><th>S/N</th><th>Name</th><th>Address</th><th>Mobile</th><th>Action</th></tr></thead>
<tbody>
<tr id="1"><td>1</td><td>Mr.X</td><td>Japan</td><td>95684256</td><td><a class="edit" href="">Edit</a></td></tr>
1Mr.YTokeyo123856641<a class="edit" href="">Edit</a>
<tr id="8"><td>1</td><td>Mr.Z</td><td>UK</td><td>456862043</td><td><a class="edit" href="">Edit</a></td></tr>
</tbody>
</table>
I think ...... is not inserting with replaced data.
How to resolve this issue, so that after replacing tr id="5" looks like a table row, not a string.
I'd suggest making an edit that will deal with this in a simpler way.
In your php code, instead of returning a div, what you should return is data.
<?php
$data = new stdClass();
$data->successMsg = 'Data Updated Successfully!';
$data->trid = 5;
$data->trContent = '<tr id="5"><td>1</td><td>Mr.Y</td><td>Tokeyo</td><td>123856641</td><td><a class="edit" href="">Edit</a></td></tr>';
echo json_encode($data);
Then in your JS code, you can go directly at the data instead of filtering it out of your HTML.
$.post(url,
data,
function(callbackdata){
var msg = callbackdata.successMsg;
var trid = callbackdata.trid;
var trdata = callbackdata.trContent;
$("#result").html(msg).show();
$('#'+trid).replaceWith(trdata);
},
'json');
The reason you're having problems is because of the way jQuery handles invalid HTML. <div><tr><td>1</td><td>2</td></tr></div> is not valid.
$('<div><tr><td>1</td><td>2</td></tr></div>').html() // outputs `12`
I am using Yii.
I have a php file which represents the view.
It has an input field <input type='text' id='client' /> which I want to update after I get a response from the server.
The response should be sent after I enter a value in other field and submit it to the server.
Can you refer me to an example on how to do this?
Thanks.
Or just php:
<form method="post" action="/">
<input type='text' name="client" id='client' value="<?php if(!empty($_POST['client'] )){ echo $_POST['client']; } ?>" />
<input type="submit">
</form>
Send a ajax request on form submit, receive the json object from server and assign it to your textbox. something like this
$('#submitButton').on('click', function(e){
e.preventdefault();
$.post( "ajax/index", function( data ) {
$( "#client" ).val( data.client );
});
});
I Have an requirement to pass form data to php using ajax and implement it in php to calculate the sum , division and other arithmetic methods I am a new to ajax calls trying to learn but getting many doubts....
It would be great help if some one helps me out with this
index.html
<script type="text/javascript">
$(document).ready(function(){
$("#submit_btn").click(function() {
$.ajax({
url: 'count.php',
data: data,
type: 'POST',
processData: false,
contentType: false,
success: function (data) {
alert('data');
}
})
});
</script>
</head>
<form name="contact" id="form" method="post" action="">
<label for="FNO">Enter First no:</label>
<input type="text" name="FNO" id="FNO" value="" />
label for="SNO">SNO:</label>
<input type="text" name="SNO" id="SNO" value="" />
<input type="submit" name="submit" class="button" id="submit_btn" value="Send" />
</form>
In count.php i want to implement
<?php
$FNO = ($_POST['FNO']);
$SNO=($_post['SNO']);
$output=$FNO+$SNO;
echo $output;
?>
(i want to display output in count.php page not in the first page index.html)
Thanks for your help in advance.
You can use a simple .post with AJAX. Take a look at the following code to be able to acheive this:
$('#form').submit(function() {
alert($(this).serialize()); // check to show that all form data is being submitted
$.post("count.php",$(this).serialize(),function(data){
alert(data); //check to show that the calculation was successful
});
return false; // return false to stop the page submitting. You could have the form action set to the same PHP page so if people dont have JS on they can still use the form
});
This sends all of your form variables to count.php in a serialized array. This code works if you want to display your results on the index.html.
I saw at the very bottom of your question that you want to show the count on count.php. Well you probably know that you can simply put count.php into your form action page and this wouldn't require AJAX. If you really want to use jQuery to submit your form you can do the following but you'll need to specify a value in the action field of your form:
$("#submit_btn").click(function() {
$("#form").submit();
});
I have modified your PHP code as you made some mistakes there. For the javscript code, i have written completely new code for you.
Index.html
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
</head>
<body>
<form name="contact" id="contactForm" method="post" action="count.php">
<label for="FNO">Enter First no:</label>
<input type="text" name="FNO" id="FNO" value="" />
<label for="SNO">SNO:</label>
<input type="text" name="SNO" id="SNO" value="" />
<input type="submit" name="submit" class="button" id="submit_btn" value="Send" />
</form>
<!-- The following div will use to display data from server -->
<div id="result"></div>
</body>
<script>
/* attach a submit handler to the form */
$("#contactForm").submit(function(event) {
/* stop form from submitting normally */
event.preventDefault();
/* get some values from elements on the page: */
var $form = $( this ),
//Get the first value
value1 = $form.find( 'input[name="SNO"]' ).val(),
//get second value
value2 = $form.find( 'input[name="FNO"]' ).val(),
//get the url. action="count.php"
url = $form.attr( 'action' );
/* Send the data using post */
var posting = $.post( url, { SNO: value1, FNO: value2 } );
/* Put the results in a div */
posting.done(function( data ) {
$( "#result" ).empty().append( data );
});
});
</script>
</html>
count.php
<?php
$FNO = $_POST['FNO'];
$SNO= $_POST['SNO'];
$output = $FNO + $SNO;
echo $output;
?>
There are a few things wrong with your code; from details to actual errors.
If we take a look at the Javascript then it just does not work. You use the variable data without ever setting it. You need to open the browser's Javascript console to see errors. Google it.
Also, the javascript is more complicated than is necessary. Ajax requests are kind-of special, whereas in this example you just need to set two POST variables. The jQuery.post() method will do that for you with less code:
<script type="text/javascript">
$(document).ready(function(){
$("#form").on("submit", function () {
$.post("/count.php", $(this).serialize(), function (data) {
alert(data);
}, "text");
return false;
});
});
</script>
As for the HTML, it is okay, but I would suggest that naming (i.e. name="") the input fields using actual and simple words, as opposed to abbreviations, will serve you better in the long run.
<form method="post" action="/count.php" id="form">
<label for="number1">Enter First no:</label>
<input type="number" name="number1" id="number1">
<label for="number2">Enter Second no:</label>
<input type="number" name="number2" id="number2">
<input type="submit" value="Calculate">
</form>
The PHP, as with the Javascript, just does not work. PHP, like most programming languages, are very picky about variables names. In other words, $_POST and $_post are not the same variable! In PHP you need to use $_POST to access POST variables.
Also, you should never trust data that you have no control over, which basically means anything that comes from the outside. Your PHP code, while it probably would not do much harm (aside from showing where the file is located on the file system, if errors are enabled), should sanitize and validate the POST variables. This can be done using the filter_input function.
<?php
$number1 = filter_input(INPUT_POST, 'number1', FILTER_SANITIZE_NUMBER_INT);
$number2 = filter_input(INPUT_POST, 'number2', FILTER_SANITIZE_NUMBER_INT);
if ( ! ctype_digit($number1) || ! ctype_digit($number2)) {
echo 'Error';
} else {
echo ($number1 + $number2);
}
Overall, I would say that you need to be more careful about how you write your code. Small errors, such as in your code, can cause everything to collapse. Figure out how to detect errors (in jQuery you need to use a console, in PHP you need to turn on error messages, and in HTML you need to use a validator).
You can do like below to pass form data in ajax call.
var formData = $('#client-form').serialize();
$.ajax({
url: 'www.xyz.com/index.php?' + formData,
type: 'POST',
data:{
},
success: function(data){},
error: function(data){},
})
I have a registration form that is currently in a popup modal window coded in jQuery. I have a PHP submit button on the bottom and I have added jQuery code that stops the button from submitting. This is because it will stop my modal window from closing when I submit the page. My issue now is that submitting the form would be impossible. Is there a way to submit my form over all this crowded pop-ups and jQuery? Say is it possible to use AJAX or jQuery to submit the form and allow my PHP to handle it.
Since I am writing in PHP, there is quite a bit of server side validation going on, so the point of this is to allow my viewers to fix their validation mistakes before the modal window closes.
Here is my jQuery, I didnt bother to mess with that anymore as it does what I need.
$(document).ready(function() {
$('a.modal-window').click(function() {
//Getting the variable's value from a link
var loginBox = $(this).attr('href');
$(loginBox).fadeIn(300);
var popMargTop = ($(loginBox).height() + 24) / 2;
var popMargLeft = ($(loginBox).width() + 24) / 2;
$(loginBox).css({
'margin-top' : -popMargTop,
'margin-left' : -popMargLeft
});
// Add the mask to body
$('body').append('<div id="mask"></div>');
$('#mask').fadeIn(300);
return false;
});
// When clicking on the button close or the mask layer the popup closed
$('a.close, #mask').live('click', function() {
$('#mask , .login-popup').fadeOut(300 , function() {
$('#mask').remove();
});
return false;
});
});
Here is the code I used to stop the form from submitting:
$(function () {
$(':submit').click(function (event) {
event.preventDefault();
// submit the form dynamically
});
});
and below is my form, it might not matter although its there for the viewing.
<form method="post" id="loginform" action="<?php echo $_SERVER['PHP_SELF']?>">
<table style="color: white;">
<tr><th style="float:left;">Register a new account with us.</th></tr>
<tr><td>Username</td><td><input type="text" name="txtUser"/></td></tr>
<tr><td>Password</td><td><input type="text" name="txtPass"/></td></tr>
<tr><td>Email</td><td><input type="text" name="txtEmail"/></td></tr>
<tr><td>Confirm Email</td><td><input type="text" name="txtEmail2"/></td></tr>
<tr><td>First Name</td><td><input type="text" name="txtFname"/></td></tr>
<tr><td>Last Name</td><td><input type="text" name="txtLname"/></td></tr>
<tr><td>Address</td><td><input type="text" name="txtAddress"/></td></tr>
<tr><td>City</td><td><input type="text" name="txtCity"/></td></tr>
<tr><td>Postal Code</td><td><input type="text" name="txtPostal"/></td></tr>
<tr><td>Birth Year</td><td><input type="text" name="txtBirth"/></td></tr>
<tr><td>Gender</td><td><input type="radio" id="radio-1-1" name="radicalSex" class="regular-radio" value="m" selected="true" /><label for="radio-1-1"></label> Male</td></tr>
<tr><td></td><td><input type="radio" id="radio-1-2" name="radicalSex" class="regular-radio" value="f"/><label for="radio-1-2"></label> Female</td></tr>
<tr><td colspan='2' style="color: #FF6600;float:left;font-size:70%;"><?php echo $Error;?></td></tr>
<tr><td colspan="2"><input type="submit" name="btnRegister" ID="btnBlueTemp" value="Submit Registration" /></td></tr>
<tr><td colspan='2' style="float:left; font-size:70%;">Address information is optional</td></tr>
</table>
</form>
Let me give you an example of how you can do that .
<html>
<head>
<title></title>
<script src="js/jquery-1.7.2.min.js" type="text/javascript"></script>
<script>
$(document).ready(function(){
function validate(name, addr){
if(name=="") {
alert('Name is Blank');
return false;
} else if(addr=="") {
alert('Address is Blank');
return false;
} else {
return true;
}
}
$("#save").click(function(event){
event.preventDefault();
var name = $("#name").val();
var addr = $("#addr").val();
if(validate(name,addr)){
$.ajax({
type:'POST',
data:'name='+name+'&addr='+addr,
url:'test2.php',
success:function(data) {
alert(data);
}
})
}
});
});
</script>
</head>
<body>
<form name="frm" method="POST" action="">
<input type="text" name="name" id="name" value=""/><br>
<input type="text" name="addr" id="addr" value="" /><br>
<input type="submit" name="save" id="save" value="Save"/>
</form>
</body>
</html>
Now in test2.php You can do your php codes
<?php
if(isset($_POST['name'])) {
echo $_POST['name'];
}
?>
Hope this gives you an Idea.
You need to serialize the form data before posting it to PHP.
<script type="text/javascript">
var frm = $('#loginform');
frm.submit(function () {
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
success: function (data) {
alert('submitted');
}
});
return false;//stop actual form submit
});
</script>
Then, submit your form via ajax
Jquery AJAX
On AJAX URL on which the request is sent, you can write necessary codes for validation and return accordingly. For eg. if some one the form element doesn't meet the validation, you can throw the flag accordingly as json value.
Its possible, why not.
Once you have done all the input validation at client side, just submit the form...
$("#loginform").submit();
Then you will have your server do the rest of the validation.
If you want to stay in the page and show the validation output from server, the. You should submit using Ajax.
It will send your form data to server, then you can do server validation, and output any errors. You will get this in your Ajax complete handler, which you can use to show error messages to user.
To stop the form from reloading the page you needn't call any prevent methods as a simple script request would do the trick.
For instance,
$('#loginForm').submit(function() {
// Do the relevant tasks needed here, form is already prevented from being submitted
});
Check out this demo for more information on what I am referring to
I've got a form that lets my user search. I'm using jQuery to append the search results lower in the page without reloading the page. So, I've got this:
isbn.php:
<form method="post" action="ajax.php" name="searchISBN" id="searchForm">
<input type="text" name="isbn" placeholder="Search..." />
<input class="myaccount" id="doSearch" name="doSearch" type="submit" value="Search" />
</form>
The problem is, I need that input text search field to clear when the user hits the Search button or hits enter. Both hitting enter and the Search button execute the search, so it must clear when either action happens.
But, I'm absolutely stumped.
Any help will be greatly appreciated!!
Edit:
I've tried what Treffynnon suggested. The problem there is, I've disabled the search button from actually loading ajax.php. So, when I use that code, it stops the page from staying on isbn.php and it loads ajax.php . This is the code that loads the search results.
isbn.php:
<script>
// attach a submit handler to the form
$("#searchForm").submit(function(event) {
// stop form from submitting normally
event.preventDefault();
// get some values from elements on the page:
var $form = $( this ),
term = $form.find( 'input[name="isbn"]' ).val(),
//term = "isbn",
url = $form.attr( 'action' );
$.post( url, { doSearch: "Search", isbn: term } ,
function( data ) {
var content = $( data );
$( "#result" ).append( content );
}
);
});
</script>
$('#searchForm').submit(function(){
// do search loading code here and then
$('input[name="isbn"]').val('');
});
Try this based on your update:
// attach a submit handler to the form
$("#searchForm").submit(function(event) {
// stop form from submitting normally
event.preventDefault();
// get some values from elements on the page:
var $form = $( this ),
$term_input = $form.find('input[name="isbn"]'),
term = $term_input.val(),
//term = "isbn",
url = $form.attr( 'action' );
$.post( url, { doSearch: "Search", isbn: term } ,
function( data ) {
var content = $( data );
$( "#result" ).append( content );
}
);
$term_input.val('');
});
Add a hidden variable to achieve this as follows:
<form method="post" action="ajax.php" name="searchISBN" id="searchForm">
<input type="text" name="isbn_holder" placeholder="Search..." />
<input type="hidden" name="isbn"/>
<input class="myaccount" id="doSearch" name="doSearch" type="submit" value="Search" />
</form>
$('#searchForm').submit(function(){
$('input[name="isbn"]').val($('input[name="isbn_holder"]').val());
$('input[name="isbn_holder"]').val('');
});