how to use jquery variable in php to insert into database - php

hello in the following code variable checked_num contains the integer value like 1,2,.
now i want this value in database using php code using mysql insert query..
the jquery code i have is:
<script type="text/javascript">
// function for counting check boxes
$(document).ready(function (){
$('.do').on('click',function(){
var checked_num =$('input[type="checkbox"]:checked').length;
});
});
now i want that variable "checked_num" is accessed in php code so i can insert this variable value into database

Have you readed the jQuery ajax/post/get ?

You can use ajax to update your database.
EG:
$('.do').on('click',function(){
var checked_num =$('input[type="checkbox"]:checked').length;
$.ajax({
type: 'POST',
url: 'yourpage.php', //this page inserts your data in database
data: {'checked_num': checked_num},
success: function(response){
//do whatever you want on success
},
error: function(xhr, status, errorThrown){
//handle ajax error
}
});
});
You can also use $.get() or $.post() instead of $.ajax().

You can use jQuery's $.post() method:
$('.do').on('click',function(){
var checked_num =$('input[type="checkbox"]:checked').length;
$.post('myPHPScript.php', { checked : checked_num }, function(data) {
/* data is the response you receive from the server. */
});
});
Here "checked" is the name of the post variable you're sending over. If you wanted to post a string named "myString" containing the text "Hello, world!", for example, you'd use { myString : "Hello, world!" }. This is an object, meaning multiple variables can be sent over by separating each with a comma.
In PHP you'd then retrieve this using $_POST:
<?php
$checked = $_POST['checked'];
?>
You'd probably want to encode this post data however before inserting it into your database.
As for how to insert the data into your database, check out PDO or mysqli.

You are using javascript to set a flag if one or more of the HTML checkboxs in your form are checked.
So you already have a <form> on the page.
When you submit the form you can access that information directly using PHP
All you have to remember is that checkboxes are only submitted back to the server PHP code if they ARE checked. So all you need to do is test for their existance.
if ( array_key_exists( 'checkbox_name', $_POST ) ) {
// this check box is checked
} else {
// this checkbox is not checked
}

Related

How to access jQuery variable in PHP and PHP variable in jQuery?

What I want to do:
I want to get a value from a select element
And then I want the specific record from the database on the basis of that value.
Finally, gets the record and displays it in an input field
This is my code:
You can't pass jQuery variable to PHP as such, however you can do same thing through ajax, where just pass selected value through ajax to PHP file and get returned result display in input field
<script>
$("#chooseRoles").change(function(e){
e.preventDefault();
$.ajax({
url: 'getValue.php',
data: 'selectedRole='+$(this).val(),
type: 'POST',
success: function(result){
$("#userRoles").val(result);
}
});
});
PHP CODE (getValue.php);
$roles = Roles::find($_POST['selectedRole']);
echo $capabilities = $roles->capabilities;

Posting data from ajax to php

Trying to send a post request from ajax to php.
I did many trial and errors based from the answers including making sure that the "type" is set to post, specifying "dataType", correct "url". I think I miss something important but I can't figure out what it is.
main.php
<script>
$(document).ready(function(){
$(".editContact").on("click", function(){
let dataID = $(this).attr("data-id");
console.log(dataID);
$.ajax({
type: 'POST',
url: 'functions/phonebook.php',
dataType: "text",
data:{data:dataID}
});
});
});
</script>
functions/phonebook.php
if(isset($_POST["data"])){
$res = array($data=>var_dump($_POST["data"]));
}
else{
$res ='null';
}
Then print the $res variable containing the dataID from ajax to my html element in main.php
<label class="m-label-floating">Contact name <?php echo $res; ?> </label>
The console.log in my main.php prints the data what I want to send in ajax but when I try to send the dataID to my phonebook.php, I get a null value.
Your problem is here:
$res = array($data=>var_dump($_POST["data"]));
You are using var_dump the wrong way.
From the docs:
This function displays structured information about one or more expressions that includes its type and value. Arrays and objects are explored recursively with values indented to show structure.
This function does not return any value, so, in your case, $data=>var_dump($_POST["data"]) will always be null.
What you need to is:
$res = array($data => $_POST["data"]);
If you are sending data to a different page altogether and need to use jquery / JS to do it, it might be simpler to send via window replace:
window.location.replace(...)
If you need to stay on the same page, you might want to include a success function in your ajax query, as this will return to the page you are calling from:
$.ajax({
type: 'POST',
url: 'functions/phonebook.php',
data:{data:dataID},
success: function (html) {
// do your HTML replace / add stuff here
},
});

