passing parameter from $.ajax post to mysqli_query not working - php

I am trying to pass parameter from $.ajax post to mysqli_query
this is my ajax
$.ajax({
type: 'post',
url: 'edit-doctor.php',
data: "imei="+imei,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
alert(data);
$.each(data, function() {
$.each(this, function(k , v) {
trHTML += '<tr><td><b>'+ k.toString() + '</b></td> : <td>' + v.toString() + '</td></tr>';
})
})
$("#target_table_id").append(trHTML);
}
});
this is my php
<?php
include("connect.php");
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$src1= $_POST["imei"]; //.. getting variable in src1
$sql = "select * from tbl_beacons where imei = '".$src1."' ";
//$sql = "select * from tbl_beacons where imei = '".$_POST['imei']."' ";
// also tried this
$result = $conn->query($sql);
$emparray = array();
while($row =mysqli_fetch_assoc($result))
{
$emparray[] = $row;
}
echo json_encode($emparray);
$conn->close();
problem is that I am able to get parameter but not able to pass in query and get result . if i send hardcore value then query is working fine
what I can modify to get parameter value and send it
EDIT:
i also figured out and modfied ajax , this also working
$.ajax({
type: "POST",
url: "edit-doctor.php",
data: {imei:imei},
success: function (data) {
$.each(JSON.parse(data), function() {
$.each(this, function(k , v) {
trHTML += '<tr><td><b>'+ k.toString() + '</b></td> : <td>' + v.toString() + '</td></tr>';
})
})
$("#target_table_id").append(trHTML);
}
});

data: "imei="+imei, is not JSON. Try data: {imei:imei},
if you send JSON you need to receive JSON too
You can also just remove the contentType: "application/json; charset=utf-8", dataType: "json",
Even better:
$.post('edit-doctor.php', {"imei":imei},function (data) {
var trHTML=[];
$.each(data, function() {
$.each(this, function(k , v) {
trHTML.push('<tr><td><b>'+ k + '</b></td> : <td>' + v + '</td></tr>');
})
})
$("#target_table_id").append(trHTML.join(''));
});

Related

selecting 2 different option values and sending data to php using ajax

I am taking two different values from select options and sending it using AJAX, but PHP is not responding to the request.
This is my jQuery code:
$(document).ready(function() {
$("#updateStatus").change(function() {
var opt = $("#updateStatus").val();
$("#updateStatus1").change(function() {
var sta = $("#updateStatus1").val();
$.ajax({
url: 'updatecode.php',
type: 'POST',
data: "option=" + opt + "&status=" + sta,
dataType: 'json',
success: function(data) {
alert(data + "hello");
}
});
});
});
});
This is my PHP code:
$id = $_POST['opt'];
$status = $_POST['sta'];
$query = "UPDATE projectstable SET projectStatus='".$status."'WHERE id='".$id."'";
$result = mysql_query($query);
$row = mysql_fetch_array($result);
if (!$row) {
echo json_encode("fail");
} else {
echo json_encode("sucess");
}
Replace your existing ajax function like this
$(document).ready(function() {
var opt = '';
var sta = '';
$("#updateStatus").change(function() {
opt = $("#updateStatus").val();
});
$("#updateStatus1").change(function() {
sta = $("#updateStatus1").val();
callAjax(opt,sta);
});
});
function callAjax(opt,sta) {
$.ajax({
url: 'updatecode.php',
type: 'POST',
data: "opt=" + opt + "&sta=" + sta,
dataType: 'json',
success: function(data) {
alert(data + "hello");
}
});
}
You are passing the json body as a query string, and you are declaring to use dataType: "json"
$.ajax({
url: 'updatecode.php',
type: 'POST',
data: "option=" + opt + "&status=" + sta,
dataType: 'json',
success: function(data) {
alert(data + "hello");
}
});
instead that you should do it like this:
$.ajax({
url: 'updatecode.php',
type: 'POST',
data: {"option": opt, "status": sta},
dataType: 'json',
success: function(data) {
alert(data + "hello");
}
});
You are sending request under data using "option=" and "&status=" but you are reading these values in PHP through $_POST['opt'] and $_POST['stat'] which should actually be $_POST['option'] and $_POST['status'] respectively.
Also you need to change the data request to JSON format like data: {option:opt,status:sta} for your dataType is JSON
Your code should be like this
$(document).ready(function () {
$("#updateStatus,#updateStatus1").change(function () {
var opt = $("#updateStatus").val();
var sta = $("#updateStatus1").val();
$.ajax({
url: 'updatecode.php',
type: 'POST',
data: {option:opt,status:sta},
dataType: 'json',
success: function (data) {
alert(data + "hello");
}
});
});
})
and php code should like this
$id = $_POST['option'];
$status = $_POST['status'];
$query = "UPDATE projectstable SET projectStatus='".$status."'WHERE id='".$id."'";
$result = mysql_query($query);
$row = mysql_fetch_array($result);
if (!$row) {
echo json_encode("fail");
} else {
echo json_encode("sucess");
}
Thanks every one looks like i just had to change some code in ajax this is my new code which is working fine
This is my PHP code I got rid of if(!$row)
mysql_select_db("dts_db",$con);
$id=$_POST['opt'];
$status=$_POST['sta'];
$query="UPDATE projectstable SET projectStatus='".$status."'WHERE id='".$id."'";
$result=mysql_query($query);if(!$result){ die("My sql query result ".mysql_error());}
else {
echo json_encode("success");
}
and this is my ajax
$.ajax({
url: 'updatecode.php',
type: 'POST',
data: {opt:opt,sta:sta},
dataType: 'json',
success: function(data) {
alert(data + "hello");
}
});

