jQuery prevent all forms from submitting at one time - php

I have a set of HTML form links which I am submitting upon click which have the id "ajaxForm"
for ($year = 2008; $year <= intval(date('Y')); $year++) {
if ($year == $currentYear)
continue;
echo '<div style="float:right;padding-right:20px;"><form name="year' . $year . 'Form1" id= "ajaxForm" action="/managementDashboard#visibleTab-5" method="post"><input name="getRecordsFor" type="hidden" value="' . $year . '"><a id="buttonRed" href="javascript:document.year' . $year . 'Form1.submit();">' . $year . '</a></form></div>' . chr(10);
}
However instead of default submission I use jQuery to post the data with this:
jQuery("form#ajaxForm").click(function(event) {
/* stop form from submitting normally */
event.preventDefault();
/* Send the data using post and put the results in a div */
jQuery.post( '/ajaxFunctions?mgmtDbrdPge=5', jQuery("#ajaxForm").serialize(),
function( data ) {
jQuery( "#visibleTab-5" ).empty().append( data );
}
);
});
The problem is that it is submitting ALL the forms instead of the individual one I click. Is there a way I can prevent this without having to write jQuery link for each individual form?
UPDATE - I accepted one of the answers because his method is legitimate but I realized what my issue was. Instead of jQuery("#ajaxForm").serialize(), I should have had it written as jQuery(this).serialize() to only call upon the data that was submitted with the click instead of ALL the forms with that id.

