Trying to send a html form identified by id using jquery - php

I am echoing out a list of content from my database and have a star icon next to each item. I tried to make it so that when the user clicks the star it will find that content in my database and change the 'popular' value in that field (a 'like' button). I have been trying to do this by having each star wrapped in a tag and then making the id of each form 'formWithId'x ...... x being the id of the content that is being displayed.
Here it is in code:
echo "<form method = 'post' class ='formId".$row['id']."' id = 'likePostWithId".$row['id']."'>";
//all inputs are hidden and send the 'id' value of the content so the php file will know which field of the table to like in the mysql database
echo "<input type ='text' name = 'email' style = 'display: none;' value= '".$row['email']."' >
<input type ='text' name = 'id' style = 'display: none;' value= '".$row['id']."' >
//this is the star icon
<i class = 'ss-icon' id = '".$row['id']."'>⋆ </i>";
echo "</form>";
So, now what i need is to be able to send the form by using jquery validate.... but the problem i am having is that I have always used jquery validation (using the submit handler) to submit specific forms whose id's are predefined and dont change based on the id of the content sent from the database.
Here is my example that i am trying to
$(document).ready(function(){
$(".ss-icon").click(function(){
var id= $(this).attr('id');
$("#likePostWithId"+id).submit();
});
});
$(function(){
$(".ss-icon").click(function(){
//this doesn't work...
$("#likePostWithId").validate({
submitHandler:function(data){
//do stuff
}
)};
)};
see where $("#likePostWithId")... i dont know how to make it choose the one with the correct id (example $("#likePostWithId"+id)) would interpret as #likePostWithId6 or $likePostWithId7 where the number is the id of the mysql content
anyway i have no clue if this will be clear to any of you... I don't really know how to ask this question.. But basically i need to send an id (the id of the content from mysql) to php form without reloading page
any help is appreciated.
thanks

You may achieve this using jQuery's Ajax. Simply give each star icon a unique id (this id should have some relation with the MySQL data, like index key). Pass this argument (the id) using jQuery's Ajax function to a php script which takes the data (unique for each MySQL entry, like index) which changes it's popularity field entry. On success function, you may give some animation or color change to star icon informing that the data is successfully posted. just give it a try.

try this
$(function(){
$(".ss-icon").click(function(){
var id= $(this).attr('id');
$("#likePostWithId" + id ).validate({ <--- here
submitHandler:function(data){
$("#likePostWithId"+id).submit();
}
)};
)};
this however submits the form... you can use ajax to submit the form wihtout reloading

Maybe you can use $.post() to solve your problem. Then you don't have to mess around with forms:
$(document).ready(function(){
$(".ss-icon").click(function(){
$.post('yourPHPUrl', { contentID: $(this).attr('id') }, successFunction);
});
});
function successFunction(data) {
if (data.success) { //just a sample, you can give a JSON-Object back to the success function
$('#' + data.ID).css() ... // do something with the clicked star
}
}

Your code:
$(function(){
$(".ss-icon").click(function(){
//this doesn't work...
$("#likePostWithId").validate({
submitHandler:function(data){
//do stuff
}
)};
}); // <-- this was missing
)};
You were missing a set of brackets but you still shouldn't implement it like that. You are merely re-initializing the plugin on every click. (The plugin already has the click event handler built-in and it's captured automatically.)
.validate() must be called once within the DOM ready to initialize the plugin. As per documentation, the submitHandler callback function is "the right place to submit a form via Ajax after it validated."
$(function(){
$("#likePostWithId").validate({ // initialize plugin
// other options & rules,
submitHandler: function(form){
// do ajax
return false; // blocks form redirection since you already did ajax
}
)};
)};
Play with a demo: http://jsfiddle.net/XnfDc/

Related

Submit form without form

This might look as the dumb question, but I hope it's not.
I have a PHP file delete.php that will delete selected users (it is not ready yet, but I will write it after I finish my HTML model).
So, on my HTML model I have the following:
<li><button class="sexybutton">
<span><span><span class="add">Add</span></span></span>
</button></li>
This sexybutton is the button styling I've downloaded. So, how to make it post the selected user list to a PHP file without putting a <form> tag inside (it will brake all the structure otherwise and will not be valid)?
I could use jQuery (or JS), but I still do not know how to do this. If PHP would have something like "onclick" function :)
Thank you in advance.
You can send an ajax request without a form, like this :
$('.sexybutton').on('click', function() {
var users = $.map( $('li.users'), function(el) {
return $(el).text();
});
$.ajax({
url : 'delete.php',
data: users
});
});
just create the data you need, and send it ?
<form id="your_form">
<ul>
<li><button class="sexybutton" onclick="$('#your_form').submit();">
<span><span><span class="add">Add</span></span></span>
</button></li>
</ul>
</form>
explanation:
wrap your existing code with form element, give some unique id to your form (e.g. your_form) and then add attribute onclick to your button and fill it with some jquery syntax (or pure javascript if you wish):
$('#your_form').submit();
this will do the submit job.

How do I post to a new php page with jquery

I am trying to post the element information that jQuery pulls, when a user clicks on table cell, to a new page that will use that information (an id in this case) in a sql query. i.e., the user clicks a cell and the job he/she clicks has an id of 25, that is to be passed to my php page that queries the database for the job with that id and then populates the page with said information. The user can then alter the information from the query and submit it to update the database table. I have the id from the click function and a success alert tells me that the info was posted. The problem is that when the page is opened it states that the posted name index is undefined.
Here is my script to get the information:
<script>
$(document).ready(function()
{
$("table.jobs tbody td#job").click(function()
{
var $this = $(this);
var col = $this.text();
var LeftCellText = $this.prev().text();
if (col == '')
alert("Please pick another column");
else
$.ajax(
{
type:"POST",
url:"../php/jobUpdate.php",
data:"name=" + LeftCellText,
success: function()
{
window.location = "../php/jobUpdate.php";
}
});
});
});
</script>
and here is the simple php page it is sending to:
$name = $_POST['name'];
echo $name;
I am new to jQuery, and I cannot figure out why this is not working?
When you use ajax, the second page ../php/jobUpdate.php processes the data sent by the first page, and returns a value (or even a huge string of html, if you want).
The first page receives the new data in the ajax routine's success function and can then update the current page. The updating part happens in the success: function, so you're on the right track.
But in your success function, you are redirecting the user to the 2nd page -- after already being there and processing the data. Redirecting them is probably not what you want to do.
Try replacing this:
success: function()
{
window.location = "../php/jobUpdate.php";
}
with this:
success: function(data)
{
alert(data);
}
If you want to see how to update the first page with the data received via ajax, try adding an empty DIV to your html, like this:
<div id="somestuff"></div>
Then, in the success: function of the ajax routine, do this:
$('#somestuff').html(data);
(Note that the term "data" can be any name at all, it only needs to match the name used in the function param. For example:
success: function(whatzup) {
alert(whatzup);
}
From your comment to my previous post, it seems that you don't need ajax at all. You just need a form in your HTML:
<form id="MyForm" action="../php/jobUpdate.php" method="POST">
<input type="hidden" id="jobID" name="yourJobID">
</form>
Note that forms are invisible until you put something visible inside them.
You can have select controls (dropdowns) in there, or all form elements can be invisible by using hidden input fields (like the HTML just above), which you can populate using jQuery. Code to do that would look something like this:
<script>
$(document).ready(function() {
$("table.jobs tbody td#job").click(function() {
var $this = $(this);
var col = $this.text();
var LeftCellText = $this.prev().text();
//Set value of hidden field in form. This is how
//data will be passed to jobUpdate.php, via its `name` param
$('#jobID').val(LeftCellText);
if (col == '')
alert("Please pick another column");
else
$('#myForm').submit();
});
});
</script>
If you add more values to your form to send over to jobUpdate.php, just ensure that each element has a name, such as <input type="text" name="selectedJobType"> (this element, type="text", would be visible on screen).
In the jobUpdate.php file, you would get these values thus:
$SJT = $_POST['selectedJobType'];
$id = $_POST["yourJobID"];
//Use these vars in MySQL search, then display some HTML based on results
Note that the key referenced in the $_POST[] array (selectedJobType / yourJobID) is always identical to the name specified in the HTML tag. These names are case sensitive (and spelling counts, too).
Hope this isn't TMI, just wish to cover all the bases.
On your success function causing the window to reload will delete any of the variables passed in via .ajax.
What you can try is returning the data and use it in the existing page.
success: function(msg) {
$('#someDiv').append(msg);
}
The reason the index is not defined is because you are using a string in the data-argument, however, that is actually an array-like object. :)
data: { name: col }
that should be the line you need to change. Otherwise I have not seen any problems. Also if I can give you a little idea, I wouldn't use POST actually. In fact, I'd use GET. I can not confirm if that is saver or not, but using $_SERVER["HTTP_REFFERER"] you can check from where that request is coming to determine if you want to let it pass or not.
The way I would suggest is, that you sent the ID in a GET-request and have the PHP code return the data using json_decode(). Now in jQuery, you can use $.getJSON(url, function(data){}) - which is, for one, shorter and a bit faster.
Since you probably will crop the URL yourself here, make sure that you use a function like intVal() in JS to make sure you are sending an intenger instead of a malicious string :)

Submit JQuery array alongside PHP form data to PHP script

I'm dabbling in JQuery, and have run up against an issue I'm not quite able yet to figure out. Here is the context:
I have a HTML form, utilising MySQL & PHP, used to edit a CMS post. This post would have a list of attachments (eg. images for a gallery, or downloadable files). Using JQuery, the user can click on these list item elements and edit the details of each attachment in a revealed div (eg. delete image, add capton, etc).
Currently when the user opts to delete an attachment, I simply fade its opacity and provide a new option to the user to 'undo' the delete. Upon submission of the complete parent form (the CMS post), I want to gather all the attachments still marked for deletion, and submit their GUID's to the PHP script that is doing all the rest of the post updating for me.
Option A:
Is it possible to submit a JQuery array to a PHP script alongside the data being sent naturally to the action script by the form inputs?
Option B:
Is it possible to fill / empty a (hidden) form input array dynamically with JQuery, which could then be submitted naturally to the action script with everything else?
I am currently at the stage where I am filling a Javascript array with the necessary GUIDs, but now don't know what to do with it.
//populate deleted attachments array
$(document).ready(function() {
$('#post-editor').submit(function() {
var arrDeleted = [];
$('.deleted-att').each(function(){
arrDeleted.push({guid: $(this).attr("data-guid")});
});
//do something with array
});
});
JSON.stringify the arrDeleted and put them in a hidden field in the form, that will be submitted.
$('#post-editor').submit(function() {
var arrDeleted = [];
$('.deleted-att').each(function(){
arrDeleted.push({guid: $(this).attr("data-guid")});
});
$('#post-hidden').val(JSON.stringify(arrDeleted));
});
Somewhere in your html:
<form id="post-editor">
<input type="hidden" id="post-hidden" name="post-hidden" />
<!-- ... other fields ... -->
</form>
Then json_decode($_POST['post-hidden']) on the server to get the array.
create a hidden field in your form..put the arrDeleted value in your input through jquery
and post the form..use json_decode() to get the posted value...
<input type="hidden" id="hidden"/>
JQUERY
$(document).ready(function() {
$('#post-editor').submit(function() {
var arrDeleted = [];
$('.deleted-att').each(function(){
arrDeleted.push({guid: $(this).attr("data-guid")});
});
$('#hidden').val(JSON.stringify(arrDeleted));
});
});
The easiest to do what you want would be to add a hidden input field to your HTML form
Then in jQuery do something like this
$('form').submit(function() {
$('#hidden_id_field').val( arrDeleted.join(',') );
});
arrDeleted in this case being your array you've already setup. It would sent a comma separated list then in your PHP you split up the values and act as you want.
Usually I just do AJAX and send JSON to my app. But the above approach will work if you really want to go about it like that. And it has the advantage of not actually deleting anything on the server until you submit the form.
You may be looking to do this with a traditional form submit and refresh, but if you're willing to submit the request asynchronously, you can use jQuery to submit the form and serialize the array of deleted items:
var form = $('#post-editor');
form.submit(function() {
var arrDeleted = [];
$('.deleted-att').each(function(){
arrDeleted.push({ // The format $.serializeArray produces.
name: "deleted",
value: $(this).attr("data-guid")
});
});
var formData = form.serializeArray();
// Add values to existing form data
formData = formData.concat(arrDeleted);
$.ajax({
url: form.attr('action'),
data: formData
// Other ajax options
});
});
On the PHP side, referring to $_REQUEST['deleted'] will return an array of GUIDs.

How to delete record in HTML table using jQuery/Javascript/PHP

I'm currently working on records that is tabulated in HTML, records are from the database and on the end part of that table, i have some actions, EDIT DELETE SHOW, i've already done the edit, which is NOT the same as my DELETE, my DELETE action is done using ajax, but the problem is that i can't properly get the value of each button, which contains the ID from the database.
This is part of the table where the delete button is located:
<td width="61"><button id="delete" value="<?php echo "$arr[0]"; ?>">Delete</button></td>
These is the jQuery part
$("#delete").click(function(){
alert($("#delete").val()); <-- CAN"T GET THE CORRECT ID
//AJAX PART HERE
})
The problem is that i can't correctly get the value of the button which i pressed, how do i do this, any suggestions are greatly appreciated..
This is the whole view of the table,
Not tested, but I expect the issue is that you are trying to get the val() of all the matches for #delete, which is probably all of your delete buttons (I can not know without seeing your generated HTML).
You should actually use a class of delete and select with .delete rather than an id, as an id, according to the HTML specification should refer to a unique element.
$("#delete").click(function(){
// note the use of `this` to refer to clicked object, rather than all delete buttons
alert($(this).val());
//AJAX PART HERE
})
First, write delete method in server side, like delete.php, return status, like 'error' and 'success'
$("#delete").click(function(){
var id = $(this).attr('id');
//AJAX PART HERE
$.get('delete.php?id=xxx',function(status){
if (status == 'success') $(this).parent().remove();
}
})
Just use jQuery's 'this' to access the button within the function...
e.g.
replace
alert($("#delete").val()); <-- CAN"T GET THE CORRECT ID
with
alert($(this).val());
The value of the button is what's displayed on it as text, but that won't get you the table's id. Also, since there are several delete buttons, use a class instead of an id.
Change your html code to something like this, using a custom attribute called "db-id", through which you will find out which record to delete:
<input class="delete" db-id="<?=$db-id?>" value="Delete"/>
Then, your js code can be adjusted like this:
$(".delete").click(function(){
var dbid = $(this).attr('db-id');
$.ajax({
type: 'POST',
url: 'script-url/here.php'
data: 'id=' + dbid,
success: function(feedback){
if(success==true) $('tr[db-id="' + dbid + '"]').delete
}
}).error(){
alert('Something went horribly wrong!');
};
})
Note that in the success function you can even make the row with the data disappear using .delete()
Also note that any malicious user will be able to edit the button's db-id in the browser, so take all necessary precautions and validations in the php script!
Try this:
$("button[id=delete]").click(function(){
$(this).closest('tr').remove(); // Delete row
alert($(this).attr('value')); // ID
});
button[id=delete] - because you'll have many buttons with same ID, better use CSS Classes...
ok here is your solution:
1) insted of id="delete" use class. like this:
<td width="61"><button class="delete" value="<?php echo "$arr[0]"; ?>">Delete</button></td>
2) your jquery should be:
$(".delete").click(function(){
alert($(this).val()); <-- CAN"T GET THE CORRECT ID
//AJAX PART HERE
})
This should alert the propper id, I proposee to this mehoded for edit, and show actio....