Populating dropdown using ajax php codeigniter

I have been trying all the help available on different forums but now give up and posting my question here. Trying to populate dropdown using ajax call. Getting the data in json format successfully. But don't know to fill dropdown. code below:
Controller:
function getRegion()
{
$this->load->model('Settings_model');
$title = $this->input->get('title');
$result = array("region" => $this->Settings_model->getSelectedRegion($title));
echo json_encode($result);
}
View:
$(document).on('change', '#campaignSel', function() {
changecampaign();
});
function changecampaign(){
var title= "New Normal";//$('#campaignSel option:selected').text();//$('#campaignSel').text();
$regionSel = $("#regionSel");
$.ajax({
type:"GET",
url: "<?php echo base_url('Pricecomparison/getRegion'); ?>",
data:{ "title":"New Normal"},
datatype: "json",
success: function(result){
var appenddata;
$.each(result, function (key, value) {
appenddata += "<option value = '" + value.id + " '>" + value.region + " </option>";
});
$('#regionSel').html(appenddata);
},
error: function(xhr, textStatus, error){
console.log(xhr.statusText);
console.log(textStatus);
console.log(error);
}
});
}
Response: {"region":[{"id":"1","region":"109 FEATHERSTON ST (ELEC)\r\n"},{"id":"2","region":"ASHBURTON/MID CANTERBURY
ELEC"}]}
I want to fill dropdown with Regions.
you need to loop the region like this $.each(result.region, function (key, value) { instead of result
Update1:
added if condition if ($.isArray(result.region)){ ... }
result = {"region":[{"id":"1","region":"109 FEATHERSTON ST (ELEC)\r\n"},{"id":"2","region":"ASHBURTON/MID CANTERBURY ELEC"}]}
var appenddata='';
if ($.isArray(result.region)){
$.each(result.region, function (key, value) {
appenddata += "<option value = '" + value.id + " '>" + value.region + " </option>";
console.log(appenddata);
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Finally I resolved the issues in my code. I like to share the changes I made to my code below:
added:
contentType: "application/json",
and
parsedobj = JSON.parse(result)
so the final ajax code is:
$.ajax({
type:"GET",
url: "<?php echo base_url('Pricecomparison/getRegion'); ?>",
data:{ "title":title},
contentType: "application/json",
datatype: "json",
success: function(result){
parsedobj = JSON.parse(result)
var appenddata='';
$.each(parsedobj.region, function(index, value)
{
appenddata += "<option value = '" + index + "'>" + value.region + " </option>";
});
$('#regionSel').html(appenddata);
},
error: function(xhr, textStatus, error){
console.log(xhr.statusText);
console.log(textStatus);
console.log(error);
}
});

How to pass array back to PHP using Ajax [duplicate]

Is it possible to work with a response from AJAX request in PHP? I am not really a JS dev so i am polling my hair out with this one.
I have sort of hacked this together:
var base_url = 'http://dev.local/westview/public';
$('select.child_id').change(function() {
var child_id = $('#child_id');
var dataString = 'child_id=' + child_id;
$.ajax({
type: "POST",
url: base_url + "/finance/payment-history",
data: dataString,
dataType: 'html',
success: function(html) {
alert(html);
},
});
return false;
});
The function appears to work ok, it gives me an alert with the correct data.
{"payments":[{"id":"19","child_id":"21","club":"Breakfast Club","term":"Half Term 3","amount":"15.00","pdate":"2015-02-25","notes":"","created_at":"2015-02-11 12:16:32","updated_at":"2015-02-11 12:16:32","starting_debt":"0","debt_start_date":"2015-01-05"},{"id":"20","child_id":"21","club":"After School Club","term":"Half Term 3","amount":"11.50","pdate":"2015-02-25","notes":"","created_at":"2015-02-11 12:16:49","updated_at":"2015-02-11 12:16:49","starting_debt":"0","debt_start_date":"2015-01-05"}]}
I need to be able output this to the user so that it is readable. A lot of guides I find describe replacing data but as it stands there is no data until a child_id is selected.. i then want it show the above data in a readable way.
I have no idea how to start working with the data in my view file(php).
Thanks
[EDIT]updated with working code:
var base_url = 'http://dev.local/westview/public';
$('select.child_id').change(function() {
var response = "";
var child_id = $('#child_id').val();
var dataString = 'child_id=' + child_id;
$.ajax({
type: "POST",
url: base_url + "/finance/payment-history",
data: dataString,
success: function(response) {
var json_obj = $.parseJSON(response);
var output = "<ul>";
for (i=0; i < json_obj.payments.length; i++)
{
var payment = json_obj.payments[i];
var date = moment(payment.pdate).format('Do MMM YYYY');
output += "<li>£" + payment.amount + " - " + date + " (" + payment.club + ")</li>";
}
output += "</ul>";
$('.history-section').html(output);
},
dataType: "html"
});
});
Do like this.
var data = $.parseJSON("your_json");
var output= "<ul>";
for (i=0; i < data.payments.length; i++){
output += "<li>" + data.payments[i].id + ", " + data.payments[i].child_id + "</li>";
}
output += "</ul>";
use
dataType: 'json',
instead
dataType: 'html',
and then use each to fetch the record from response in success function
Use $.parseJSON() For Convert Json Format Data To Array
Right code at sucess of ajax..
Like,
var data = $.parseJSON(html);
data in you get array format of responce
You need to use json_encode() in your php file to send the data back as an array
For example;
$myarray = array("data1"=>"value1","data2"=>"value2");
echo json_encode($myarray);
You can then access the data separately in the js file like this;
success: function(html) {
alert(html.data1);
alert(html.data2);
},
You also need to change the dataType to 'json'
$('input[name=\'product_attribute[' + attribute_row + '][name]\']').catcomplete({
delay: 0,
source: function(request, response) {
$.ajax({
url: 'index.php?route=catalog/attribute/autocomplete&token=<?php echo $token; ?>',
type: 'POST',
dataType: 'json',
data: 'filter_name=' + encodeURIComponent(request.term),
success: function(data) {
response($.map(data, function(item) {
return {
category: item.attribute_group,
label: item.name,
value: item.attribute_id
}
}));
}
});
},
select: function(event, ui) {
$('input[name=\'product_attribute[' + attribute_row + '][name]\']').attr('value', ui.item.label);
$('input[name=\'product_attribute[' + attribute_row + '][attribute_id]\']').attr('value', ui.item.value);
return false;
}
});
You Can map your json something like this

$.each iterates only one object

All that I am trying is to iterate the data I have in the database using the Jquery each method, but couldn't figure when I am losing it all. Can someone look through this piece of code and tell me what I am doing wrong ?
$(function(){
var output = $("#folderOne");
$.ajax({
url: 'http://......',
dataType: 'json',
// data: {action: 'output'},
success: function(data, status){
console.log(data);
$.each(data, function(index, value) {
if (value.f_id == 1) {
var cards = "<div class='thumb'>" + value.f_id +
"</div><br>" + "<p>" + value.title + "</p> ";
}
output.append(cards);
});
},

Get the json encoded data to ajax success

I have a php file with encoded json. What I would like to do is to get each data(maxVote and Id) from encoded json
Here is my php file named results.php
<?php
$result = array();
array_push($result,array("maxVote"=>300,"id"=>"li_2"),array("maxVote"=>200,"id"=>"li_1"));
echo json_encode($result);
?>
Since I am new to ajax and json,
what are the codes to put on success so that i will get each maxVote's and each id's
$.ajax({
url: "results.php",
success: function(){
...
}
});
Thanks in advance!
You can use:
$.ajax({
dataType: "json",
url: 'results.php',
success: function(data){
var items = [];
$.each(data, function(key, val) {
items.push(key + ' : ' + val + '</br>');
});
$('body').append(items.join(''));
}
});
or
$.getJSON('results.php', function(data) {
var items = [];
$.each(data, function(key, val) {
items.push(key + ' : ' + val + '</br>');
});
$('body').append(items.join(''));
});
Add the data parameter to your success function:
$.ajax({
url: "results.php",
success: function(data){
$.each(data, function(id, elt) {
// use data[id].maxVote or elt.maxVote
}
}
});

Categories