Looks like you are having more than one form with the same id of ajaxForm .
Make sure it is unique
If you know the id's of the Ajax forms in your page.. then you can do this
jQuery("form#ajaxForm ,form#myForm , form#myFormThird ").click(function(event) {
This will make sure the multiple elements are attached to the same event handler..
UPDATED CODE
If you do not know the id's then you can iterate using a for loop and attach the events..
$('form').each(function() {
$(this).click(function(event) {
// Your Function
}
});
Also make sure you use .on() to attach your events .. Instead of just the click so that the events are delegated..
jQuery("form#ajaxForm").on('click',function(event) {

Related

Update form with ajax

I have list of table which displays users information. There will be an amend link at the top. I need to update the form through Ajax rather than moving on to another page to update it.
This is my code.
<?php while ($row = mysql_fetch_assoc($displayer)){
echo("<tr><td>First Name</td><td>" . $row['first_name'] . "</td> </tr>");
echo("<tr><td>Last Name</td><td>" . $row['last_name'] . "</td> </tr>");
echo("<tr><td>Email</td><td>" . $row['email'] . "</td> </tr>");
echo("<tr><td>Country</td><td>" . $row['country'] . "</td> </tr>");
echo "<a class='page' href='amend.php?id=" .urlencode($row['users_id']) . "&firstname=" .urlencode($row['first_name']) . "&lastname=".urlencode($row['last_name']) ."'>Amend Record</a></td></tr>";
?>
Could any one tell me how to update the form using Ajax on the same page itself.
much details go into these that would require a very lengthy answer...nonetheless I am going to stress some important starting points.
First you need a JS file with a handler about the link.
When the link is clicked a ajax request must be made...there are various way to do that but I personally use jquery's $.ajax....inside the request you must gather the variables that reflect the values of the form inputs....then you send these values to a PHP script that makes validation and if this is successful update the corresponding values in the database.Inside the request you must also specify the URL that the this script resides.
This ajax request though is comprised of 2 important callbacks...error and success...in them you must write code that will deal with the situation if the request succeeds or not....for example you update he values in form when you are certain that this has indeed happen in the database and you can a make check for that in the PHP script...whatever values the PHP script echoes back must be done with json_encode...and you can access these values with the data argument of the success callback.AS I said there is an error callback also..this is triggered by various causes...it the URL is wrong or JSON is not returned from the server.
These above are just starting points...I am laying out a general approach.
/* AJAX using jQuery */
// attach event to your <a> upon click
$(document).on('click','a.page', function(e) {
e.preventDefault()
var sURL = $(this).attr("href"); // url to call for amend
update( sURL ) // call the function update
});
// update() function that is called after clicking anchor tag
function update( _url )
{
$.ajax({
method: 'POST',
url: _url,
success: function() {
alert("Amend Success)";
},
error: function( c ) {
alert("Internal server error. Check your browser console");
console.log( c.responseText )
}
})
}
NOTE: Put this before </body> tag

Ajax visit link without actually visiting link

I've got a basic like button concept on my site that visits url.tld?action=love and adds +1 to the link's database column.
It's a hassle redirecting to another page all the time though. Is it possible to click the button, and send a request to the URL without actually redirecting to a new URL? Also maybe refresh the button afterwards only so that the count updates?
For a general idea of what my download button is this is in the header:
<?php require_once('phpcount.php'); ?>
<p class="hidden"><?php
$time = time();
for($i = 0; $i < 1; $i++)
{
PHPCount::AddHit("$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]", "127.0.0.1");
}
echo (time() - $time);
/*echo "PAGE1 NON: " . PHPCount::GetHits("page1") . "\nPAGE1 UNIQUE: " . PHPCount::GetHits("page1", true);
echo "\n\n" . PHPCount::GetHits("page2");
$ntot = PHPCount::GetTotalHits();
$utot = PHPcount::GetTotalHits(true);
echo "###$ntot!!!!$utot";*/?></p>
And this is an example of my "love" button.
Love <span class="count">'. PHPCount::GetHits("$package_get?action=love", true).'</span>
The reason I used this method is because people create pages, and I wanted the like button to work out of the box. When their page is first visited it adds their url to the database, and begins tallying unique hits.
This is basically adding a new link column called downloadlink?action=love, and tallying unique clicks.
use the following code. assgin id="btn_my_love" to that button and add this code to you page
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
//assign url to a variable
var my_url = <?php echo "https://alt.epicmc.us/download.php?link='.strip_tags($package_get).'?action=love"; ?>;
$(function(){
$("#btn_my_love").click(function(){
$.ajax({
url:my_url,
type:'GET',
success:function(data){
//comment the following result after testing
alert("Page visited");
},
error: function (request, status, error) {
alert(request.responseText);
}
});
//prevent button default action that is redirecting
return false;
});
});
</script>
Yes, it is possible. I am assuming you know what ajax is and how to use it, if not I am not going to give you the code because some simple reading on ajax as suggested by #Black0ut will show you how. But the basic steps are as follows:
Send ajax request to a PHP script that will update +1 vote to the database
In the PHP script, add +1 to the database and return some data to the ajax, maybe the new number of votes
Parse the return data in your JavaScript and update the button accordingly

php how to handle hyperlink like a POST instead of GET?

I will have a query that return a set of results, and these results will be in hyperlink form as shown below:
echo "<td><a href='abc.php?cif=" . $row['cif'] . "'>{$row['cif']}</td>";
Now user get to click on this hyperlink and get routed to abc.php?cif=$cif..
My question is, is it possible to only show abc.php to user, just like a POST method, and $cif remains available at abc.php?
As #Flosculus said above, the "best" solution to simulate a post request is doing something like proposed here: JavaScript post request like a form submit
However, despite it's surely a reliable solution, I'm wondering you just don't use sessions instead, something like:
From the page where you set the cif variable:
session_start();
$_SESSION['cif'] = $row['cif'];
In abc.php:
session_start();
if (isset($_SESSION['cif'])) {
// Do what you need
}
EDIT::
Another (possible) solution is setting an hidden input and silently submit a form when you click on an anchor, like this:
From your example, instead of:
echo "<td><a href='abc.php?cif=" . $row['cif'] . "'>{$row['cif']}</td>";
You do this:
When you print all the entries, please add this first (from PHP):
<?php
echo <<<HEADER
<form action="abc.php" method="post" id="submitAble">
<input type="hidden" name="cif" id="cif" value="{$row['cif']}">
<table>
HEADER;
// Get data from your query.. Here is an example:
while ($row = mysli_fetch_assoc($query)) {
echo <<<ENTRY
<tr>
<td>{$row['cif']}</td>
</tr>
ENTRY;
}
echo "</table> <!-- \table collapse --></form> <!-- \form collapse -->";
?>
Then, if you're using jQuery (thing that I'm recommending), simply add an event listener in javascript, like this:
$('.cifSetter').on('click', function(e) {
e.preventDefault();
$('#cif').val($(this).data('cif'));
$('#submitAble').submit();
});
If you don't have jQuery, use this instead:
var cifSetter = document.getElementsByClassName('cifSetter');
for (var i = 0; i < cifSetter.length; i++) {
cifSetter[i].addEventListener('click', function(e) {
e.preventDefault();
var cif = document.getElementById('cif');
cif.value = this.dataset.cif;
document.getElementById('submitAble').submit();
});
}
In both ways, whenever an anchor gets clicked, it will prevent its standard behavior (redirecting) and will instead set the value of an hidden field to the value of the CURRENT "cif" and submit the form with the desired value.
To retrieve the desired value from abc.php, just do this:
$cif = $_POST['cif'];
However, keep in mind that the hidden field is editable by the client (most persons won't be able to edit it, though), therefore you should also sanitize your data when you retrieve it.
Sessions could do it but I'd recommend to just use $_POST. I dont get why you wouldn't want to use POST.

Pass Jquery Array to phpself

Ok guys. Im new to jquery, and I have a jquery array that I need to pass as a $_POST to the same file which is called index.php. When they click the button I need it to reload the index.php so I can get the POST. Now I'm sure I'm doing something wrong here cause this isn't working. But I'm certain that its something simple that I'm missing, or that I'm doing it all wrong and I mis-understood how this works. Any help is appreciated as I've been on this and trying to figure it out for the last 6 hours.
The index.php also contains the jquery scripts which are below, and the Post check which is
if (isset($_POST['data'])){
echo "ok, data was sent.<br>";
echo " Data is - " .$_POST['data'];
}
And the Button call
echo "<p><input type=\"submit\" class=\"input-button\" id=\"btn-add\" value=\"Add Squad\" /></p>";
Jquery
$(document).ready(function(){
// Get items
function getItems(exampleNr)
{
var count = 0;
var columns = [];
$(exampleNr + ' ul.sortable-list').each(function(){
count++;
columns.push($('#squad'+count).val(), $(this).sortable('toArray').join(','));
});
return columns.join('|');
}
$(document).on('click','#btn-get', function() {
$.post('index.php', {'data': getItems('#squad')}
});
});
You aren't doing anything with the response of your POST.
If you want it to submit like a form, you will need to create a form, attach a hidden input to it with your key-value pair, then submit that form. $.post alone is used for AJAX.

MySQL database update through AJAX and PHP

I have been going to stackoverflow for hints and tips in my programming journey but I have yet to register. . .till now.
My question is, is it possible to update/edit mysql data which I've inserted into an html/css table without having to go to another page?
for example:
when looking at the table in my browser, I wanted to edit my email information. I could just simply press the edit button then the email field becomes a text field right on the same page then I could just update it and hit save?
thanks!
EDIT(added my code):
$(button#edit).on('click', function() {
// get email inline to this edit button
var email = $(this).parent().siblings('td.email').html();
// change button from edit to save
$(this).attr('id', 'save-email').html('Save');
// change email display to input field
$(this).parent().siblings('td.email').html('<input type="text" id="user-email" value="'+email+'" />');
});
and this is the table I used which is formatted with php which also grabs data from my database:
echo ' <tr>';
echo ' <td>' . $row['name']. '</td>';
echo ' <td>' . $row['age']. '</td>';
echo ' <td>' . $row['sex']. '</td>';
echo ' <td>' . $row['email']. '</td>';
echo ' <td>' . $row['contact_no']. '</td>';
echo ' <td>' . $row['school_name']. '</td>';
echo ' <td>
<button id = "edit">EDIT</button>';
nothing happens,your help is greatly appreciated!
Yes, it is possible. Here are a few hints:
Use jQuery to listen to a click-event on the button and insert the text-field.
On Submit, use jQuery to send an ajax-request to a different php-file (like save.php).
Inside this file, you can do any mysql-queries you would normally do.
Again through jQuery, display the result of the queries to the user.
Yes. It's possible. Make a hidden div tag in your html code.
By means of ajax when you press button that div tag will be filled up by textbox / text.
Go through some tutorials related to ajax.
Sharing you an idea on how it works
JS script:
$('button#update').click(function(){
$.ajax({
url : 'yourpagehere',
data : {
id : '1' // send sample data to url
},
type: json,
sucess: function(response){
//Your script
});
});
});
PHP:
function yourpagehere(){
$id = $_POST['id']
$result = updateUserInfo($id); //Your script updating info in your database
json_encode($result); //Your response
}
Then you use firebug and check the console log on what you're ajax returned.
Yes, It is possible using AJAX.
AJAX is very powerful jQuery tool which is used to make asynchronous javascript calls which means you can submit data to another page without page loading.
As well as you can fetch data and fill dynamically in your page using AJAX without reload/load page.
You can find many tutorial and examples of AJAX.

Categories