jQuery Droppable - Make an Update Statement after an element gets dropped

I want to do an update statement in my database, after an element gets dropped on a jQuery UI droppable element.
$("#pictures th div").droppable({drop: function(ev, ui) {
alert('You filled this box with a picture');
var this_id = $(ui.draggable).attr("alt");
var draggableId = ui.draggable.attr("id");
}
I know how to get the information (see the code above) I need, but how can I put them now into the database ?
Thank you !
At this point, you can use jQuery's $.post() method to post to a PHP file you've written. In the $.post(), you can pass the ids you would like to have written to your database.
So something like this:
$.post("/save.php", { imageId: this_id, draggedId: draggableId }, function (data) {
alert("success!");
});
Post the variable values to other page lyk this:
$.ajax({
type: "POST",
url: "data.php",
data: "Cat=" + id + "&Wid=" + WID
});
and then on data.php page get the values lyk this:
$Cat=$_POST['Cat'];
$WID=$_POST['Wid'];
simply store them in database by using insert query,hope it will help you.

passing array value from jquery ajax to php function call

I have a 10 checkboxes, when i want to delete the appropriate record I use to select one or more checkbox. All the checkbox nams are array. I'm properly getting the values from the html page to jquery function. After that i pushed all the checked boxes into the array created in the jQuery function. But i'm not able to sent the values from this jquery function to the ajax php function. May be the way i'm trying will be wrong. Please check out my code below.
function BulkDelete()// jQuery Function
{
var Selected = new Array();
jQuery("input[name='chec[]']:checked").each(function(){
Selected.push(jQuery(this).val());
});
jQuery.ajax({
url:"<?php echo admin_url( 'admin-ajax.php' ); ?>",
type:"POST",
data:"action=doctor_management_add_dept&id="+ Selected +"&task=bulkdelete",
success:function(data){
jQuery("#msg").html("<div id='message'>"+data+"</div>");
}
});
}
function doctor_management_add_dept() // PHP function
{
if($_POST['task']=="bulkdelete") {
$ars[] = $_POST['id'];
echo count($ars);
}
}
I'm not getting any error. But the same time it's always returning 1.
You may want to serialize your form data, then pass a whole one to your PHP script. In this case, you'll be able to tell how many rows affected.

How to pick up JSON in PHP from Jeditable Script

I want to create a jeditable text area that posts the values entered in to a database and then returns the new value to the div that replaces the textarea. I found this on Stackoverflow that handles returning the new value to the div.
$(document).ready(function() {
$('.edit_area').editable(submitEdit, {
indicator : "Saving...",
tooltip : "Click to edit...",
type : "textarea",
submit : "OK",
cancel : "Cancel",
name : "Editable.FieldName",
id : "elementid",
});
function submitEdit(value, settings)
{
var edits = new Object();
var origvalue = this.revert;
var textbox = this;
var result = value;
edits[settings.name] = [value];
var returned = $.ajax({
url: "http://jimmymorris.co.uk/xmas/record_xmas_msg.php",
type: "POST",
data : edits,
dataType : "json",
complete : function (xhr, textStatus)
{
var response = $.secureEvalJSON(xhr.responseText);
if (response.Message != "")
{
alert(Message);
}
}
});
return(result);
}
});
My problems is I don't know what my POST vars are called so I can insert in to my db. Does it even return POST var to php or does it send php json and how do I know what that is called?
Please help, Cheers in advance.
What it sends to the server depends on what you supply to the "post" mamber of the $.ajax options paremeter.
If you pass a query string parementer data : "name=foo&surname=bar" The PHP script would recieve it in the $_POST variable and could be accessed by means of $_POST['name'] $_POST['surname']
However if you passed an object to the data parameter it would be changed to a query string i.e
data : {name : 'foo', surname : 'bar'},
JQuery.ajax would change it into a query string like the example above then It would be sent to the server, and the PHP script would also access it same as mentioned above.
P.S I highly recommend using some type of encoding when sending data to the server, encodeURIComponent(variable) and accordingly decode it in PHP by using urldecode.
You have the id posted which you can retrieve in the PHP page as $_POST['id']. The text is posted as value which you can retrieve in the PHP page as $_POST['value']. You can of course change the default names.

Categories