How to assign AJAX JSON response to jquery variable? - javascript

When some one clicks the category button an AJAX request send to category.php in this php file i am encoding a JSON response.
Jquery Onclick Function
$('#Category').change(function(){
var j;
$.ajax({
url:'categories.php',
success: function(results){
var obj = JSON.parse(status);
alert(obj);
}
});
});
category.php File
<option value="" selected="">Select Sub Category</option>
<option value="Cars">Cars</option>
<option value="Motorbikes & Scooters">Motorbikes & Scooters</option>
$status = array('type' => 'yes');
echo json_encode($status);
Now how to assign yes to a JQuery variable on AJAX success? i tried some codes (in Above JQuery codes) but that didn't work please suggest me a solution.

According to your, you are getting the response from php page in results not in status and results itself is a jquery variable. So change status to results.
$('#Category').change(function () {
var j;
$.ajax({
url: 'categories.php',
success: function (results) {
var obj = JSON.parse(status);
alert(obj);
}
});
});

Fixed this problem.. thanks for the effort guys..
$('#Category').change(function () {
$.ajax({
url: 'categories.php',
success: function (results) {
if (results.indexOf("yes") >= 0) {
var j = 'yes';
alert(j);
}
}
});
});

Related

Send variable to php via ajax

I'm trying to send a input value to php via ajax but I can't seem to get this right. I'm trying to create a datatable based on the user input.
This is my code:
<input class="form-control" id="id1" type="text" name="id1">
My javascript code:
<script type="text/javascript">
$(document).ready(function() {
var oTable = $('#jsontable').dataTable(); //Initialize the datatable
$('#load').on('click',function(){
var user = $(this).attr('id');
if(user != '')
{
$.ajax({
url: 'response.php?method=fetchdata',
data: {url: $('#id1').val()},
dataType: 'json',
success: function(s){
console.log(s);
oTable.fnClearTable();
for(var i = 0; i < s.length; i++) {
oTable.fnAddData([
s[i][0],
s[i][1],
s[i][2],
s[i][3],
s[i][4],
s[i][5],
s[i][6],
s[i][7]
]);
} // End For
},
error: function(e){
console.log(e.responseText);
}
});
}
});
});
</script>
My php script:
<?php
$conn = pg_connect(...);
$id1 = $_POST["id1"];
$result = pg_query_params($conn, 'SELECT * FROM t WHERE id1 = $1 LIMIT 20', array($id1));
while($fetch = pg_fetch_row($result)) {
$output[] = array ($fetch[0],$fetch[1],$fetch[2],$fetch[3],$fetch[4],$fetch[5],$fetch[6],$fetch[7]);
}
echo json_encode($output);
?>
I don't know a lot of js but my php is correct i test it. So i guess the problem is in the javascript code.
The problem is, my datatable is not being created based on the user input.
Thank you!
change
data: {url: $('#id1').val()},
to:
type: 'POST',
data: {id1: $('#id1').val()},
However the problem might be bigger. You might not be getting the correct data from PHP. You can debug by adding the error option to your ajax() call, like this:
$.ajax({
url: 'response.php?method=fetchdata',
type: 'POST',
data: {id1: $('#id1').val()},
dataType: 'json',
success: function(s){
},
error: function (xhr, status, errorThrown) {
console.log(xhr.status);
console.log(xhr.responseText);
}
});
Then check your browser's Console for the output, this should give you some type of error message coming from PHP.
My assumption is that since you are using dataType: 'json', the ajax request expects JSON headers back, but PHP is sending HTML/Text. To fix, add the correct headers before echoing your JSON:
header('Content-Type: application/json');
echo json_encode($output);

How to access a javascript variable inside a php query?

