Passing javascript variable to php without refreshing the page - javascript

I have a 5x5 grid of div boxes (25 of them) and I am using jQuery UI to register when I drop a item in it. It will receive the title of the box it was dropped in and the name of the item, that part works.
I want to pass the title and name to PHP without refreshing the page (because then the items will reset). I get a "success!" but it seems like it doesn't pass the data.
index.php
<script>
$(function() {
$( "li img" ).draggable({
snap: ".grid",
start: function (event, ui ) {
item = $(this).attr('title');
}
});
$( "li .grid" ).droppable({
drop: function( event, ui ) {
box = $(this).attr('title');
$.ajax({
type: "POST",
url: 'index.php',
data: { box : 'box' },
success: function(data){
alert("success!");
}
});
}
});
});
</script>
sessions.php
<?php
session_start();
if(isset($_POST['box']))
{
// store session data
$_SESSION['box'] = $_POST['box'];
}
//retrieve session data
echo $_SESSION[box];
?>
How do I pass the title and name to PHP without refreshing the page?

Try to change the url and your data from this:
url: 'index.php',
data: { box : 'box' }
to this:
url: 'sessions.php',
data: { box : box }

Given that you're doing this...
box = $(this).attr('title');
I assume you want to pass that variable to the server. However, you're just passing the literal string "box", not the variable box.
In your code, you've written this...
data: { box : 'box' },
which needs to be this, to pass the value in box:
data: { box : box },
As an aside, you've created a global variable box. Instead of box = $(this).attr('title');, you should use var box = $(this).attr('title'); to create a variable local to the function.

Related

Pick the value from a text box id to PHP

Iam getting a value to the text box id using AJAX which is working fine.
<input type='text' id='selectuser_id' />
Javascript
$( "#customers" ).autocomplete({
source: function( request, response ) {
var countrycode = '<?php echo $agencyid; ?>';
$.ajax({
url: "http://localhost:8000/core/country/fetch_customers.php",
type: 'post',
dataType: "json",
data: {
search: request.term
},
success: function( data ) {
response( data );
}
});
},
select: function (event, ui) {
$('#customers').val(ui.item.label); // display the selected text
$('#selectuser_id').val(ui.item.value); // save selected id to input
var customerid = $("#selectuser_id").val(); //equals $q6[$t2] exactly
return false;
}
});
Now how will i pick this value to my PHP
<?php echo $selectuser_id; ?>
I tried many ways but not getting the result. Can someone help me on this?
Since you don't show us where you hold the data of the input field i will give you an example.
Javascript side (since you are also using jQuery) you can get the value of the input field by id like:
let myValue = $( "#selectuser_id" ).val();
Then inside your ajax call you can include your data just like you did for the search:
data: {
search: request.term,
myValue: myValue
}
In your fetch_customers.php file you should be able to access your post data like:
$_POST['myValue'];

How to detect that my select form have been change by ajax success

I have two form input ( text and select form ).
The select form change by ajax success when user search the employee data.
Now, i want the other jquery function that can automatically detect when the select form have been change by ajax success and retrieve the new value of select form to use by other function to make new data in my input text.
my Search Employee Function
function search_personal_result(formObj, urlres, responseDIV, disable_data, modal_class,result_data)
{
disable_data=disable_data||false;
modal_class=modal_class||false;
result_data=result_data||false;
var loading = '<p>Loading ...</p>';
$.ajax({
url: site_url+'/'+urlres,
beforeSend: function(){
$(responseDIV).html(loading);
},
data: $(formObj).serialize(),
type: "post",
dataType: "html",
success: function(response){
//proceed data result here
if(result_data==false){
var obj = jQuery.parseJSON(response);
$.each(obj, function (index, value) {
if(result_data==false){
for(var j in value){
//My SELECT Form Changed here
$('#VCIDSBU').val('MY NEW VALUE');
}
}
});
}
},
error: function(){
alert("Terjadi kesalahan!");
},
});
}
If the user search the employee data using search_personal_result, my select form have been successfully changes.
Now that i need is, how to make the other jQuery function that can detect that my SELECT Form have been changed by search_personal_result
I have try using
$(function () {
$('#form_create_sp').on('change','SELECT#my_select_id',function(){
alert('it changes');
});
})
It can only detect when the user manually change the select form. but not working when the select form changed by search_personal_result
Thanks for all expert here
You could always do some sort of console.log("Success"); Function based on if it sent or not.

update session and refresh page with ajax/jquery

I need help with a script that according to 2 parameters updated me a $ _SESSION variable and then refresh the page. One of these parameters comes from a select and the other according to a select class "active".
Here's my code:
<div class="simple-drop-down">
<select id="select-order">
<option>Price</option>
<option>Category</option>
<option>A - Z</option>
</select>
And my jquery function like this:
function order_visual() {
var type_order = $('#loader-wrapper').val();
var arrow_order = $( "#select-arrow" ).hasClass( "active" );
$.ajax({
url: "visual.php?order="+type_order="&"+arrow_order,
type: "post",
data: {},
success: function(data){
location.reload();
}
});
});
And then the PHP is a simple script that manages the $_SESSION.

how can I make one button correspond to different clicked div html jquery php?

