Hi I have a JQuery problem with dynamic checkboxes and I don't know what I'm missing, if some one could help I appreciate here is my code
$('input[name="id_especieganado[]"]').each(function(e){
//$('[name="id_especieganado[]"]').click(function() {
var $this = $(this);
var id_jurisdiccion = new Array();
var jurisdicciones = "";
//id_jurisdiccion = $("#id_jurisdiccion[]");
var i = 0;
$(this).bind('click',function(){
//$('input[name="id_especieganado[]"]').each(function(){
if($(this).is(':checked'))
{
id_jurisdiccion.push($(this).val());
jurisdicciones += "id_jurisdiccion[]="+$(this).val()+"&";
$("#buscarrfc").val("Hola");
}
})
//if($("#id_jurisdiccion[]").attr("checked")==true)
//alert($("input[name='id_jurisdiccion[]']").val());
$.ajax({
url:"funciones_jquery2.php",
type: "POST",
dataType: 'html',
data: jurisdicciones,
success: function(datos){
$("#listamunicipios").html(datos);
//alert(datos);
}
})
//})
});
The dynamic checkbox I write them from a database which is a Postgres DB and PHP
Here is the code embeded in a class
The checkboxes looks ok
private function especies_ganado()
{
$database = $this->conexion_db();
$resultado = pg_query($database, "SELECT *FROM especies_ganado;");
echo "<tr><td>";
while($row = pg_fetch_array($resultado))
{
echo "<input type=\"checkbox\" name=\"id_especieganado[]\" id=\"id_especieganado[]\" value=\"$row[id_especieganado]\"> $row[especie_ganado]<BR>";
}
echo "</td></tr>";
}
First of all, the $.ajax() call is in the .each() function body, so you are calling it for every checkbox (on page load), but I assume you want your data to be sent when the checkboxes are each clicked. Put them in the click handler.
Second, you have to collect every checkbox value in the click event handler, before sending the data.
// for every checkbox, add a click handler (no need for each anymore)
$('input[name="id_especieganado[]"]').bind('click',function() {
// create an object for post data
var post_data = {'id_jurisdiccion': new Array()};
// collect the values from checked checkboxes
$('input[name="id_especieganado[]"]:checked')).each(function() {
post_data['id_jurisdiccion'].push($(this).val());
});
// send the data
$.ajax({
url:"funciones_jquery2.php",
type: "POST",
dataType: 'html',
data: post_data,
success: function(datos) {
$("#listamunicipios").html(datos);
}
});
});
Related
I have done some reading and I think i need to use json for this. I have never used this before. I am trying to accomplish this, but in jQuery
$email_exist_check = mysqli_query($connect, "SELECT * FROM accounts WHERE email='$desired_email'") or die(mysql_error());
$email_exist = mysqli_num_rows($email_exist_check);
if ($email_exist == 0) {
//stop and make user write something else
} else {
//keep going
}
I am switching my website over from php to jQuery, which is also very new to me but seems so much better. Here is a piece of my jQuery. I am validating a form. The form works and submits, but now i want to see if the email exists in my database before submission. How would i do this?
if (email == "") {
$("#error5").css("display", "inline");
$("#email").focus();
return false;
}
// Im guessing the new code would go here
var dataString = $("#acc_form").serialize();
var action = $("#acc_form").attr('action');
$.ajax({
type: "POST",
url: action,
data: dataString,
success: window.location.assign("cashcheck_order.php")
});
This is a basic ajax call using jquery
var thing1; //thing 1 to use in js
var thing2; //thing 2 to use
var form = ("#acc_form"); //localize the form to a variable. you don't need to keep looking it up
var dataString = form.serialize();
var action = form.attr('action');
$.ajax({
url: action,
data: dataString,
type: "post",
success: function(data){
var responseData = $.parseJSON(data); //json native decoding if available, otherwise will do it with jquery
thing1 = responseData["thing1"];
thing2 = responseData["thing2"];
},
error: function(data){
console.log("error", data);
}
});
On the php side, to bring the vars in you use
$input1 = isset($_GET["name_of_input1"]) ? $_GET["name_of_input1"] : "";
if this is set, set this value, else set blank.
you can use $_POST, $_REQUEST if you prefer.
do not forget to sanitize your inputs.
Now to send it back to the js file
$dataToReturn = [
"thing1"=>"I'm thing 1",
"thing2"=>"I'm thing 2"
];
//sending back data
echo json_encode($dataToReturn);
This is my first day and first question here, hope you will forgive me if my question is very trivial for this platform.
I am trying to call ajax inside ajax, One ajax call is going to call one cotroller action in which it will insert a record in the database, The action for the 1st ajax call is
public function createAction(Request $request){
if ($request->isXmlHttpRequest()) {
$name = $request->get("gname");
$description = $request->get("desc");
$portfolio_id = $request->get("PID");
$portfolio = $this->getDoctrine()
->getRepository('MunichInnovationGroupPatentBundle:PmPortfolios')
->find($portfolio_id);
$portfolio_group = new PmPatentgroups();
$portfolio_group->setName($name);
$portfolio_group->setDescription($description);
$portfolio_group->setPortfolio($portfolio);
$portfolio_group->setOrder(1000000);
$portfolio_group->setIs_deleted(0);
$em = $this->getDoctrine()->getEntityManager();
$em->persist($portfolio_group);
$em->flush();
$msg = 'true';
}
echo $msg;
return new Response();
}
The 2nd ajax call is going to get the updated data that is inserted by the first ajax call, The action for this call is
public function getgroupsAction(Request $request){
if ($request->isXmlHttpRequest()) {
$id = $request->get("PID");
$em = $this->getDoctrine()->getEntityManager();
$portfolio_groups = $em->getRepository('MunichInnovationGroupPatentBundle:PmPatentgroups')
->getpatentgroups($id);
echo json_encode($portfolio_groups);
return new Response();
}
}
My JQuery is as follows
$.ajax({
type: 'POST',
url: url,
data: data,
success: function(data) {
if(data == "true") {
$("#new-group").fadeOut("fast", function(){
$(this).before("<strong>Success! Your Portfolio Group is created Successfully.</strong>");
setTimeout("$.fancybox.close()", 3000);
});
$.ajax({
type: 'POST',
url: getgroups,
data: data,
success: function(data)
{
var myArray = JSON.parse(data);
var options = $("#portfolio-groups");
for(var i = 0; i < myArray.length; i++)
{
options.append($("<option />").val(myArray[i].id).text(myArray[i].name));
}
}
});
}
}
});
I am calling the 2nd ajax inside the success of the 1st one to ensure that the first ajax is successfully completed, but the 2nd ajax call is not getting the updated data.
How can I ensure that the 2nd ajax will be called after the completion of the first one and I get the recently inserted data as well
Thanks
MY SOLUTION
Just using one ajax call
in the create action where an insertion is made , just after the insertion take all the groups for the portfolio, and return json_encode($portfolio_groups);
Inside the JQuery
$.ajax({
type: 'POST',
url: url,
data: data,
success: function(data) {
$("#new-group").fadeOut("fast", function(){
$(this).before("<strong>Success! Your Portfolio Group is created Successfully.</strong>");
setTimeout("$.fancybox.close()", 3000);
});
var myArray = JSON.parse(data);
var options = $("#portfolio-groups");
for(var i = 0; i < myArray.length; i++)
{
options.append($("<option />").val(myArray[i].id).text(myArray[i].name));
}
}
});
I think the problem may be that you've got lots of variables names ´data´. In the second ajax call, the data sent will always be "true", but I suspect you would like to send something else. I would give them unique names to make things clearer and see what happens.
Just using one ajax call
in the create action where an insertion is made , just after the insertion take all the groups for the portfolio, and return json_encode($portfolio_groups);
Inside the JQuery
$.ajax({
type: 'POST',
url: url,
data: data,
success: function(data) {
$("#new-group").fadeOut("fast", function(){
$(this).before("<strong>Success! Your Portfolio Group is created Successfully.</strong>");
setTimeout("$.fancybox.close()", 3000);
});
var myArray = JSON.parse(data);
var options = $("#portfolio-groups");
for(var i = 0; i < myArray.length; i++)
{
options.append($("<option />").val(myArray[i].id).text(myArray[i].name));
}
}
});
Ajax in side the success method of the first Ajax, as you did, should ensure you the second Ajax is called after the first one. The success method is triggered ONLY after results have returned.
For a test add console.log() inside the first Ajax req just before you call the second one. and another console.log() inside the second Ajax success method.
try to put a console.log on the first success->data variable and see what you get. If you have an error I will cause the second request to fail.
I've been trying different options for over a week now and nothing seems to work. What makes this slightly more complicated is that I have multiple forms on the page that all need to be tied to this same submit function. They all have different IDs.
The following is a simplified version of my jQuery:
$('form').on('submit', function(form){
var data = $(this).serialize();
$.ajax({
type: 'POST',
cache: false,
url: 'inc/process.php',
data: data,
success: function(){
// The following fires on first AND second submit
console.log("Updates have successfully been ajaxed");
}
});
return false;
});
I have also tried using $('form').submit() with the same results.
Relevant sections of process.php:
$query = 'UPDATE pop_contents
SET ';
$id = $_POST['content_id'];
/* to avoid including in MySQL query later */
unset($_POST['content_id']);
$length = count($_POST);
$count = 0;
foreach($_POST as $col => $value){
$value = trim($value);
$query .= $col."='".escapeString($value);
// don't add comma after last value to update
if(++$count != $length){ $query .= "', "; }
// add space before WHERE clause
else{ $query .= "' "; }
}
$query .= 'WHERE id='.$id;
$update_result = $mysqli->query($query);
After much hair pulling and swearing, I've solved the problem.
TinyMCE editor instances do not directly edit textareas, so in order to submit the form, I needed to first call tinyMCE.triggerSave() from the TinyMCE API. So, the working code looks like this:
$('form').on('submit', function(form){
// save TinyMCE instances before serialize
tinyMCE.triggerSave();
var data = $(this).serialize();
$.ajax({
type: 'POST',
cache: false,
url: 'inc/process.php',
data: data,
success: function(){
console.log("Updates have successfully been ajaxed");
}
});
return false;
});
I was confused when i pass the Ajax String data via tinyMce ..but it is not save to database with php...then i use the
tinyMCE.triggerSave();
event.preventDefault();
then fine.........
$("#save").click(function() {
tinyMCE.triggerSave();
event.preventDefault();
var data = $(this).serialize();
var position = $("#position").val();
var location = $("#job_location").val();
|
|
|
|
var end_date = $("#end_date").val();
var dataString = '&position='+ position + '&job_location=' + location + '&job_category=' + category + '&job_des=' + job_des +'&job_res='+ job_res + '&job_requ='+ job_requ + '&start_date='+ start_date + '&end_date='+ end_date;
alert(dataString);
$.ajax({
type: "POST",
url: "regis.php",
data: dataString,
success: function(data){
}
});
return false;
});
i believe the problem is that you don't prevent the default action of the form. try this
$('form').bind( 'submit', function(event) {
event.preventDefault(); // added
console.log("Binding"); // changed to console.log
$.ajax({
type: "POST",
url: "inc/process.php",
data: $(this).serialize(),
success: function() {
console.log("Your updates have successfully been added."); // changed to console.log
}
});
});
Another neat trick to go along with this is setting the progress state on the tinymce editor, giving you a very simple way to add a loading icon. This article in the TinyMCE docs explains how to do that.
Also from that article, using ed.setContent() will allow you to set the text showing in the editor. I used it to blank the editor, but only after a successful post.
My page consists of a list of records retrieved from a database and when you click on certain span elements it updates the database but at present this only works for the first record to be displayed.
(Basically changes a 0 to 1 and vice versa)
These are my two html elements on the page that are echoed out inside a loop:
Featured:<span class="featured-value">'.$featured.'</span>
Visible:<span class="visible-value">'.$visible.'</span>
Here is what I have:
$(document).ready(function() {
$('.featured-value').click(function() {
var id = $('.id-value').text();
var featured = $('.featured-value').text();
$('.featured-value').fadeOut('slow');
$.ajax({
type: "POST",
url: "process.php",
data: "id="+id+"&featured="+featured,
success: function(data) {
$('.featured-value').html(data);
$('.featured-value').fadeIn('slow');
}
});
return false;
});
// same function for a different span
$('.visible-value').click(function() {
var id = $('.id-value').text();
var visible = $('.visible-value').text();
$('.visible-value').fadeOut('slow');
$.ajax({
type: "POST",
url: "process.php",
data: "id="+id+"&visible="+visible,
success: function(data) {
$('.visible-value').html(data);
$('.visible-value').fadeIn('slow');
}
});
return false;
});
});
It was working fine with one using id attributes but now I'm using class the fadeIn part of the success query isn't working but I'm hoping the .each will fix this.
UPDATE
The full loop is as follows:
while ($event = $db->get_row($events, $type = 'MYSQL_ASSOC'))
{
// open event class
echo '<div class="event">';
echo '<div class="id"><span class="row">Event ID:</span><span class="id-value"> '.$id.'</span></div>';
echo '<div class="featured"><span class="row">Featured: </span><span class="featured-value">'.$featured.'</span></div>';
echo '<div class="visible"><span class="row">Visible: </span><span class="visible-value">'.$visible.'</span></div>';
echo '</div>';
}
Cymen is right about the id selector causing you trouble. Also, I decided to refactor that for you. Might need some tweaks, but doesn't everything?
function postAndFade($node, post_key) {
var id = $node.parents('.id').find('.id-value').text();
var post_val = $node.text();
$node.fadeOut('slow');
$.ajax({
type: "POST",
url: "process.php",
data: "id="+id+"&"+post_key+"="+post_val,
success: function(data) {
$node.html(data);
$node.fadeIn('slow');
}
});
return false;
}
$('.featured-value').click(function() { return postAndFade($(this), 'featured'); });
$('.visible-value').click(function() { return postAndFade($(this), 'visible'); });
The click function is getting the same id and value on each click because you've bound it to the class. Instead, you can take advantage of event.target assuming these values are on the item being clicked. If not, you need to use event.target and navigate to the items within the row.
$('.featured-value').click(function(event) {
var $target = $(event.target);
var id = $target.attr('id');
var featured = $target.text();
$target.fadeOut('slow');
$.ajax({
type: "POST",
url: "process.php",
data: "id="+id+"&featured="+featured,
success: function(data) {
$target.html(data).fadeIn('slow');
}
});
return false;
});
So something like that but it likely won't work as it needs to be customized to your HTML.
At the moment i have this piece of javascript code:
//Display custom confirm box and delete multiple message
$(document).ready(function () {
$(".delete_button-multiple").click(function () {
//Get message id as variable
var id = $(this).attr("id");
var dataString = 'id=' + id;
var parent = $(this).parent();
//Display custom Confirm box
jConfirm('Are you sure you want to delete this message?', '', function (r) {
if (r == true) { //initiate delete message if agreed
$.ajax({
type: "POST",
url: "delete-mail_ajax.php",
data: dataString,
cache: false,
success: function () {
window.location = "mail_inbox.php";
}
});
return false;
}
});
});
});
delete-mail_ajax.php:
if($_POST['id'])
{
$id=$_POST['id'];
$id = mysql_escape_String($id);
$sql = "delete FROM mail WHERE mail_id='$id'";
mysql_query( $sql);
}
This is a working code for deleting only one mail item.
I wrote the following code to delete multiple messages from checkboxes:
//Multiple delete mail
if(!empty($_POST['message'])){
$list_mail = $_POST['message'];
foreach ($list_mail as $messageID){
$sql = "delete FROM mail WHERE mail_id='$messageID'";
mysql_query($sql);
//deletion complete, refresh the page
header("Location: mail_inbox.php");
}
}//end delete multiple
The difficulty i'm having is changing the working code above to incorporate the multiple selection, and deletion, of selected mails.
Any help on this issue would be appreciated
-Callum
Assuming you're using checkboxes, your code would look something like:
var messages = new Array();
$("input[name='mail_items[]']:checked").each(function() {
messages.push($(this).val());
});
$.ajax({
type: "POST",
url: "delete-mail_ajax.php",
data: { message: messages } //jQuery should translate this to an array that PHP should understand
cache: false,
...
});
You may need to json_decode the input to the $_POST['message'] variable, but I'd do a var_dump() on the stuff first just to make sure what PHP is doing in the background. Can't check at the moment, sorry.
I guess you have trouble submitting the form via Ajax? There is a neat plugin that does that for you: http://jquery.malsup.com/form/