AJAX call to PHP 2 arrays and a string - php

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

Related

How to get the passed text and array to 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"}]

How to use a jQuery data into a PHP code?

I want to use the value of limit and offset into my PHP code but I can't.
Here is my code:
var maxData = 0;
var limitt=6;
var offsett=1;
$.ajax({
url: "../model/conn.php",
type: 'POST',
data: 'getData='+'&limit='+limitt+'&offset='+offsett,
}).done(function( data ) {
$("#d1 ").html(data);
while (limitt<maxData){
limitt= limitt+6;
offsett=offsett+6;
}
});
<?php
if(isset($_POST['getData'])) {
$serv = "localhost";
$user = "root";
$psrd = "";
$db = "nonc";
$conn = mysqli_connect($serv, $user, $psrd, $db);
$limit=$_POST['&limit'];
$offs=$_POST['&offset'];
$sql = "SELECT * FROM non_confor limit $offs, $limit;";
$resltt = mysqli_query($conn, $sql);
$checkk = mysqli_num_rows($resltt);
?>
When I run my PHP page they show me that I have errors on $limt and $offs, because they don't receuve the data from AJAX.
First thing, you are using POST method for form submission and passing data as a query string which is making an error. Correct that as below:
$.ajax({
url: "../model/conn.php",
type: 'POST',
data: {
'getData': 1, // passing 1 as you are using getData in php.
'offset': offsett,
'limit': limitt
},
}).done(function(data) {
$("#d1 ").html(data);
while (limitt<maxData){
limitt= limitt+6;
offsett=offsett+6;
}
});
After this, you need to make modification in your PHP code as below:
$limit=$_POST['limitt'];
$offs=$_POST['offsett'];
After this, your code should work fine. Hope it helps you.
This is a syntax problem , here is the correction :
$.ajax({
type: 'POST',
url: '../model/conn.php',
data: {
'getData':limit,
'offset':offsett
},
success: function(msg){
// rest of your code
}
});
Data attribute should have as value a json format

Codeigniter Ajax request URL issue

I am using codeigniter version 3+, Jquery version 3+. I am trying to get data through ajax request but it does not return anything. And when I inspect and see its request url is wrong but did not get how i modify that.
Ajax request
var site_url = '<?=base_url()?>';
var id = $(this).find("option:selected").attr('value');
$.ajax({
type : 'POST',
dataType : 'json',
url: '<?=base_url()?>'+'index.php/talika_12/get_data_by_id_ajax',
data: {user_id:id},
success: function(data) {
alert(data);
$('#inst_name').text(data.talika_12_user_name);
$('#inst_account_no').text(data.talika_12_user_account_no);
}
});
Controller
public function get_data_by_id_ajax(){
$user_id = $_POST['user_id'];
$data = $this->talika_12_m->get_data_by_id($user_id);
$ajax_response_data = array(
'talika_12_user_name' => $data[0]->talika_12_user_name ,
'talika_12_user_account_no' => $data[0]->talika_12_user_account_no ,
);
echo json_encode($ajax_response_data);
}
Model
public function get_data_by_id($id){
$where_clause = array('talika_12_user_id' => $id);
$this->db->limit(1);
$val = $this->db->get_where('table_12', $where_clause)->result();
return $val;
}
Get request url is ( Request URL:http://localhost/test/codeIgniter/talika_12/%3C?=base_url()?%3Eindex.php/talika_12/get_data_by_id_ajax
)
Please try this code
var id = $(this).find("option:selected").attr('value');
$.ajax({
type : 'POST',
dataType : 'json',
url: "<?=base_url()?>index.php/talika_12/get_data_by_id_ajax'",
data: {user_id:id},
success: function(data) {
alert(data);
$('#inst_name').text(data.talika_12_user_name);
$('#inst_account_no').text(data.talika_12_user_account_no);
}
});
changed url portion url: "<?=base_url()?>index.php/talika_12/get_data_by_id_ajax'", otherwise you can use url:<?= site_url('talika_12/get_data_by_id_ajax')

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

Sending an array from jquery to PHP and back

I have a list of options (categories) of projects that the user can see. By selecting the categories, the div below should update with the lists of projects matching said categories.
Despite using the following answer, almost verbatim, Send array with Ajax to PHP script, I am still unable to retrieve any results, and yet no errors show up either.
The jquery:
// filter for projects
var $checkboxes = $("input:checkbox");
function getProjectFilterOptions(){
var opts = [];
$checkboxes.each(function(){
if(this.checked){
opts.push(this.name);
}
});
return opts;
}
$checkboxes.on("change", function(){
var opts = getProjectFilterOptions();
//alert(opts);
var categories = JSON.stringify(opts);
$.ajax({
url: "/web/plugins/projcat.php",
type: "POST",
dataType: "json",
data: {data : categories},
cache: false,
success: function(data) {
$('#projects').html(data);
//alert(data);
}
});
});
the php (still in testing, so not filled out):
<?php
if(isset($_POST['categories'])) {
//echo "testing";
$data = json_decode(stripslashes($_POST['categories']));
print_r($data);
}
?>
Where is the error?
Try this:
JS
...
// dataType: "json", // remove that; you're not sending back JSON string
data: {categories : categories},
cache: false,
...
PHP
<?php
if($_SERVER['REQUEST_METHOD']=='POST' && isset($_POST['categories'])) {
//echo "testing";
$data = json_decode(stripslashes($_POST['categories']));
// .. process the $data
print_r($data);
return;
}
?>
Your desired array is in $_POST['data'] and not in $_POST['projcats']. Change data: {data : categories}, to data: { projcats: categories }, to use $_POST['projcats'].

Categories