How to get the passed text and array to php - php

I have a form named as my-form. Inside of it has a 2 textbox and 1 multiple select tag. I'm unable to get all the passed data in PHP.
textbox1 has a name "tname"
textbox2 has a name "tcode"
multiple select has a name "tsubteam"
I am able to pass all the data but i don't know how to get all the data in PHP
var arr = [];
$('#tsubteam > option').each(function(){
arr.push(this.value +","+this.text)
});
$.ajax({
type: "POST",
url: "modify_team.php",
dataType: "json",
contentType: "application/x-www-form-urlencoded; charset=UTF-8;",
data: `$('#my-form').serialize()+"&id="+getQueryVariable('id')+"&subteam="+JSON.stringify(arr),
cache: false,
success: function(data)
{
console.log(data)
},
error: function(xhr, ajaxoption, thrownerror)
{
alert(xhr.status+" "+thrownerror);
}
And in PHP:
<?php
$tcode = $_POST['tcode'];
$tname = $_POST['tname'];
$id = $_POST['id'];
$subteam = $_POST['subteam'];
?>

I already resolved the main problem here.
All I did was change the
dataType: "json"
into
dataType: "text"
And modify the retrieving code of each option tag into
$('#tsubteam > option').each(function(){
item = {}
item["id"] = this.value
item["name"] = this.text
arr.push(item)
});
In PHP:
$tcode = $_POST['tcode'];
$tname = $_POST['tname'];
$id = $_POST['id'];
$subteam = json_decode($_POST['subteam'], true);
foreach($subteam as $k=>$v)
{
$subteam_name = $v["name"];
$subteam_id = $v["id"];
}
The output of passed data in AJAX
tcode=CMPSS&tname=Compass&id=1&subteam=[{"id":"1","name":"Compass Team A"},{"id":"2","name":"Compass Team B"},{"id":"3","name":"Falcon"},{"id":"4","name":"GPON"},{"id":"5","name":"TTV"},{"id":"6","name":"INFRA"},{"id":"7","name":"OSS"}]

Related

Ajax get value from php

Ajax
$(document).ready(function(){
$("#diklat").change(function(){
var diklat = $("#diklat").val();
$.ajax({
url: "function.php",
data: {'action': 'diklat'},
cache: false,
success: function(msg){
$("#angkatan").html(msg);
}
});
});
PHP
$get_action = $_GET['action'];
if($get_action=='diklat'){
$diklat = $_GET['diklat'];
$angkatan = mysql_query("SELECT id,name FROM batches WHERE IdMasterDiklat='$diklat' order by id");
echo "<option>-- Pilih Angkatan --</option>";
while($p = mysql_fetch_array($angkatan)){
echo "<option value=\"".$p['id']."\">".$p['name']."</option>\n";
}
}
The value didnt include in my ajax, ajax only read echo. how to get that value
You have written data: {'action': 'diklat'} but it should dilkat without quotes as its variable so in php you will get value in $_GET['action'].
Ajax
$(document).ready(function(){
$("#diklat").change(function(){
var diklat = $("#diklat").val();
$.ajax({
url: "function.php",
data: {'action': diklat},
cache: false,
success: function(msg){
$("#angkatan").html(msg);
}
});
});
PHP
if($_GET['action'] == 'diklat'){
$diklat = $_GET['action'];
$angkatan = mysql_query("SELECT id,name FROM batches WHERE IdMasterDiklat='$diklat' order by id");
echo "<option>-- Pilih Angkatan --</option>";
while($p = mysql_fetch_array($angkatan)){
echo "<option value=\"".$p['id']."\">".$p['name']."</option>\n";
}
}
You should pass 2 variables, one action and another id (diklat)
Ajax:
$(document).ready(function(){
$("#diklat").on('change', function(){
var diklat = $("#diklat").val();
$.ajax({
type: "POST",
url: "function.php",
data: {'action': 'diklat', 'diklat':diklat},
cache: false,
success: function(msg){
$("#angkatan").html(msg);
}
});
});
PHP
$action = isset($_POST['action']) ? $_POST['action'] : '';
if ($action == 'diklat')
{
$diklat = isset($_POST['diklat']) ? $_POST['diklat'] : '';
$angkatan = mysql_query("SELECT id, name FROM batches WHERE IdMasterDiklat='$diklat' order by id");
echo "<option>-- Pilih Angkatan --</option>";
while($p = mysql_fetch_array($angkatan))
{
echo "<option value=\"".$p['id']."\">".$p['name']."</option>\n";
}
}
Two things:
For a GET request, to ask a PHP server, data should be URL-encoded (as you see here, query string is just appended to the URL...) So tell 'data' : '?action=diklat' ...
EDIT : Jquery automatically converts object to Url-encoded query string... So It work with array ! I'm confusing with angular's $http...
And also, the parameter will be in $_GET['action'] (because action is parameter name, and diklat the value... So PHP convert query string to associative array, with parameters names as keysn and values as values...

How to insert data to database using multiple array using POST method with ajax:

I read similar answer here in this question: How to insert into MYSQL row from multiple $_POST arrays and How to insert into MYSQL row from multiple $_POST arrays but the problem is these answers do not work in my code. Is it because im using an ajax? and i only get the value of the first array.
If i also place the variable declaration inside the for loop it is not working too.
Here is my ajax:
var name = [];
$('input[name="name[]"]').map(function(){ name.push($(this).val()); }); var studid = [];
$('input[name="studid[]"]').map(function(){ studid.push($(this).val()); }); var nameStr = name != '' ? '&name='+ name : '';
var studStr = studid != '' ? '&studid='+ studid : '';
var dataString = 'subject='+ subject + '&section=' + section + studStr + nameStr;
$.ajax({ type: "POST", url: 'save.php', data: dataString, dataType: "html",
success: function(data) {
$('input#subject-field').val('');
$('input#section-field').val('');
$('input.record-input-forms').val('');
$('#status-message').css({"color":"#39b1c6"});
$('#status-message').html('Save successfully',function(){
$('#status-message').fadeOut(2000); }); },
error:function (xhr, ajaxOptions, thrownError){
alert(thrownError); } });
return false;
});
Here is my php:
if(isset($_POST['studid']) || isset($_POST['name'])){
$studid = array_map(mysql_real_escape_string, explode(",",$_POST['studid']));
$name = array_map(mysql_real_escape_string, explode(",",$_POST['name']));
for ($i=0; $i<count($studid); $i++){
$sql_1 = "INSERT INTO tbl_student(StudentID, StudentName, SubjectID) VALUES ('".$studid[$i]."', '".$name[$i]."', LAST_INSERT_ID())";
mysqli_query($con,$sql_1);
}
}
use mysql_insert_id();
instead of LAST_INSERT_ID()
You're not sending data correctly from the jQuery and its seems you'r mixing arrays and string together.
This is a simple request that posts studid-array from jQuery
var saveData = $.ajax({
type: 'POST',
data: {studid: studid},
url: 'save.php',
dataType: 'html'
});
saveData.done(function(data) {
$('input#subject-field').val('');
$('input#section-field').val('');
$('input.record-input-forms').val('');
$('#status-message').css({"color":"#39b1c6"});
$('#status-message').html('Save successfully',function(){
$('#status-message').fadeOut(2000); });
});
saveData.fail(function(ts) {
alert(ts.responseText);
});
When save.php is called, $_POST['studid'] would be set (if there are anything in the array)
If you instead do like this:
var saveData = $.ajax({
type: 'POST',
url: 'save.php?studid=' + studid,
dataType: 'html'
});
When save.php is called, $_GET['studid'] would be set (if there are anything in the array). The best way though is to use data-option in the ajax-function call (in my first case). If you choose to use this option you would have to serialize the stuid-array before putting it in as a part of an url.
UPDATE
If you want to pass multiple arrays you would have to do something like this:
var saveData = $.ajax({
type: 'POST',
data: {studid: studid, name_arr2: data_arr2},
url: 'save.php',
dataType: 'html'
});

AJAX call to PHP 2 arrays and a string

I want to pass 2 arrays (each containing values from checkboxes) and a string (coming from a search textbox) from AJAX to PHP
selectedCategories and selectedCompanies are both arrays
searchWord is a string
I have an AJAX call which looks like this, I'm not sure if it looks right though
$.ajax({
type: "POST",
data: {
'companies' : selectedCompanies;
'categories' : selectedCategories;
'searchWord' : searchWord;
},
url: "php/filteringscript.php",
success: function(data){
alert(data);
}
});
and a PHP file that catches the posts
$selectedCategories = "";
$selectedCompanies = "";
$searchWord = "";
if(isset($_POST['companies'])){
$selectedCompanies = $_POST['companies'];
}
if(isset($_POST['categories'])){
$selectedCategories = $_POST['categories'];
}
if(isset($_POST['searchWord'])){
$searchWord = $_POST['searchWord'];
}
print_r($selectedCategories);
print_r($selectedCompanies);
print_r($searchWord);
But it is not working, and nothing gets printed out.
Any help will be greatly appreciated, thanks!
var jsonString1 = JSON.stringify(selectedCompanies);
var jsonString2 = JSON.stringify(selectedCategories);
return $.ajax({
type: "POST",
url: "php/filteringscript.php",
data: {companies : jsonString1,
categories : jsonString2,
searchWord : searchWord
},
cache: false,
success: function(data){
alert(data);
}
});
In PHP file:
$companies = json_decode(stripslashes($_POST['companies']));
$categories = json_decode(stripslashes($_POST['categories']));
$searchWord = $_POST['$searchWord']));

how to return html code and php value in one ajax call

i have a simple ajax call which returns html codes,
//=======-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-==-=-=-=-=-=-=-==-=-==-=-=-=-=
//SEARCH Submit ===============================================================================
$('.clicked_search').live("click",function() {
var from = $('#from').val();
var to = $('#to').val();
var sel = $('#sel').val();
var BegDT = new Date(from);
var EndDT = new Date(to);
var sum = BegDT - EndDT;
alert (BegDT +" b"+ EndDT +" e"+ sum);
if(sum > 0 | from == "" & to != "" | from != "" & to == ""){
$('.inv_date').show();
}
else{
$("#app_panel").html('<div id="flash" align="left" ><img src="img/clientimg/ajax.gif" align="absmiddle"> <span class="loading">Loading Request...</span></div>');
$("#clock").html('<div id="flash2" align="left" ><img src="img/clientimg/ajax.gif" height="15px" align="absmiddle"> <span class="loading"><font size="1">Loading Request...</font></span></div>');
$.ajax({
type: "POST",
url: "database/clientpanel/logs/search_call_log.php",
data: {
from: from,
to: to,
sel: sel
},
cache: false,
success: function(html){
$("#flash").hide();
$('.inv_date').hide();
$("#app_panel").append(html);
}
});
$.ajax({
url: "database/clientpanel/logs/search_clock_log.php",
cache: false,
success: function(html){
$("#flash2").hide();
$('.inv_date').hide();
$("#clock").append(html);
}
});
}
return false;
});
but i also want it to return values that was produced from the php which the ajax called,
session_start();
include("../../dbinfo.inc.php");
// connect to the database
$client_id = $_SESSION['clientid'];
//===========THIS PHP VALUES RIGHT HERE===================================
$out = 0;
$in = 0;
$ext =0;
$min = 0;
$sec = 0;
//====================================================================
$query=" select * from call where client='$client_id' ORDER BY date_time DESC";
$result = $mysqli->query($query);
how can i return the "html code" together with the "php values" using one ajax call?
You could transfer your data in a JSON format.
Within your PHP, you'll build an array with all the data you want to pass back for the AJAX call.
$results = array(
'html' => $html,
'variable1'=>'value1',
'variable2'=>'value2',
...
);
Now you encode this array into a JSON format using json_encode() -
$jsonString = json_encode($results);
echo $jsonString;
This is the value that you echo out of your PHP.
Now in your jQuery $.ajax request, you'll need to specify the dataType:json, and you'll be able to access all the parameters in your success callback -
$.ajax({
type: "POST",
dataType: "json",
...
success: function(data){
...
$("#app_panel").append(data.html);
// also available :
// data.variable1 and data.variable2
}
});

jQuery autosave running success function, but not updating MySQL

My jQuery autosave is running the success function, but not updating the MySQL database. What am I doing incorrectly?
jQuery:
function autosave() {
var t = setTimeout("autosave()", 5000);
var translation = $("#doc-translation").val();
if (translation.length > 0) {
$.ajax({
type: "POST",
url: "update-draft-submission.php",
data: translation,
cache: false,
success: function() {
$(".autosaved").empty().append("saved");
}
});
}
}
PHP:
<?php
session_start();
//retrieve our data
$iddoc = $_GET['iddoc'];
$trans = translation;
$transowner = $_SESSION['userid'];
$true = 1;
include "../dbconnect.php";
$query = "UPDATE translations
SET trans='$trans'
WHERE iddoc='$iddoc'
AND transowner='$transowner'";
mysqli_query($query);
mysqli_close();
echo "Saved";
?>
You are not fetching the data in your PHP correctly:
$iddoc = $_GET['iddoc'];
$trans = translation;
iddoc is not passed as a GET parameter anywhere
"translation" is not a variable (neither do I think it is a constant)
Your SQL will break if it does not get the required values in the query.
Update your javascript so:
$.ajax(
{
type: "POST",
url: "update-draft-submission.php",
data: data: {translation:translation,iddoc:"XXX"},
cache: false,
success: function()
{
$(".autosaved").empty().append("saved");
}
});
Replace XXX with your iddoc value.
Then in PHP fetch them as:
$iddoc = $_POST['iddoc'];
$trans = $_POST['translation'];

Categories