This question already has answers here:
How do I pass JavaScript variables to PHP?
(16 answers)
Closed 5 years ago.
I want to send data from JS file to PHP file where a function receives this data and performs further actions on it. But the problem is that the data isn't receiving from JS to controller function.
JS code:
$("#mybtn").click(function(){
$.post(<?= base_url()?>+"upload",{a1: $('#a1').val(), a2:
$('#a2').val(), a3: $('#a3').val(), a4: $('#a4').val(),a5:
$('#a5').val()},function(data) {
});
});
Controller function:
function upload() {
echo "this is upload";
$data = array(
'name' => $this->input->post('a1'),
'email' => $this->input->post('a2'),
'pass' => $this->input->post('a3'),
'amnt' => $this->input->post('a4'),
'pcode' => $this->input->post('a5')
);
$result = $this->pages_m->upload($data);
var_dump($data);
}
first you declare this on header, after this you dont need to use base_url() function again in ajax.
<script>
var url = <?php echo base_url(); ?>
</script>
$("#mybtn").click(function(){
$.ajax({
url: url+'upload',
type: 'post', // performing a POST request
data : {
a1: $('#a1').val(),
a2: $('#a2').val(),
a3: $('#a3').val(),
a4: $('#a4').val(),
a5: $('#a5').val()
},
dataType: 'json',
success: function(data)
{
console.log(data)
}
});
});
In controller
function upload()
{
if($_POST){
$data = array(
'name' => $this->input->post('a1'),
'email' => $this->input->post('a2'),
'pass' => $this->input->post('a3'),
'amnt' => $this->input->post('a4'),
'pcode' => $this->input->post('a5')
);
$result = $this->pages_m->upload($data);
if($result == true){
echo "Successfully Save";
}else{
echo "Error";
}
}
}
Related
I am trying to make a simple AJAX GET call to my php backend, it hit and runs the method defined however no matter what the response data in the success function is always an empty string with a 200 response.
My ajax request is:
$("#coverage-table").on("click", "td", function() {
$(this).attr('id');
//Create Ajax call
//Get bill data/notes
//Present modal
$.ajax({
url: 'http://tms-v2.test/tms/getBillNotes',
type: 'GET',
data: {
bills: $(this).attr('id')
},
success: function(response) {
console.log(response);
debugger;
modal.style.display = "block";
}
});
});
My php method is:
public function getBillNotes() {
$bills = array_filter(explode("," ,$_GET['bills']));
$billingGateway = new BillingGateway;
$data = $billingGateway->getBillNotes($bills);
//Convert mysql object to array
while($row = mysqli_fetch_array($data)){
$items[] = $row;
}
foreach ($items as $key => $bill) {
$return[$bill['bill_id']] = [
'invoice_number' => $bill['invoice_number'],
'supplier' => $bill['supplier_name'],
'creation_date' => $bill['creation_date'],
'uploaded_by' => $bill['first_name'].' '.$bill['last_name'],
'is_credit_note' => !!$bill['type'],
'validation_status' => !!$bill['is_validating'],
'paid_date' => $bill['paid_date'],
'critical_notes' => $bill['note']
];
}
return 'TEST';
}
However this is always returning "", is this something to do with my request headers?
The data (array of array) is not getting passed from view to controller while using AJAX in CodeIgniter (PHP)
url is working in $.ajax. It is redirecting to the method in controller
view.php (view)
$('#save').click(function(){
var table_data = [];
// use .each to get all data
$('#data_table tr').each(function(row,tr){
// create array again to store data by row
// get only data with value
if ($(tr).find('td:eq(0)').text() == "") {
} else {
var sub = {
'no' : $(tr).find('td:eq(0)').text(),
'firstname' : $(tr).find('td:eq(1)').text(),
'middle' : $(tr).find('td:eq(2)').text(),
'last' : $(tr).find('td:eq(3)').text(),
};
table_data.push(sub);
}
});
//use ajax to insert the data
console.log(table_data);
var data = {'data_table':table_data};
console.log(data);
$.ajax({
data : data,
type : 'POST',
url : 'save',
crossOrigin : false,
dataType : 'array',
success: function(msg){
$('.answer').html(msg);
}
});
Welcome.php (controller)
public function save() {
$relatives_list = $this->input->post('data');
echo 'as';
echo $relatives_list;
// the list is not shown here
$this->load->model('Batch');
$status = $this->Batch->save($relatives_list);
$this->output->set_content_type('application/json');
echo json_encode(array('status' => $status));
}
Batch.php (model)
public function save($relative_list){
$length = count($relative_list);
for($x = 0; $x < count($relative_list); $x++){
$data[] = array(
'no' => $relative_list[$x]['no'],
'firstname' => $relative_list[$x]['firstname'],
'middle' => $relative_list[$x]['middle'],
'last' => $relative_list[$x]['last'],
);
}
try {
for($x = 0; $x<count($relative_list); $x++){
$this->db->insert('hhh',$data[$x]);
}
return 'success';
}catch(Exception $e) {
return 'failed';
}
}
Error:
parameter-must-be-an-array-or-an-object-that-implements-countable
According to your script it wouldn't be data it would be data_table
var data = {'data_table':table_data};
Thus:
var_dump($this->input->post('data_table')
If that doesn't work please post the console.log of your data var.
Please note: you will have to remove the echos before json_encode after you are done troubleshooting or jquery will fail to parse the response.
I'm trying to send some values through ajax and after being treated in the test.php, send the data back to be used.
The database part is correct. My problem is in the re-sending of the data:
The Json coding part does not give error, but when I try to check the data, many of them do not appear.
I think this can be caused by:
The way I am resending the data;
The way I encode Json.
My code.
ajax main.php:
$('#filtro_limit1').val(num_Limite_rows);
$.ajax({
url: teste.php,
type:'post',
data:
{
limite: num_Limite_rows,
tipologia: tipologia_val,
ordenar_por: ordenar_por_val
},
success: function(data, num_rows, num_actual_rows, mensagem_erro)
{
}
});
PHP teste.php:
if(pg_num_rows($result1) > 0)
{
$data = array[];
$data = $result1;
$out = array_values($data);
echo json_encode($out);
echo pg_num_rows($result1);
echo $filtro_limit;
echo "Não existem erros";
}
else
{
$data = array[];
echo json_encode($data);
$numero_rows = 0;
echo $total_rows;
echo $filtro_limit;
echo "Não existem valores a serem mostrados";
}
Please some help needed. Thank you for the future help.
Your success function is wrong. The parameter data will contain all the output of your php script. You can't automatically split the output by using different parameters in the function definition.
function success(data, textStatus, jgXHR) {
console.log(data);
}
Check your console and you'll see your data.
You'll probably want to change your php code:
$result = [
'out' => json_encode($out),
'result1' => pg_num_rows($result1),
'filtro_limit' => $filtro_limit,
'message' => "Não existem erros",
]
echo json_encode($result);
exit;
and
$result = [
'total_rows' => $total_rows,
'filtro_limit' => $filtro_limit,
'message' => "Não existem valores a serem mostrados",
];
echo json_encode($result);
exit;
That way, you'll have a much easier time to parse the data in JavaScript. For example:
function success(data, textStatus, jgXHR) {
var message = data.message;
}
you have to return all data in one statement in php like this :
echo json_encode(array(
'out'=>$out,
'num_rows'=>pg_num_rows($result1),
'filtro_limit'=>$filtro_limit,
'msg'=>"Não existem valores a serem mostrados"
));
and ajax code like this:
$('#filtro_limit1').val(num_Limite_rows);
$.ajax({
url: 'teste.php',
type:'post',
dataType: 'json',
data:
{
limite: num_Limite_rows,
tipologia: tipologia_val,
ordenar_por: ordenar_por_val
},
success: function(data)
{
$num_rows=data['num_rows'];
}
});
This question already has answers here:
Parse JSON from JQuery.ajax success data
(12 answers)
Closed 7 years ago.
I make an AJAX request to a PHP file as follows:
function verifica() {
var meuid = $('.meuid').attr('id');
var datas = "user=" + meuid;
$.ajax({
type: "GET",
url: 'sys/stream2.php',
data: datas
}).done(function(data) {
//alert(data);
$('#nome').html(data);
});
}
In my PHP file, I output JSON data from a loop:
foreach ($gUsuarios as $usuarios) {
$agora = $usuarios['AGORA'];
if ($agora >= $usuarios['cUsu_Limite']) {
echo json_encode(array('usuarioon' => $usuarios['cUsu_ID'], 'status' => 'fa fa-circle-o text-red'));
} else {
echo json_encode(array('usuarioon' => $usuarios['cUsu_ID'], 'status' => 'fa fa-circle-o text-green'));
}
}
The output is two JSON objects:
{"usuarioon":"1","status":"fa fa-circle-o text-red"}
{"usuarioon":"3","status":"fa fa-circle-o text-red"}
How can I parse the two JSON objects in my AJAX success handler? I've tried with parseJSON, but it did not work. I think it's because I'm returning an array within a foreach.
You shouldn't echo multiple json strings into your Ajax request, that will make it fail.
If you do this, you will get the desired results:
$retorno = array();
foreach ($gUsuarios as $usuarios) {
$agora = $usuarios['AGORA'];
if ($agora >= $usuarios['cUsu_Limite']) {
$retorno[] = json_encode(array('usuarioon' => $usuarios['cUsu_ID'], 'status' => 'fa fa-circle-o text-red'));
} else {
$retorno[] = json_encode(array('usuarioon' => $usuarios['cUsu_ID'], 'status' => 'fa fa-circle-o text-green'));
}
}
echo json_encode($retorno);
I am using wordpress and need to update a tables data with jQuery ajax, I have the below code which posts the data successfully.
jQuery('#update-<?php echo $row->id; ?>').live('click', function (){
var myname = jQuery('input[name="name_two"]').val();
var mystep = jQuery('#step<?php echo $row->id; ?> option:selected').val();
jQuery.ajax({
type: "POST",
url: "/wp-content/plugins/gates/updateGateData.php",
data: {name_two:myname, step_two:mystep},
success: function(data) {
alert('Data updated');
},
});
});
Now my problem resides on what to put in the updateGateOption.php file to post to update the database.
Thanks Guys for the responses! So I have this now:
$name = $_POST['name_two'];
$step = $_POST['step_two'];
global $wpdb;
$wpdb->update(
'gate_options',
array(
'step' => $step,
'name' => $name,
'image_path' => 'new-img-path',
'option' => strtolower($name),
'value' => strtolower($name),
)
);
But the values are not being updated, plus I cannot see any errors..
Try below Code in updateGateOption.php:
$name = $_POST['name_two'];
$step = $_POST['step_two'];
Now run your query,
if(mysql_query("UPDATE tablename SET field1= $name, field2=step WHERE 1=1 AND YOUR_CONDITION")){
echo "Data updated successfully";
}else{
echo "Something went wrong";
}