how do I display json results using jquery ajax - php

here is my ajax request :
$(".colorme").on("click", function () {
var c = $(this);
var b = "id=" + c.attr("id");
$.ajax({
type: "POST",
url: "../../colorme",
data: b,
success: function (a) {
$.when(c.fadeOut(300).promise()).done(function () {
if (c.hasClass("btn")) {
c.removeClass("btn-default").addClass("btn-success").text(a).fadeIn()
} else {
c.replaceWith('<span class="notice_mid_link">' + a + "</span>")
}
})
}});
return false
})
so here is what I receive as a response :
{"f0d8c0":0.3269616519174,"d8d8d8":0.22377581120944,"181818":0.10926253687316,"d8a890":0.091268436578171,"303030":0.054454277286136}
I would like to be able display each one of those values as a pair.Right now it returns :[object OBJECT]

Use,
data = $.parseJSON(JSON.stringify(a));

Try this.
var obj = jQuery.parseJSON(a);
alert( obj.f0d8c0);
alert( obj.d8d8d8);
You can assign your response value in var a =$.parseJSON(RESPONSE VALUE)
For more Details Read this LINK

$.ajax({type: "POST", url: "../../colorme", data: b, success: function (a) {
resp = jQuery.parseJSON(a);
alert(resp.f0d8c0);
alert(resp.d8d8d8); //maybe you need to use a better way to name the data?
$.when(c.fadeOut(300).promise()).done(function () {
if (c.hasClass("btn")) {
c.removeClass("btn-default").addClass("btn-success").text(a).fadeIn()
} else {
c.replaceWith('<span class="notice_mid_link">' + a + "</span>")
}
})
}});

Related

jQuery use ajax and json to switch page with button