You can see my code below. I face a challenge that I don't know how to use one button to correspond different click. On the php, if I put the button inside the foreach loop, it will create a lot of button, that's not what I want. In the js, if I put the on.click button inside the foreach elements loop, it will also create a lot of on.click button, so I click one button, it will run many times depends on the number of label_name. I think about addClass, if I clicked the heart div, I use js to add a class, and then get the attr('id') inside button.on.(click), so I can differentiate them in my server php and mysql can request the correspond data. But the problem is that if a user click every div, then every div add classes, then problem again.
var current_page = 1;
var elements_body = {
"heart": "1",
"eye": "2",
"ear_nose_throat": "3",
"hand_foot_mouth": "4"
};
jQuery.each(elements_body, function (label_name, label_num) {
var disease_label = $('#' + label_name + '_d');
disease_label.on('click', function () {
var data = {
action: 'body_part_keyword', //wordpress loading url
postSearchNonce: MyAjaxSearch.postSearchNonce,
current_page: current_page,
label_name: label_name //this label_name will differentiate data that need to request from mysql in the action.php
};
$.ajax({
url: MyAjaxSearch.ajaxurl,
type: 'POST',
cache: false,
data: data,
success: function (data) {
disease_menu_result.append(data);
current_page++
}
}); //ajax
});
}); //jQuery.each
$('#loadmorebutton_body').on('click', function () {
//I dont know how can I make this button to correspond above code
});
<div id="disease_menu">
<?php
$arr = Array(
'heart'=>'heart',
'eye'=>'eye',
'ear_nose_throat'=>'ear nose throat',
'hand_foot_mouth'=>'hand foot mouth'
);
foreach ($arr as $key=>$value) {
?>
<div class="disease_li" id="disease_li_<?php echo $key;?>">
<span class="disease_span" id="<?php echo $key;?>_d"><label>(<?php echo $value;?>)</label>diseases</span>
</div>
<!--disease_li-->
<?php }?>
</div>
<!--disease_menu-->
<button id="loadmorebutton_body">Load More</button>
Use javascript functions :
function MyFunction() {
jQuery.each( elements_body, function( label_name, label_num) {
var disease_label= $('#'+ label_name + '_d');
disease_label.on('click',function(){
var data={
action: 'body_part_keyword',//wordpress loading url
postSearchNonce : MyAjaxSearch.postSearchNonce,
current_page:current_page,
label_name:label_name//this label_name will differentiate data that need to request from mysql in the action.php
};
$.ajax({
url: MyAjaxSearch.ajaxurl,
type:'POST',
cache: false,
data: data,
success: function(data){
disease_menu_result.append(data);
current_page++
}
});//ajax
});
});
}
$('#loadmorebutton_body').on('click',function(){
MyFunction();
}

How to pass form input field value to external page using jquery

I have a form where I would like to pass the value of an text input field to an external page without a form submit event. I would like to field value to become a php variable on the external page.
Here is what I have so far:
<script type="text/javascript">
jQuery(document).ready(function() {
$(function() {
cityField = $('#the_form input[id=city]');
$.ajax({
type: "POST",
url: "external.php",
data:{ city: cityfield },
success: function(data){
console.log(data);
}
});
});
});
</script>
Within the external.php page, I would like to declare the city form field value as a php variable as
$city = $_POST['city'];
To start with
jQuery(document).ready(function() {
and
$(function() {
are equivalent. The $(function() should be something like
$("input[type='button']").click(function() {
so that when you click the button, it runs the ajax request.
I cleaned up the code but the data is not being sent to external.php. It is being set but not posting. Here is my revised code
<script type="text/javascript">
$('#city').blur(function() {
var cityField = document.querySelector('#city').value;
$.ajax({
type: "post",
url: "external.php",
data: {'cityField': cityField },
dataType: "text",
success: function(data, status){
if(status=="success") {
alert("You typed: " + cityField);
}
}
});
});
I dont feel right posting an answer for a single change... But
EDIT: There are actually a few things...
<!-- For .click() -->
Click Me!
<script type="text/javascript">
// $(function() { // Trigger on page load
// $('#doStuff').click(function() { // Trigger on a click
$('#city').blur(function() { // Trigger when the focus on the field is lost (click away, tab to another field, ect)
// $('#city').change(function() { // Trigger when the fields value changes
var cityField = $('#city');
$.ajax({
type: "POST",
url: "external.php",
data:{ 'city': cityField.val() },
success: function(data){
console.log(data);
}
});
});
</script>
Changes:
You dont need jQuery(document).ready(function() {}) AND $(function(){ }). Its the same thing.
Its smart to put a var in front on your variables.
Case is important. cityField and cityfield are not the same thing
You were just sending the whole dom element to your external script. (which I assume you only wanted the contents of the input)
Also, you dont need to look for "an input, with an 'id' attribute , with a value of 'city'". Just look for #city
EDIT:
Your updated code (just putting it here so its easier to see):
<script type="text/javascript">
$('#city').blur(function() {
var cityField=$('#city').val();
$.ajax({
type:"post",
url:"autosuggest.php",
data:{'cityField':cityField },
dataType:"text",
complete:function(data, status) {
alert("You typed: "+cityField);
}
});
});
</script>
Your data will should be available in autosuggest.php as $_POST['cityField'];
Having a status check within the success function, is a little redundant, in my opinion.
It would be better to move the success:function(data,... to a complete:function(data,...

Categories

Resources