jQuery: Radio button selection determens which div to display, with ”checked” attribute

I have a form with different options provided by radio buttons. I also have a script which displays different divs with different form inputs.
This script works fine, my problem is that I have a “previous” link where a user can go one step back and edit already entered data and that I can’t force the different options with the checked attribute to the radio button. It has to be clicked, which make sense because my script uses the .click event.
But how can I say something like: “If $_SESSION[‘unemployed’] == ‘yes’ then echo ‘checked’” and it shows the right option.
I hope I explained myself correctly otherwise fell free to ask.
Please see the code live here http://jsfiddle.net/GEFMX/1/ and my question is if one or more or the checkboxes default is "checked".
The Javascript I’m using looks like this:
<script type="text/javascript">
$(function() {
$("input[name$='step2_student']").click(function() {
var diffoptions = $(this).val();
$("div.studerende_janej").hide();
$("#studerende" + diffoptions).show();
});
$("input[name$='step2_otheredu']").click(function() {
var diffoptions = $(this).val();
$("div.othereducation_janej").hide();
$("#othereducation" + diffoptions).show();
});
$("input[name$='step2_haveeducation']").click(function() {
var diffoptions = $(this).val();
$("div.haveeducation_janej").hide();
$("#haveeducation" + diffoptions).show();
});
});
</script>
Sincere
- Mestika
You can add some code to your page load to trigger a 'click' for all radios that are checked. i.e. something like:
$(function() {
// .. bind your click events here
$('input[type="radio"]').each(function() {
if($(this).prop('checked')) $(this).click(); // trigger 'click' if checked
});
});
At the end of your document ready, add $("input[name~='step2_']:checked").click(). This will trigger the click event for already checked radio buttons, effectively displaying the divs.

Categories