Hi so I have a JS file with a function for my button, this button get value from different checkbox in a table. But now i want to get these value on another page (for invoice treatement).
Here is my Script :
$("#boutonfacturer").click(function () {
var checked = $('input[name="id_commande[]"]:checked');
var tab = [];
var jsonobj = {};
checked.each(function () {
var value = $(this).val();
jsonobj.value = value;
tab.push(jsonobj);
});
var data= { recup : tab };
console.log(data);
$.ajax({
type: 'POST',
url: 'genererfacture-facture_groupee.html',
data: data,
success: function (msg) {
if (msg.error === 'OK') {
console.log('SUCCESS');
}
else {
console.log('ERROR' + msg.error);
}
}
}).done(function(msg) {
console.log( "Data Saved: " + msg );
});
});
i use an MVC architecture so there is my controller :
public function facture_groupee() {
$_POST['recup'];
var_dump($_POST['recup']);
console.log(recup);
$this->getBody()->setTitre("Facture de votre commande");
$this->getBody()->setContenu(Container::loader());
$this->getBody()->setContenu(GenererFacture::facture_groupee());
and for now my view is useless to show.
I have probably make mistake in my code.
Thank you.
Nevermind after thinking, I have used my ajax.php page which get my another page thanks to a window.location :
my JS :
$("#boutonfacturer").click(function () {
var checked = $('input[name="id_commande[]"]:checked');
var tab = [];
checked.each(function () {
var value = $(this).val();
tab.push(value);
});
var data = {recup: tab};
console.log(data);
$.ajax({
type: 'POST',
url: 'ajax.php?action=facture_groupee',
data: data,
success: function (idfac) {
console.log("Data Saved: " + idfac);
var id_fac = idfac;
window.location = "ajax.php?action=facture_groupee=" + id_fac;
}
});
});
my php :
public function facture_groupee() {
foreach ($_POST['recup'] as $p){
echo $p; }

Get repeated data from database when mousemove using jquery ajax

I have data which I got from database and It's in display.php.
Then mousemove is used to display data. But the data keeps repeating when I do mouseover. This is the code to mouse move
$(line.node).mousemove(get_over_handler(country));
and this is some code in function get_over_handler(country)
function get_over_handler(country) {
return function (event) {
color_country(country, selected_color);
var country_name = $("#country_name_popup");
country_name.empty();
country_name.append("<span id='popup_country_name'> " + code_to_name[country] + "</span><table width='100%' style='border-spacing:20px;'>");
var id_dataset = $("#dataset_select").find('option:selected').attr('id');
$.ajax({
type: "POST",
url: "display.php",
data: {ibukota: country, id_dataset: id_dataset},
success: function (data) {
country_name.append(data);
}
});
My question is how to prevent repeated data I got from database?
Rewrite your function to:
function get_over_handler(country) {
return function (event) {
color_country(country, selected_color);
var id_dataset = $("#dataset_select").find('option:selected').attr('id');
$.ajax({
type: "POST",
url: "display.php",
data: {ibukota: country, id_dataset: id_dataset},
success: function (data) {
var country_name = $("#country_name_popup");
country_name.empty();
country_name.append("<span id='popup_country_name'> " + code_to_name[country] + "</span><table width='100%' style='border-spacing:20px;'>");
country_name.append(data);
}
});
}
}

CodeIgniter : How to retrieve ajax jquery data passed through window.location.href in new controller

CodeIgniter : How to retrieve ajax jquery data passed through window.location.href in new controller ?
$(".x").on("click","a.p",function(){
productId = $(this).attr("productId");
alert("product ID : " + productId);
$.ajax({
url: 'home/allProductDetails',
type: 'POST',
data: {
'productId' : productId
},
success: function (dat) {
var result = eval('(' + dat + ')');
if (result.success == true)
{
if(result.data.length>0)
{//alert("Success");window.location.href = "newControllerName" + "?result=" + result.data;
}
}
on ajax success, the data is passed to the new controller using window.location.href
Try this,
Ajax:
$(".x").on("click","a.p",function(){
productId = $(this).attr("productId");
alert("product ID : " + productId);
$.ajax({
url: 'home/allProductDetails',
type: 'POST',
data: {
'productId' : productId
},
success: function (dat) {
var result = eval('(' + dat + ')');
if (result.success == true)
{
if(result.data.length>0)
{
//alert("Success");
window.location.href = "newControllerName/methodName/" + result.data;
}
}
});
});
Controller:
function methodName($data)
{
//here you can access `$data` variable
print_r($data);
}
This can work try it...

Ajax call returns nothing

I am trying to make an ajax call on click on anchor tag dynmically generated from $.each loop for a JSON response.
For Information : #records is my table and .update is the class of anchor tag in that table.
Please be informed that the table is generated dynamically.
Now the problem is that my ajax call is returning nothing even i have checked it error: but no response received. I have tried alerting my var data just before the ajax call and it worked.So the problem starts from the ajax call. Moreover, my server side code is running fine.
// Update existing customers
$("#records").on('click', ".update", function() {
var data = '?'+ $(this).attr('id');
$.ajax({
type: "GET",
url: "viewcustomers.php",
data: data,
success: function(response) {
console.log(response);
}
});
});
Thanks in advance.
For reference below is the code that generates the table.
// Function to make datagrid
function getRecords() {
$.getJSON("viewcustomers.php", function(data) {
var items = [];
var xTd = '';
var xTr = '';
$.each(data, function(key, val) {
var c = 0;
var id = 0;
$.each(val, function(key1, val1) {
if (c == 0)
{
id = val1;
}
c++;
xTd += '<td>' + val1 + '</td>';
});
xTd += '<td>Edit</td>';
xTd += '<td>Delete</td>';
xTr = '<tr>' + xTd + '</tr>';
items.push(xTr);
xTd = '';
xTr = '';
});
$("#records").append(items);
});
}
Updated the server side code:
page url : localhost/hotel/viewcustomers.php
/**
* Fetch single row for the purpose of update / delete.
*/
if(isset($_GET['update'])){
$customer = new Customers;
$Id = $_GET['update'];
$customer_single = $customer->View_Single_Customer($Id);
echo json_encode($customer_single);
unset($customer);
}
This line is not used the right way var data = '?'+ $(this).attr('id');
Change it like this: var my_id = $(this).attr('id');
Then update the line data: data with data : {id:my_id}
Complete code :
$("#records").on('click', ".update", function() {
var my_id = $(this).attr('id');
$.ajax({
type: "GET",
url: "viewcustomers.php",
data : {id : my_id},
success: function(response) {
console.log(response);
}
});
});
Or do it like this:
$("#records").on('click', ".update", function() {
var param = '?id='+ $(this).attr('id'); /*notice that I have added "id=" */
$.ajax({
type: "GET",
url: "viewcustomers.php" + param,
/* remove the data attribute */
success: function(response) {
console.log(response);
}
});
});
Modify it as
$("#records").on('click', ".update", function() {
var request = '?id='+ $(this).attr('id');
$.ajax({
type: "GET",
url: "viewcustomers.php" + request,
success: function(response) {
console.log(response);
}
});
});

Jquery ajax is not sending data

For some reason ajax is not sending data.
On the PHP I have this code:
if (isset($_POST['submit'])) {
echo "submit";
} else {
echo "not submit";
}
And I get not submit.
This is JS code:
$(function () {
$('#submit').click(function () {
var length = $('#number').val();
var small = $('#small').val();
var big = $('#big').val();
var number = $('#numero').val();
var special = $('#special').val();
var submit = 'submit';
var url = 'public/php/codegenerator.php';
var data = "length=" + length + "&small=" + small + "&big=" + big +
"&number=" + number + "&special=" + special + "&submit=" + submit;
$.ajax({
type: "POST",
url: url,
data: data,
success: function () {
$('#code').load(url, function () {
$(this).fadeIn(1000)
});
}
});
return false;
});
});
You can try this approach
$(function(){
$('#submit').click(function(){
//YOUR CODE
var param = {
length:length,
small:small,
big:big,
number:number,
special:special,
submit:submit
}
$.ajax({
type: "POST",
url: url,
data: param,
//EDITED LINE
success: function (data) {
$('#code').hide().html(data).fadeIn(1000);
}
});
return false;
});
});
// REVISED ANSWER
// IN YOUR PHP FILE
if (isset ($_POST['submit'])) {
echo json_encode(array('result'=>"submit"));
}
else {
echo json_encode(array('result'=>"not submit"));
}
//IN YOUR JQUERY CODE
$.ajax({
type: "post",
url: url,
data: param,
dataType:'json';
//EDITED LINE
success: function (data) {
// alert(data.result);
$('#code').hide().html(data.result).fadeIn(1000);
}
});
You are getting Not submit, because it comes from the .load() call and not from .ajax - and in the load call you just load the URL without passing any POST data. So why you are running .load inside the success callback of .ajax with the same url?

Categories