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/
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);
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);
}
});
});
In a JS file I am performing this function:
$(function() {
$(".button").click(function() {
//get the button's ID (which is equal to its row's report_id)
var emergency = this.id;
var button = this.attributes['name'].value;
var dataString = 'reportid=' + emergency;
alert(dataString);
if (button == "clockin") {
$.ajax({
type: "POST",
url: "/employeetimeclock.php",
data: dataString,
success: function() {
window.location = "/employeetimeclock.php";
}
});
} else if (button == "closereport") {
var r = confirm("Are you sure you want to close this report?\nThis action CANNOT be undone!");
if (r == true) {
$.ajax({
type: "POST",
url: "/closeemergencyreport.php",
data: dataString,
success: function() {
alert("Report Successfully Closed!");
window.location = "/closeemergencyreport.php";
},
error: function() {
alert("An error has occured, the report was not closed");
}
});
} else {
alert("Report was not closed.");
}
}
});
});
For the else if (to closeemergencyreport.php) the code in that php script is as follows:
<?php
require_once("models/config.php");
require_once("models/header.php");
require_once("models/dbconnect.php");
$reportid = $_POST['reportid'];
var_dump($_POST);
$sql = "UPDATE emergency_report SET report_closed = '1' WHERE report_id IN ( $reportid )";
//execute and test if succesful
$result = mysql_query($sql) or die(mysql_error());
if($result){
} else{
}
?>
I've done this same exact thing on 3 other pages and it works flawlessly however this is giving me trouble where on that php script the VAR_DUMP is saying it's returning an empty array. I've been reading and rereading the code for about an hour and a half now so I think i'm burnt out and need to have an outside view. Ive been all over the site and no one has had a solution that worked for me.
I know it's posting because fire bug is showing this on the form's page that the javascript is run on:
http://i.imgur.com/hItdVU1.png (sorry cant post images yet)
I have a screen from which a user can click on a button that brings up a popup
window. When the user clicks on save from the pop up window, the data is to be
save. It doesn't save anything, it is as if it does not see the database. This cannot be because I'm able to call data from it and display it.
jQuery on user page:
$(".up").click(function(){
var code = '1234';
var id = '24';
var who = 'someone';
$("#ui").html('loading...').show();
var url = "box.php";
$.post(url, {code: str, g:id, u:who} ,function(data) {
$("#ui").html(data).show();
});
});
php on popup bx:
//link db {...........}
// grab post
$click = $_POST[code];
$id = $_POST['g'];
$u = $_POST['u'];
// query php {........}
jQuery on popup box:
$("#process").click(function(){
var ID = '24';
var who = "someone";
var pla = "place";
$.ajax({
type: "POST",
url: "member.php", //contains function
data: 'user='+ who+ '&dept='+ pla+ '&sure='+ ID,
cache: false,
success: function(html) {
//do something
}
});
});
When I hit submit it doesn't post to the database. Maybe it's not passing the data to the member.php page.
Try to change:
$('#process').click(function()
{
...
});
to:
$(document).on('click','#process',function()
{
...
});
Edit:
BTW, you also need to change:
$click = $_POST[code];
to:
$click = $_POST['code'];
Maybe you should also take a look at jQuery's serialize() function, which will make it easier for you to get all your form values passed to your Ajax request.
For more information: http://api.jquery.com/serialize/
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.