Passing JavaScript variable to PHP using POST - javascript

I read somewhere that you don't need a form or hidden value to pass data when using ajax. If I could even get an example I would be grateful.
index.js:
function collectData(r) {
//gets the rows index
var i = r.parentNode.parentNode.rowIndex;
//selects the row picked
var sliceRow = document.getElementById('Sona').rows[i];
//have access to indiviual cells in the row
var sliceCell = sliceRow.cells;
var song = (sliceCell[0].innerHTML);
var artist = (sliceCell[1].innerHTML);
$.post("myLibrary.php", { postsong: song, postartist: artist });
}
PHP file :
if (isset($_POST)) {
$song = $_POST['postsong'];
echo $song;
}

$.ajax({
url : example.com',
contentType : 'application/x-www-form-urlencoded',
type : 'post',
data : {
i : r.parentNode.parentNode.rowIndex,
sliceRow : document.getElementById('Sona').rows[i],
sliceCell : sliceRow.cells,
song : (sliceCell[0].innerHTML),
artist : (sliceCell[1].innerHTML),
},
success:function(data) {
// blabla
},
});
<?php
if(isset($_POST)) {
print_r($_POST);
}

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);

Ajax not fully posting data to php file

Getting a really strange error with Ajax not sending the entire string data across to the php script.
The string is
"<p class="MsoNormal" style="text-align:justify"><b><u><span lang="DE" style="font-size:10.0pt;mso-bidi-font-size:11.0pt;
font-family:"Verdana",sans-serif;mso-ansi-language:DE">Gold GoldGold Gold Gold Gold<o:p></o:p></span></u></b></p>
<p class="MsoNormal" style="text-align:justify"><span lang="EN-GB" style="font-size:10.0pt;mso-bidi-font-size:11.0pt;font-family:"Verdana",sans-serif"> </span></p>"
but what arrives at the php script is only (Seen through DB submission and the php $result test.
"<p class="MsoNormal" style="text-align:justify"><b><u><span lang="DE" style="font-size:10.0pt;mso-bidi-font-size:11.0pt;
font-family:"
I have tried to check through multiple methods of why this is happening but just cant figure it out at all.
Here is my Javascript code and php code.
JS:
function Send_upload_news()
{
get_title = document.getElementById('Germ_title');
get_date = document.getElementById('Germ_date');
input_title = get_title.value;
input_date = get_date.value;
input_content = $("div.nicEdit-main").html();
//console.log(input_content);
var Data = '&input_title='+input_title+'&input_date='+input_date+'&input_content='+input_content;
//console.log(Data);
$.ajax({
url : "uploadNews.php",
type: "POST",
dataType: 'text',
data : Data,
success: function(result){alert(result);},
/* success: function() {
alert('Post has been uploaded to Database');
}, */
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert('There is an error, screenshot this error and send to Admin : ' +textStatus+" - "+errorThrown);
}
});
nicEditors.findEditor( "Germ_content" ).setContent( '' );
get_title.value = "";
get_date.value = "";
$('html, body').animate({ scrollTop: 0 }, 'slow');
};
pHp:(uploadNews.php)
<?php
//Database info
$db_host = "localhost";
$db_username = "";
$db_pass = "";
$db_name = "";
//connect db
$connMS = new mysqli ( $db_host, $db_username, $db_pass, $db_name );
//grab data
$this_title = $_POST['input_title'];
$this_date = $_POST['input_date'];
$this_content = $_POST['input_content'];
$result = file_put_contents ( "test.txt", $this_content);
//create query and execute
$sqlupdate_news = "INSERT into news_content(germ_title, germ_date, germ_content) values ('$this_title','$this_date','$this_content')";
mysqli_query ($connMS,$sqlupdate_news);
//close
mysqli_close($connMS);
?>
Im using WYSWYG Nicedit as my text area
If there is somebody that can help me figure this out I would be very grateful.
The problems with your code is you are not encoding the values. So that will mess up the values. Plus you have a leading & which makes no sense. You can manually encode all the values with encodeURIComponent or you can let jQuery handle that for you.
jQuery does the encoding for you when you use an object.
function Send_upload_news() {
var get_title = document.getElementById('Germ_title');
var get_date = document.getElementById('Germ_date');
var Data = {
input_title : get_title.value,
input_date : get_date.value,
input_content : $("div.nicEdit-main").html()
};
$.ajax({
url : "uploadNews.php",
type: "POST",
dataType: 'text',
data : Data,
success: function(result){alert(result);},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert('There is an error, screenshot this error and send to Admin : ' +textStatus+" - "+errorThrown);
}
});
nicEditors.findEditor( "Germ_content" ).setContent( '' );
get_title.value = "";
get_date.value = "";
$('html, body').animate({ scrollTop: 0 }, 'slow');
}
And you really should use var so your application is not full of global variables.
You have to escape(encode) sent parameters to the server, to avoid confusion of characters like ampersand(&)
Change this:
var Data = '&input_title='+input_title+'&input_date='+input_date+'&input_content='+input_content;
To this:
var Data = '&input_title='+encodeURIComponent(input_title)+'&input_date='+encodeURIComponent(input_date)+'&input_content='+encodeURIComponent(input_content);
Encode your string properly before firing off the Ajax.
var title = encodeURIComponent(input_title);
var date = encodeURIComponent(input_date);
var content = encodeURIComponent(input_content);
var Data = 'input_title='+title+'&input_date='+date+'&input_content='+content;
$.ajax({
...
data : Data,
...
To make your life easier, why not just use object notation and let jQuery handle the encoding?
$.ajax({
...
data : {
input_title: input_title,
input_date: input_date,
input_content: input_content
},
...

How to wait for AJAX calls in an each loop to complete before moving on without ASYNC: FALSE

I currently have setup a AJAX to PHP set of functions that processes a number of items on a page. Basically the code inserts a series of tasks into the database, then inserts supplies into the database based on those newly created task ID's. However it works 90% of the time. Sometimes it seems as though the Task ID's are not created first which doesn't allow the supplies to use those ID's for inserting into the database. Is there a way to make sure that the task is inserted, then all supplies are inserted for that ID, then move onto the next one. At the end when all is complete I would like to redirect to a new page, again I put this in the last success call on the supplies portion, but it would redirect on the first loop. This process usually generates around 5 tasks, with 12 supplies per each task. I was reading about a $.when loop but could not get it to work. NOTE: after testing the ajax calls are submitting correctly, it was that one field on some of them was null, and the DB was having an issue. So the counter method below works.
$(document).on("click", "#submitTasks", function(e) {
e.preventDefault();
var tasks = $('#tasks').find('.box');
var project_id = $('#project_id').val();
tasks.each(function() {
var trs = $(this).find('.reqTables').find('.table').find('tbody').find('tr');
var task_definition_id = $(this).find('.task_definition_id').val();
var labor_type_id = $(this).find('.laborAmount').children('option:selected').val();
var task_status_id = 1;
var qty_labor = $(this).find('.laborQty').val();
var amount_labor = $(this).find('.laborTotal').val();
var amount_materials = $(this).find('.matTotal').val();
var amount_gst = $(this).find('.gstTotal').val();
amount_materials = +amount_materials + +amount_gst;
amount_materials = amount_materials.toFixed(2);
var active = 1;
//console.log(div)
var task = {
project_id : project_id,
task_definition_id : task_definition_id,
labor_type_id : labor_type_id,
task_status_id : task_status_id,
qty_labor : qty_labor,
amount_labor : amount_labor,
amount_materials : amount_materials,
active : active
};
saveTasks(task, trs, project_id);
});
});
function saveTasks(task, trs, project_id) {
$.ajax({
type : "POST",
url : "<?php echo base_url(); ?>" + "mgmt/project/saveTasks",
data : task,
dataType : "json",
cache : "false",
success : function(data) {
trs.each(function() {
var total = $(this).find('input[name="calculatedCost"]').val();
if (total != 'n/a') {
var task_id = data;
var supply_id = $(this).find('.suppliesPicker').children('option:selected').val();
var task_requirement_id = $(this).find('td:first-child').data('id');
var qty = $(this).find('input[name="calculatedQty"]').val();
var cost_per = $(this).find('.costPicker').val();
var delivery_cost = $(this).find('input[name="transport"]').val();
var notes = '';
var qty_actual = '';
var active = 1;
var taskSupply = {
task_id : task_id,
supply_id : supply_id,
task_requirement_id : task_requirement_id,
qty : qty,
cost_per : cost_per,
delivery_cost : delivery_cost,
total : total,
notes : notes,
qty_actual : qty_actual,
active : active
};
saveTaskSupplies(taskSupply);
console.log(taskSupply);
}
});
}
});
}
function saveTaskSupplies(taskSupply) {
$.ajax({
type : "POST",
url : "<?php echo base_url(); ?>" + "mgmt/project/saveTaskSupplies",
data : taskSupply,
dataType : "json",
cache : "false",
success : function(data) {
***** I WANT TO REDIRECT TO A NEW PAGE WHEN THE LAST ONE OF THESE COMPLETES ******
}
});
}
This code will wait for nested loop ajax function calls to finish their promises, then proceed..
var allPromises;
$(document).on("click", "#submitTasks", function(e) {
//...
var tasks = $('#tasks').find('.box');
allPromises = [];
tasks.each(function() {
//.. somehow getTask
var req = saveTasks(task, trs, project_id);
allPromises.push(req);
});
$.when.apply(null, allPromises).done(function(){
// Do your things here,
// All save functions have done.
});
});
function saveTasks(task, trs, project_id) {
return $.ajax({
// ,,, your codes
success : function(data) {
// ...
trs.each(function() {
// ... Somehow get taskSupply
var req = saveTaskSupplies(taskSupply);
allPromises.push(req);
}
}
});
}
function saveTaskSupplies(taskSupply) {
return $.ajax({
// ... bla bla bla
success : function(data) {
// Whatever..
}
});
}
Here is a direct solution using the code you provided. The basic concept is to increment a counter as supplies are processed. Once the counter reaches the total number of supplies, a procedure is run. See comments throughout.
var totalTaskSupplies = 0;
var processedTaskSupplies = 0;
$(document).on("click", "#submitTasks", function(e) {
e.preventDefault();
var tasks = $('#tasks').find('.box');
var project_id = $('#project_id').val();
tasks.each(function() {
var trs = $(this).find('.reqTables').find('.table').find('tbody').find('tr');
var task_definition_id = $(this).find('.task_definition_id').val();
var labor_type_id = $(this).find('.laborAmount').children('option:selected').val();
var task_status_id = 1;
var qty_labor = $(this).find('.laborQty').val();
var amount_labor = $(this).find('.laborTotal').val();
var amount_materials = $(this).find('.matTotal').val();
var amount_gst = $(this).find('.gstTotal').val();
// Add number of supplies for current task to total task supplies
totalTaskSupplies += trs.length;
amount_materials = +amount_materials + +amount_gst;
amount_materials = amount_materials.toFixed(2);
var active = 1;
//console.log(div)
var task = {
project_id : project_id,
task_definition_id : task_definition_id,
labor_type_id : labor_type_id,
task_status_id : task_status_id,
qty_labor : qty_labor,
amount_labor : amount_labor,
amount_materials : amount_materials,
active : active
};
saveTasks(task, trs, project_id);
});
});
function saveTasks(task, trs, project_id) {
$.ajax({
type : "POST",
url : "<?php echo base_url(); ?>" + "mgmt/project/saveTasks",
data : task,
dataType : "json",
cache : "false",
success : function(data) {
trs.each(function() {
var total = $(this).find('input[name="calculatedCost"]').val();
if (total != 'n/a') {
var task_id = data;
var supply_id = $(this).find('.suppliesPicker').children('option:selected').val();
var task_requirement_id = $(this).find('td:first-child').data('id');
var qty = $(this).find('input[name="calculatedQty"]').val();
var cost_per = $(this).find('.costPicker').val();
var delivery_cost = $(this).find('input[name="transport"]').val();
var notes = '';
var qty_actual = '';
var active = 1;
var taskSupply = {
task_id : task_id,
supply_id : supply_id,
task_requirement_id : task_requirement_id,
qty : qty,
cost_per : cost_per,
delivery_cost : delivery_cost,
total : total,
notes : notes,
qty_actual : qty_actual,
active : active
};
saveTaskSupplies(taskSupply);
console.log(taskSupply);
}
});
}
});
}
function saveTaskSupplies(taskSupply) {
$.ajax({
type : "POST",
url : "<?php echo base_url(); ?>" + "mgmt/project/saveTaskSupplies",
data : taskSupply,
dataType : "json",
cache : "false",
success : function(data) {
++processedTaskSupplies;
// All supplies have been processed
if (processedTaskSupplies == totalTaskSupplies) {
// Do something
}
}
});
}
Regarding the first question, by studying your code I couldn't see the reason of it. You only execute the saveTaskSupplies() when saveTasks() has executed successfully, so the task_id should already be created.
However, I would think of another possible problem from your backend, in your Ajax success function in saveTasks(), You assume the PHP script always execute successfully and return the task_id. Would it be possible that your PHP script has some problem and the task_id is not created in some instance?
For the second question, there are a few approaches, as #Seth suggest you can use jQuery.when, or you can create a global counter to keep track of whether the saveTaskSupplies() is the last one. Note that you should calculate the total length of trs before firing the Ajax request, otherwise, you may have a chance of having a not well-calculated total and redirecting before all tasks are done. If it is the last one it will redirect after successful Ajax call.
// create a global counter
var counter = 0,
trl = 0;
$(document).on("click", "#submitTasks", function(e) {
...
var trList = [];
tasks.each(function() {
// calculate the length of total task before actually firing the Ajax Request
var trs = $(this).find('.reqTables').find('.table').find('tbody').find('tr');
// keep a copy of the trs so the next each loop does not have to find it again
trList.push(trs);
trl += trs.length;
});
tasks.each(function() {
// get the trs of current iteration we have found in last loop
var trs = trList.shift();
...
saveTasks(task, trs, project_id);
});
});
function saveTasks(task, trs, project_id) {
$.ajax({
...
success : function(data) {
trs.each(function() {
...
saveTaskSupplies(taskSupply);
}
}
});
}
function saveTaskSupplies(taskSupply) {
$.ajax({
...
success : function(data) {
// check if the counter exceed the length of trs
if (++counter == trl) {
location.href = 'place you want to go';
}
}
});
}
On the other hand, for your task I would also suggest shifting the responsibility of data insertion to PHP backend, so all you need to do is to pass the task information and the task supplies at once to a single PHP script. This approach allows the use of Transaction to make sure all data insertion is success or otherwise all should fail.

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 :)

Pass Array FROM Jquery with JSON to PHP

hey guys i read some of the other posts and tried alot but its still not working for me.
when i alert the array i get all the results on the first site but after sending the data to php i just get an empty result. any ideas?
$(document).ready(function() {
$('#Btn').click(function() {
var cats = [];
$('#cats input:checked').each(function() {
cats.push(this.value);
});
var st = JSON.stringify(cats);
$.post('foo.php',{data:st},function(data){cats : cats});
window.location = "foo.php";
});
});
Php
$data = json_decode($_POST['data']);
THANK YOUU
my array looks something like this when i alert it house/flat,garden/nature,sports/hobbies
this are a couple of results the user might choose (from checkboxes).
but when i post it to php i get nothing. when i use request marker (chrome extension) it shows me something likethat Raw data cats=%5B%22house+themes%22%2C%22flat+items%22%5D
i also tried this way-- still no results
$(document).ready(function() {
$('#Btn').click(function() {
var cats = [];
$('#cats input:checked').each(function() {
cats.push(this.value);
alert(cats);
$.ajax({
type: 'POST',
url: "foo.php",
data: {cats: JSON.stringify(cats)},
success: function(data){
alert(data);
}
});
});
window.location = "foo.php";
});
});
php:
$json = $_POST['cats'];
$json_string = stripslashes($json);
$data = json_decode($json_string, true);
echo "<pre>";
print_r($data);
its drives me crazy
Take this script: https://github.com/douglascrockford/JSON-js/blob/master/json2.js
And call:
var myJsonString = JSON.stringify(yourArray);
so now your code is
$(document).ready(function() {
$('#Btn').click(function() {
var cats = [];
$('#cats input:checked').each(function() {
cats.push(this.value);
});
var st = JSON.stringify(cats);
$.post('foo.php',{data:st},function(data){cats : cats});
// window.location = "foo.php"; // comment this by this page redirect to this foo.php
});
});
//and if uou want toredirect then use below code
-------------------------------------------------
$.post('foo.php',{data:st},function(data){
window.location = "foo.php";
});
---------------------------------------------------
Php
$data = json_decode($_POST['data']);
var ItemGroupMappingData = []
Or
var ItemGroupMappingData =
{
"id" : 1,
"name" : "harsh jhaveri",
"email" : "test#test.com"
}
$.ajax({
url: 'url link',
type: 'POST',
dataType: "json",
data: ItemGroupMappingData,
success: function (e) {
// When server send response then it will be comes in as object in e. you can find data //with e.field name or table name
},
error: function (response) {
//alert(' error come here ' + response);
ExceptionHandler(response);
}
});
Try this :-
$data = json_decode($_POST['data'], TRUE);
I think you should move the "window.location = " to the post callback, which means it should wait till the post finshed and then redirect the page.
$.post('foo.php', {
data : st
}, function(data) {
window.location = "foo.php";
});

Categories

Resources