How to pass JavaScript variables to PHP without reload the page? - javascript

i want to assign javascript variable value to php variable to loop products
here is my php code:
$products = wc_get_products( array(
'include' => $products_ids // `**i want to pass value from javascript here**`
) );
foreach ( $products as $product ) {
// fetching my product details
}
here is my js code:
(function($){
$(document).ready(function(){
$(document).on('change', '#myform', function(e) {
e.preventDefault();
data = $(this).serialize();
var settings = {
"url": "<?php echo WC_AJAX::get_endpoint( 'myajaxfunction' ) ?>",
"method": "POST",
"data": data,
}
$.ajax(settings).done(function (result) {
// i want to make $products_ids = result
// result value is array(1,2);
});
});
});
})(jQuery);
**
i want to make $products_ids = result so i can pass it in my php
code,
result value is array(1,2);
**

Related

How to insert multiple values to database table using php?

Plz check this jsfiddle. My results are like this,
http://jsfiddle.net/kz1vfnx2/
i need to store these datas to database(sql server) one by one in each row using PHP Codeigniter. Insert to table looks like
Date Frequency
05-Feb-2019 1st Basic Treatment
12-Mar-2019 2nd Control Treatment
----------------------------------
--------------------------------
when button clicks call the function and insert to datatabase
$('#saveactivityarea').on('click', function(event) { //save new activity area
var act_contractbranch_firstjobdt = "2019-01-01";
var Contractend_firstjobdt = "2020-01-01";
var act_job_freq_daysbtw= "30";
saveschedule(act_contractbranch_firstjobdt,Contractend_firstjobdt,act_job_freq_daysbtw,0);
var contractID = $('#contractID').val();
var act_job_freq_contract = $("#act_job_freq_contract option:selected").val();
$.ajax({
type: "POST",
url: 'activity_submitted',
data: {
//here i need to pass date and frequency. insert to table like one by one row
getcontract_id: contractID,
getcontractbranch_firstjobdt: act_contractbranch_firstjobdt,
//etc....
},
success: function(data) {
alert('success')
}
})
PHP MODAL FUNCTION
$data_jobschedule = array(
'Contract_id' => $this->input->post('getcontract_id'),
'job_freq_id' => $this->input->post('getcontractbranch_freq')
);
$insert_id = 0;
if ($this->db->insert("job_schedule", $data_jobschedule))
$insert_id = $this->db->insert_id();
}
Please find the jQuery Ajax code here
Inside while loop
var dataArray = [];
while(condition) {
details = [];
//do your calculations
details['date'] = date;
details['frequency'] = frequency;
dataArray[] = details;
}
$.ajax({
url: "<?php echo site_url('activity_submitted'); ?>",
data: {dateArray: dataArray},
success: function(data){
alert('success');
},
error: function() { alert("Error."); }
});
In the controller and model, you need to get the data and insert it into the table.
$data = $_REQUEST['dateArray'];
$this->db->insert_batch('mytable', $data);

Saving a JS Variable to Local Storage Passed from PHP

When a build name is clicked the inner html is passed into a JavaScript variable loadDump then passed over to PHP.
$.ajax({
url:"http://custom-assembly.tcad.co.uk/wp-content/themes/custom-assembly/grp-enclosure/load.php",
method: "post",
data: { loadDump: JSON.stringify( loadDump )},
success: function(res){
var key_map_obj = '<?php echo $key_map_loaded; ?>';
console.log(key_map_obj);
var key_map_obj_string = key_map_obj;
localStorage.setItem("key_map_obj_string", key_map_obj_string);
console.log(localStorage);
}
})
Once this happens the php in load.php executes. The loadDump variable is used in a sql query to find the matching field.
$loadDump = wp_unslash( $_POST['loadDump'] );
$table_name= $wpdb->prefix. 'product_configurator';
$DBP_results= $wpdb->get_results("SELECT * FROM $table_name WHERE keymap_key = $loadDump");
$DBP_current_user = get_current_user_id();
foreach($DBP_results as $DBP_cols){
$user_id= $DBP_cols->user_id;
$enclosure_type= $DBP_cols->enclosure_type;
$keymap_key= json_decode($DBP_cols->keymap_key, true);
$key_map_loaded=json_decode($DBP_cols->key_map, true);
}
?>
How can i get $key_map_loaded to pass to the JavaScript and save in the local storage using Ajax.
In you php file try to return the result :
e loadDump variable is used in a sql query to find the matching field.
$loadDump = wp_unslash( $_POST['loadDump'] );
$table_name= $wpdb->prefix. 'product_configurator';
$DBP_results= $wpdb->get_results("SELECT * FROM $table_name WHERE keymap_key = $loadDump");
$DBP_current_user = get_current_user_id();
foreach($DBP_results as $DBP_cols){
$user_id= $DBP_cols->user_id;
$enclosure_type= $DBP_cols->enclosure_type;
$keymap_key= json_decode($DBP_cols->keymap_key, true);
$key_map_loaded=$DBP_cols->key_map;
}
echo $key_map_loaded;
?>
Then in the JavaScript receive it for the ajax request:
$.ajax({
url:"load.php",
method: "post",
data: { loadDump: JSON.stringify( loadDump )},
success: function (data) {
var key_map_obj = data;
console.log(key_map_obj);
var key_map_obj_string = (key_map_obj);
localStorage.setItem("key_map_obj_string", key_map_obj_string);
console.log(localStorage);
},
})

How do I pass my form arrays to my PHP script within my function?

How do I pass my form arrays to my PHP script? My php script will be serializing the data ready to be input into mysql.
Form input WHITHOUT the [] will happily pass through one value to my php. but i need to pass through and array so was thinking using the [] and then serializing on my php.
var fcl_form_data = {
index: window.localStorage.getItem("fcl_form_data:index"),
$table: document.getElementById("fcl_form_data-table"),
$form: document.getElementById("fcl_form_data-form"),
$button_save: document.getElementById("fcl_form_data-op-save"),
$button_discard: document.getElementById("fcl_form_data-op-discard"),
init:
function() {
// initialize storage index
if (!fcl_form_data.index) {
window.localStorage.setItem("fcl_form_data:index", fcl_form_data.index = 1);
}
// initialize form
fcl_form_data.$form.reset();
fcl_form_data.$form.addEventListener("submit", function(event) {
var entry = {
id: parseInt(this.id_entry.value),
client_number:this.client_number.value,
client_name:this.client_name.value,
// HERE Just these middle fields are arrays []
service:this.service.value,
size:this.size.value,
volume:this.volume.value,
deliver_point:this.deliver_point.value,
port_orgin:this.port_orgin.value,
a_port_orgin:this.a_port_orgin.value,
road_freight:this.road_freight.value,
terms:this.terms.value,
competitor:this.competitor.value,
freight_speed:this.freight_speed.value,
report_comments:this.report_comments.value,
// HERE
company_stage:this.company_stage.value,
client_user_name:this.client_user_name.value,
client_user_name_status:this.client_user_name_status.value,
client_user_name_kids:this.client_user_name_kids.value,
client_user_name_hobbies:this.client_user_name_hobbies.value,
client_user_comments:this.client_user_comments.value
};
if (entry.id == 0) { // add
fcl_form_data.storeAdd(entry);
// Adds data to table when pressed save - like a temp table above
fcl_form_data.tableAdd(entry);
}
else { // edit
fcl_form_data.storeEdit(entry);
fcl_form_data.tableEdit(entry);
}
this.reset();
this.id_entry.value = 0;
event.preventDefault();
},
true);
Form inputs are like this -
<input type="text" name="deliver_point[]" placeholder="Deliver Point">
my Ajax -
databaseAdd: function(entry) {
$.ajax({
type: "POST",
url: "//cms/by/m_upload.php",
data: entry ,
success: function(v) {alert("okay");},
failure: function(v) {alert("fail");},
dataType: JSON
});
},
MY PHP -
$client_number = $_POST['client_number'];
$client_name = $_POST['client_name'];
$service =serialize ($_POST['service']);
$size =serialize ($_POST['size']);
$volume =serialize ($_POST['volume']);
$deliver_point =serialize ($_POST['deliver_point']);
$port_orgin =serialize ($_POST['port_orgin']);
$a_port_orgin =serialize ($_POST['road_freight']);
$terms =serialize ($_POST['terms']);
$competitor =serialize ($_POST['competitor']);
$freight_speed =serialize ($_POST['freight_speed']);
$report_comments =serialize ($_POST['report_comments']);
$company_stage = $_POST['company_stage'];
$meeting_rating = $_POST['meeting_rating'];
$client_user_name = $_POST['client_user_name'];
$client_user_status = $_POST['client_user_status'];
$client_user_kids = $_POST['client_user_kids'];
$client_user_hobbies = $_POST['client_user_hobbies'];
$client_user_comments = $_POST['client_user_comments'];
$query="INSERT INTO l_reports (client_number,client_name,service,size,volume,deliver_point,port_orgin,a_port_orgin,road_freight,terms,competitor,freight_speed,report_comments,company_stage,meeting_rating,client_user_name,client_user_status,client_user_kids,client_user_hobbies,client_user_comments)
VALUES ('".$client_number."', '".$client_name."', '".$service."', '".$size."', '".$volume."', '".$deliver_point."', '".$port_orgin."', '".$a_port_orgin."', '".$road_freight."', '".$terms."', '".$competitor."', '".$freight_speed."', '".$report_comments."', '".$company_stage."', '".$meeting_rating."', '".$client_user_name."', '".$client_user_status."', '".$client_user_kids."', '".$client_user_hobbies."', '".$client_user_comments."');";
$result = $dbLink->query($query);
A small refactoring of your code would make life a lot easier for you.
For example, the ajax request which you are sending, you could make it more effiecient for the server side php by sending an object like this.
var postObjct = {
data: entry
};
Then when you send it to the php like so :
$.ajax({
type: "POST",
url: "//cms/by/m_upload.php",
data: postObjct ,
success: function(v) {alert("okay");},
failure: function(v) {alert("fail");},
dataType: JSON
});
You only have 1 json_decode to work with on the php :
//php
$postedObject = json_decode($_POST['data']);
//This POST['data'] actually contains everything in your javascript 'entry' object.
Now with this php object you can work with the values in this way :
//php
$client_number = $postedObject->{"client_number"};
//Or — TODO: Will need to test the structure
$client_number = $postedObject["entry"]["client_number"];
Of course you should do checks for nulls etc, but this will make your life a little easier!

How to access array elements in ajax response received from PHP?

jQuery code of ajax function is as follows:
$(document).ready(function() {
$("#zip_code").keyup(function() {
var el = $(this);
var module_url = $('#module_url').val();
if (el.val().length === 5) {
$.ajax({
url : module_url,
cache: false,
dataType: "json",
type: "GET",
data: {
'request_type':'ajax',
'op':'get_city_state',
'zip_code' : el.val()
},
success: function(result, success) { alert(result.join('\n'));
$("#city").val(result.place_name);
$("#state_code").val(result.state_code);
}
});
}
});
});
PHP code snippet is as follows :
case "get_city_state":
// to get the city and state on zip code.
$ret = $objUserLogin->GetCityState($request);
if(!$ret) {
$error_msg = $objUserLogin->GetAllErrors();
list($data) = prepare_response($request);
$smarty->assign('data', $data);
} else {
$data = $objUserLogin->GetResponse();
echo $data;
}
die;
break;
In PHP code the $data contains data in following manner :
<pre>Array
(
[id] => 23212
[zip_code] => 28445
[place_name] => Holly Ridge
[state_code] => NC
[created_at] => 1410875971
[updated_at] => 1410875971
)
</pre>
From the above data(i.e. response which will be available in variable result in ajax response) I want to access only two fields place_name and state_code.
I tried printing the content of result variable using alert(result) in console but I get the word Array
How to achieve this is my doubt?
Thanks in advance.
You should encode your result to json. So instead of the statement echo $data
use
echo json_encode($data);
it will return your result in json format. like
{"id":23212,"place_name":"Holly Ridge"...}
and in your javascript your can access your data

How to do the ajax + json using zf2?

i am using zf2. i want to load my second drop down by using the ajax call. i have tried with following code. i can get hard coded values. but i dont know how to add database values to a array and load that values to the drop down using ajax.
Ajax in phtml :
<script type="text/javascript">
$(document).ready(function () {
$("#projectname").change(function (event) {
var projectname = $(this).val();
var projectkey = projectname.split(" - ");
var projectname = {textData:projectkey[1]};
//The post using ajax
$.ajax({
type:"POST",
// URL : / name of the controller for the site / name of the action to be
// executed
url:'<?php echo $this->url('userstory', array('action'=>'answer')); ?>',
data:projectname,
success: function(data){
//code to load data to the dropdown
},
error:function(){alert("Failure!!");}
});
});
});
</script>
Controller Action:
public function answerAction() {
// ead the data sent from the site
$key = $_POST ['textData'];
// o something with the data
$data= $this->getProjectTable ()->getkeyproject( $key );
$projectid = $data->id;
$projectusers[] = $this->getRoleTable()->fetchRoles($projectid);
// eturn a Json object containing the data
$result = new JsonModel ( array (
'projectusers' => $projectusers
) );
return $result;
}
DB query :
public function fetchRoles($id) {
$resultSet = $this->tableGateway->select ( array (
'projectid' => $id
) );
return $resultSet;
}
your json object new JsonModel ( array (
'projectusers' => $projectusers
) json object become like this format Click here for Demo
var projectkey = [];
projectkey = projectname.split(" - ");
var projectname = { "textData" : "+projectkey[1]+" };
$.ajax({
type:"POST",
url : "url.action",
data : projectname,
success : function(data){
$.each(data.projectusers,function(key,value){
$('#divid').append("<option value="+key+">"+value+"</option>");
});
});
});
<select id="divid"></select>
This is what i did in my controller. finaly done with the coding.
public function answerAction() {
// ead the data sent from the site
$key = $_POST ['textData'];
// o something with the data
$data= $this->getProjectTable ()->getkeyproject( $key );
$projectid = $data->id;
$i=0;
$text[0] = $data->id. "successfully processed";
$projectusers = $this->getRoleTable()->fetchRoles($projectid);
foreach ($projectusers as $projectusers) :
$users[$i][0] = $projectusers->username;
$users[$i][1] = $projectusers->id;
$i++;
// eturn a Json object containing the data
endforeach;
$result = new JsonModel ( array (
'users' => $users,'count'=>$i
) );
return $result;
}
and the ajax is like this
<script type="text/javascript">
$(document).ready(function () {
$("#projectname").change(function (event) {
var projectname = $(this).val();
var projectkey = projectname.split(" - ");
var projectname = {textData:projectkey[1]};
//The post using ajax
$.ajax({
type:"POST",
// URL : / name of the controller for the site / name of the action to be
// executed
url:'<?php echo $this->url('userstory', array('action'=>'answer')); ?>',
data:projectname,
success: function(data){
// alert(data.users[0][0]+" - " + data.users[0][1] );
var count= data.count;
alert(count);
$('#myDropDown').empty();
for(var i=0;i<count;i++){
$('#myDropDown').append($('<option></option>').attr('value', data.users[i][1]).text(data.users[i][0]));
}
},
error:function(){alert("Failure!!");}
});
});
});
</script>
used the same zf2 query to access the database. thanks for the help everyone :)

Categories

Resources