I want to access a javascript variable inside a php query
function myFunction2(){
Total=parseInt(point2)
<?php
$con->query("UPDATE eventlist SET P2 = $this.Total WHERE Eid=$PID");
?>
}
I want the query to set p2=value of total
I understand that php is a serverside script and I cant do this like this. What is an alternative to this.?
EDIT
ok i got this on the JS side
function myFunction2(){
var Total = parseInt(point1)+parseInt(point2);
$.ajax({ url: 'ajax.php',
data: {'total' : Total},
type: 'post',
dataType:'json',
success: function(output) {
alert(output);
},
error: function(request, status, error){
alert("Error");
}
and if i put
echo $_POST['total']
in ajax.php i get an alert with the value passed. So i think the value is being passed properly.
But what i need to do is a Mysql Query.
$con->query("UPDATE eventlist SET P2 = $_POST['total']; WHERE Eid=1");
Something like this. How do i do this
Try send javascript value to another php page which contain your query
function myFunction () {
var param = "value";
$.post('query.php', { postvalue: param}, function(data) {
//do what you want with returned data
//postvalue should be the name of post parameter in your query page
})
}
Change your PHP in this way:
$total = $_POST['total'];
$con->query("UPDATE eventlist SET P2 = $total WHERE Eid=1");

Pass a return value from php to js

I have 3 files main.php, action.js and ajax.php and i successfully changed the content on click of some divs from main.php to some of ajax.php with a ajax call in my javascript file. It looks like this:
var value = $(this).attr("id");
$.ajax({
type: 'get',
url: "ajax.php",
data: {
auto_value: value
},
success: function(response) {
$('.gridnr1, .textnr1').fadeOut(400, function(){
$('.textnr2, .gridnr2').fadeIn(400);
});
var newtextcaption = $(response).filter('#newtextcaption').html();
var box = $(response).filter('#box').html();
$('#textnr2').html(newtextcaption);
$('#gridnr2').html(box);
for (var i=0; i<VALUE_FROM_AJAXphp; i++) {
DO SOMETHING WITH i;
}
});
Now i need a return value from a function in ajax.php in my action.js because I want to iterate till this value (see the code above).
How to pass this value from the ajax.php to the action.js.
I am confused what do I need to get the value ajax?, json? or something else?
Thank you.
in the success function, response, is what you get back from the PHP. so sending JSON would be easiest, because then your response is just an object.
Lets say ajax.php returns this JSON
{
"newtextcaption": "whatever the text is",
"boxhtml": "whatever your box html is",
"AjaxValue": 4389489473289
}
then your success function should be
success: function(response) {
$('.gridnr1, .textnr1').fadeOut(400, function(){
$('.textnr2, .gridnr2').fadeIn(400);
});
var newtextcaption = response.newtextcaption;
var box = response.boxhtml;
$('#textnr2').html(newtextcaption);
$('#gridnr2').html(box);
for (var i=0; i<response.AjaxValue; i++) {
DO SOMETHING WITH i;
}

ajax call with jQuery Mobile to PHP

I have a problem in my code, I call the php by an ajax call, I have the right answere (I tested the json answere by some alerts), my problem is when I append the data to my list-view, I have no data in my list even using the "refresh". Can you help me to find the bug please.
He gives me this error:
Uncaught Error: cannot call methods on listview prior to initialization; attempted to call method 'refresh'
Here the code in HTML and jQuery
<script language="javascript" type="text/javascript">
$(document).ready(function () {
$.ajax({url: "SubCategory.php",
dataType: "json",
jsonpCallback: 'successCallback',
async: true,
success: function (result) {
ajax.parseJSONP(result);
},
error: function (request,error) {
alert('Network error has occurred please try again!');
}
});
var ajax = {
parseJSONP:function(result){
$.each(result, function(i, row) {
$('#select-subCategory').append('<option value="'+row.id+'">Annuncio: '+row.name+'</option>');
});
$('#select-subCategory').listview('refresh');
}
}
});
</script>
<body>
<form method="post" action="SubCategory.php">
<select id="select-subCategory" data-native-menu="false">
</select>
</form>
</body>
And this is my php file
class SCategory
{
public $id;
public $name;
}
$SubCategories = array();
$SubCategories[0] = new SCategory;
$SubCategories[0]->id = 0;
$SubCategories[0]->name = 'first';
$SubCategories[1] = new SCategory;
$SubCategories[1]->id = 1;
$SubCategories[1]->name = 'second';
$SubCategories[2] = new SCategory;
$SubCategories[2]->id = 2;
$SubCategories[2]->name = 'third';
$SubCategories[3] = new SCategory;
$SubCategories[3]->id = 3;
$SubCategories[3]->name = 'fourth';
echo json_encode($SubCategories);
SOLUTION
Delete 'data-native-menu="false"' from HTML, (maybe is true by
default), so the select in HTML become simply
<select id="select-subCategory" ></select>
then the listview will refresh and
appear!! :)
You are using $('#select-subCategory').append(
and id is selectsubCategory
but should be used
$('#selectsubCategory').append(
this should work fine
$.each(result, function(key, row) {
$.each(row, function(id, name) {
$("<option>").val(id).text(name).appendTo($('#selectsubCategory'));
});
});
$('#select-subCategory').listview();
if you are loading the entire list you will need to initialize it not to refresh it
I fixed the problem :
Delete 'data-native-menu="false"' from HTML, (maybe is true by default), so the select in HTML become simply
<select id="select-subCategory" ></select>
then the listview will refresh and appear!! :)

Select list not getting populated (jQuery Ajax)

Update: Got this working by disabling CodeIgniter Profiler which was interfering with the Ajax success response. I think it adds a div to the JSON response.
I am trying to populate a dependent select box with data from mysql database. The problem is that the dependent select box is not getting populated in spite of getting data in the correct format in response to Ajax request.
Please help me as I am totally clueless about what's happening here. Below is my JavaScript code.
<script type="text/javascript">
$(document).ready(function(){
$('#country').change(function(){
$("#cities > option").remove();
var form_data = {
country: $('#country').val(),
csrf_token_name: $.cookie("csrf_cookie_name")
};
$.ajax({
type: "POST",
url: "http://localhost/outlets/get_cities",
data: form_data,
dataType : "JSON",
success: function(cities)
{
$.each(cities,function(id,name)
{
var opt = $('<option />');
opt.val(id);
opt.text(name);
$('#cities').append(opt);
});
}
});
});
});
</script>
And here is the HTML. I am using Codeigniter.
<form id="form">
<?php $cities['#'] = 'Please Select'; ?>
<label for="country">Country: </label><?php echo form_dropdown('country_id', $countries, '#', 'id="country"'); ?><br />
<label for="city">City: </label><?php echo form_dropdown('city_id', $cities, '#', 'id="cities"'); ?><br />
</form>
Here is the controller:
function get_cities(){
$country = $this->input->post('country');
$this->load->model('city');
header('Content-Type: application/x-json; charset=utf-8');
echo (json_encode($this->city->get_cities($country)));
}
& the Model:
function get_cities($country = NULL){
$this->db->select('id, name');
if($country != NULL){
$this->db->where('countries_id', $country);
}
$query = $this->db->get('cities');
$cities = array();
if($query->result()){
foreach ($query->result() as $city) {
$cities[$city->id] = $city->name;
}
return $cities;
}else{
return FALSE;
}
}
Change your ajax success callback to:
success: function (cities) {
for (var id in cities) {
var opt = $('<option />');
opt.val(id);
opt.text(cities[id]);
$('#cities').append(opt);
}
}
Because your ajax result is not a array but an json object.
Alright everyone, I managed to get this working by disabling CodeIgniter Profiler. Codeigniter profiler, that otherwise is a handy tool, breaks javascript on any page with Ajax. If you can't do without profiler, use the solution provided on Making CodeIgniter’s Profiler AJAX compatible

Categories