Ajax call returns nothing - php

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

Related

loop Ajax Response in select Option tag

i have to select multiple tests and date and when clicked on submit based on the test,laboratory names are loaded in select option
Ajax script
$('[name=submits]').click(function(e)
{
e.preventDefault();
var array = [];
$('select :selected').each(function(i,value)
{
array[i] = $(this).val();
});
var testdate = $("#appointmentdate10").val();
//here make your ajax call to a php file
$.ajax({
type: "POST",
url: "http://localhost/refer/index.php/details",
data: { laboratory_tests: array, testdate: testdate },
success: function(data){
// alert(data);
console.log(data);
var selOpts = "";
for (i=0;i<data.length;i++)
{
var id = data[i]['laboratory_id'];
var val = data[i]['laboratory_name'];
selOpts += "<option value='"+id+"'>"+val+"</option>";
}
$('#yourSelect').append(selOpts);
}
});
});
Ajax success response is:
[
{"laboratory_id":"19","laboratory_name":"ghc","laboratory_address":"cgc","laboratory_place":"jhggj","laboratory_tests":"MRI R\/L SHOULDER WITH CONTRAST"},
{"laboratory_id":"20","laboratory_name":"BBNB","laboratory_address":"sdfds","laboratory_place":"sdfsd","laboratory_tests":"MRI R\/L SHOULDER WITH CONTRAST"},
{"laboratory_id":"22","laboratory_name":"Anand","laboratory_address":"bsk","laboratory_place":"bengaluru","laboratory_tests":"MRI R\/L SHOULDER WITH CONTRAST"}
]
html
<select class="form-control" id="yourSelect">
</select>
but i am not able to display in select tag
$.ajax({
url: config.routes.profitsReport,
type: "POST",
dataType: 'json',
success: function (result) {
$.each(result, function (i, value) {
$('#category_profit').append('<option id=' + JSON.stringify(value.id) + '>' + JSON.stringify(value.name) + '</option>');
});
},
error: function (request, status, error) {
alert(request.statusText + "[" + request.status + "]");
alert(request.responseText);
$('button#form_salesReport_button').html(config.messages.searchReport);
}
});
Try to loop through the result like this:
success: function(data){
// alert(data);
console.log(data);
var selOpts = "";
$.each(data, function(k, v)
{
var id = data[k].laboratory_id;
var val = data[k].laboratory_name;
selOpts += "<option value='"+id+"'>"+val+"</option>";
});
$('#yourSelect').append(selOpts);
}
You can loop
[
{"laboratory_id":"19","laboratory_name":"ghc","laboratory_address":"cgc","laboratory_place":"jhggj","laboratory_tests":"MRI R\/L SHOULDER WITH CONTRAST"},
{"laboratory_id":"20","laboratory_name":"BBNB","laboratory_address":"sdfds","laboratory_place":"sdfsd","laboratory_tests":"MRI R\/L SHOULDER WITH CONTRAST"},
{"laboratory_id":"22","laboratory_name":"Anand","laboratory_address":"bsk","laboratory_place":"bengaluru","laboratory_tests":"MRI R\/L SHOULDER WITH CONTRAST"}
]
via
var options = "";
for (let item in array) {
options += `<option value=${item.id}>${item.laboratory_name}</option>`;
}
document.getElementById("yourSelect").innerHTML = options;
If it's a String, you can convert it to an array via JSON.parse.
If you are expecting json data from ajax request then you need to require to add dataType as json.
$('[name=submits]').click(function(e)
{
e.preventDefault();
var array = [];
$('select :selected').each(function(i,value)
{
array[i] = $(this).val();
});
var testdate = $("#appointmentdate10").val();
//here make your ajax call to a php file
$.ajax({
type: "POST",
dataType: "json",
url: "http://localhost/refer/index.php/details",
data: { laboratory_tests: array, testdate: testdate },
success: function(data){
// alert(data);
console.log(data);
var selOpts = "";
for (i=0;i<data.length;i++)
{
var id = data[i]['laboratory_id'];
var val = data[i]['laboratory_name'];
selOpts += "<option value='"+id+"'>"+val+"</option>";
}
$('#yourSelect').append(selOpts);
}
});
});

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

how do I display json results using jquery ajax

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

jquery passing variables to php file

acctually i am not familier much with jquery.. i got this jquery script this is passing variables to the file which is showing data in json format.. but here i'm unable to show that data..plz see this piece of code
$(document).ready(function() {
var globalRequest = 0;
$('#search').bind('keyup', function(event) {
if (event.keyCode == 13) {
searchAction();
}
});
$('#search-link').bind('click', function(event) {
searchAction();
});
var searchAction = function() {
var value = $('#search').val();
var cat = $('#category').val();
var country = $('#country').val();
var page = $('#page').val();
var resultContainer = $('#results');
if (value.length < 3 && globalRequest == 1) {
return;
}
_gaq.push(['_trackEvent', 'Search', 'Execute', 'Page Search', value]);
globalRequest = 1;
$.ajax({
url: "search.php",
dataType: 'json',
type: 'GET',
data: "q="+value+"&category="+cat+"&country="+country+"&page="+page,
success: function(data){
globalRequest = 0;
resultContainer.fadeOut('fast', function() {
resultContainer.html('');
console.log(data.length);
for (var x in data) {
if (!data[x].price)
data[x].price = 'kA';
if (!data[x].img)
data[x].img = 'assets/images/no.gif';
var html = '<div class="res-container">';
html += '<h2>'+data[x].Title+'</h2>';
html += '<img src="'+data[x].img+'">';
html += '<h3>Price: '+data[x].price+'</h3>';
html += '</div>';
resultContainer.append(html);
}
resultContainer.fadeIn('fast');
});
}
});
};
});
in search.php data is in simple echo.. how to get data from search.php and show here..
sorry for bad english
First,
you shouldn't concatenate your parameters but use a hashmap:
$.ajax({
url: "search.php",
dataType: 'json',
type: 'GET',
data: {
q : value,
category : cat,
country : country,
page : page }
As your method is (type: 'GET'), just use the ($_GET[param] method) in the php file
<?php
$value = htmlentities($_GET['q']);
$category = htmlentities($_GET['category ']);
$country = htmlentities($_GET['country ']);
In the js callback function, this is how you log the whole response ('something' is a tag) :
success: function(data){
var $xml = $(data);
console.log($xml); // show the whole response
console.log($xml.find('something')); // show a part of the response : <something>value</something>
});
It is a bit hard to understand what your problem is but my guess is that you need to json encode the data before echoing it back in search.php.
simplified example......
eg.
<?php
$somevar = $_GET['a']
$anothervar = $_GET['b']
//Do whatever
$prepare = array('a'=>$result1,'b'=>$result2) //etc..
$json = json_encode($prepare);
echo $json;
exit();
?>
Then you can access the results in the javascript with:
success: function(data){
var obj = $.parseJSON(data);
alert(data.a);
$("#some_element").html(data.b);
}

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