Get response array from jquery ajax to php - php

I am trying to populate a table from mysql based on a select box option using jquery ajax, so far this is my jquery code. I can show the result on the alert box but i dont know how to send it to php so that i can loop thru the array and create the table.
// selector de campaƱa en reporte de clientes mas activos
$(document).ready(function(){
$('.selector-camp').change(function(){
var campaing = $('.selector-camp').val();
$.post( "../campanas/test", { 'camp': campaing },
function( data ) {
alert( data.result );
}, "json");
});
});

As I use JavaScript more than jquery, I'll write it in JavaScript and I am sure you can do that in Jquery too, but in JavaScript it's also easy to do
function( data )
{
createTable(data.result); //pass your json array to JS function
}, "json");
//here i create js function
function createTable(array)
{
var array = JSON.parse(array); //decoding from json format
//So if i have numbers in array like [1, 2, 3, 4] and want
//to create row with them something like this should be done
var table = document.createElement("table"); //create table
var tr = document.createElement("tr"); //create row
for(var i=0; i<array.length; i++)
{
var td = document.createElement("td");
td.innerHTML = array[i];
tr.appendChild(td);
//for each array element creates cell and appends to row
}
table.appendChild(tr);
//Then you can have some empty div and append table to it
var div = //your empty div
div.appendChild(table);
}

Please check below php prototype code as per your requirement.
From ajax please make a call to this file it will return you a json response since I have used json_encode() function, you can directly return array as well but I would not suggest that, also you can edit this code for further mysql query.
<?php
test();
function test(){
$camp = htmlspecialchars($_POST['camp']);
isset($camp)&&!empty($camp)?
$data = array('test_key'=>'test_value');
echo json_encode($data);
}
?>

Related

Accessing DOM element created using jquery .load()

My goal is to obtain an array of data from a mysql database using PHP for use in a javascript function; graph() in the example below.
I have chosen to do this by loading the data i need to a DOM element. I am now trying to access it. The query works and I can see the information I need in my #loadTarget div. I am having trouble accessing the innerHTML though.
According to Jquery documentation, i can use a complete function which will execute once the load is done:
.load( url [, data ] [, complete ] )
Why then, when I can see the database data I need rendered in my element, can i not access it using getElementByID and innerHTML?
var dataLocation = document.getElementById("arrayTargetOne");
var data = dataLocation.innerHTML;
The above returns data is null. If i do the same getElementById on the parent element (not the one created in my PHP .load file, the one already there), i can see the data I need. It is like the .load function is not complete. Am i missing something minor or should i take a different approach?
The Javascript/Jquery
$( ".selectUser" ).click(function() {
var userChoice = document.getElementById(this.id);
var user = x.innerHTML;
$("#loadTarget").load("example.php",{"data":user},function() {
var dataLocation = document.getElementById("arrayTargetOne");
var data = dataLocation.innerHTML;
alert(data);
graph();
});
The PHP
<?php
$login_errors = array();
require ("config.php");
require (MYSQL);
$arrayOne = array();
$arrayTwo = array();
$exampleQuery = $dbc->prepare("SELECT exampleFieldOne,exampleFieldTwo FROM exampleTable WHERE userID=? AND name=?");
$exampleQuery->bind_param('ss',$_SESSION['user_id'],$_POST['data']);
$exampleQuery->execute();
$exampleQuery->bind_result($a,$b);
while($exampleQuery->fetch()){
array_push($arrayOne,$a);
array_push($arrayTwo,$b);
}
echo '<span id="arrayTargetOne">';
echo json_encode($arrayOne);
echo '</span><span id="arrayTargetTwo">';
echo json_encode($arrayTwo);
echo '</span>';
?>
});
var list = document.getElementById('loadTarget').children;
for (var i=0, len = list.length; i<len; ++i) {
var data = list[i].nodeValue; //for text nodes, use innerHTML for elements
//do stuff with data
}
The list will be a list of the created DOM nodes.

Print an element array in jquery

I have a jquery function that calls a controller which in turn calls a function that I extracted the data from the users table. I return an array cin all the data in the table. ID, username etc etc.. So mold date in jQuery and indeed the array is full. Ex. [{"Id_user": "21", "username": "cassy1994"}].
From this array I have to extract only the username. How can I do?
This is the Ajax function:
$(".apprezzamenti").click(function()
{
var id = $(this).attr('id');
var txt = "";
$.get("http://localhost/laravel/public/index.php/apprezzamenti/"+id,
function(data)
{
$(".modal-body-apprezzamenti>p").html(data);
});
});
If the json is parsed, your object is stored in an array, so:
data[0].username
If not (if it is a string), you need to parse it first:
data_parsed = JSON.parse(data);
// data_parsed[0].username
assuming data is where your response is stored, data[0].username should work. Example:
$(".modal-body-apprezzamenti>p").html(data[0].username);
To print all usernames:
var count = 0;
$.each($(".modal-body-apprezzamenti>p"), function() {
this.html(data[count].username);
count++;
]);
Hope this helps!
So, this is the problem. It's okay though, I realized that with this code I'm using can not seem to generate as many sections as there are users want to print and it shows me only the last username because it can generate only a paragraph in html. A possible solution which would it be?
This is the code:
$(".apprezzamenti").click(function()
{
var id = $(this).attr('id');
var txt = "";
$.get("http://localhost/laravel/public/index.php/apprezzamenti/"+id,
function(data)
{
data_parsed = JSON.parse(data);
for(var i=0; i<data_parsed.length; i++)
{
$(".modal-body-apprezzamenti>p").html((data_parsed[i].username));
}
});
});

jQuery Looping JSON Data

I have created APIs to retrieve data from my server and then I get the data with json format like this :
{
"items": [
{
"2013-03-28": 1771,
"2013-03-29": 1585,
"2013-03-30": 1582,
"2013-03-31": 1476,
"2013-04-01": 2070,
"2013-04-02": 2058,
"2013-04-03": 1981,
"2013-04-04": 1857,
"2013-04-05": 1806,
"2013-04-06": 1677,
"2013-04-07": 1654,
"2013-04-08": 2192,
"2013-04-09": 2028,
"2013-04-10": 1974,
"2013-04-11": 1954,
"2013-04-12": 1813,
"2013-04-13": 1503,
"2013-04-14": 1454,
"2013-04-15": 1957,
"2013-04-16": 1395
}
]
}
How do I looping with my json data dynamically using jQuery?
My code :
<html>
<head></head>
<body>
<script src="jquery-1.9.1.js"></script>
<script>
$(document).ready(function() {
$.ajax({
type : "GET",
url: "myurl.php",
cache: false,
dataType: "jsonp",
success:function(data){
if(data==''){
alert('Fail');
}else{
alert('Success');
}
}
})
});
</script>
</body>
</html>
How do I modify my jQuery to get data dynamically following the date that the data will change every day as in the example I wrote above data??
Thanks before...
There are a few things to consider with your example data, but in your case, the following will do the trick:
var importantObject = data.items[0];
for(var item in importantObject ){
var theDate = item;//the KEY
var theNumber = importantObject[item];//the VALUE
}
Here is a working example
But what does all this mean?...
First of all, we need to get the object that we want to work with, this is the list of dates/numbers found between a { } (which means an object) - an array is defined as [ ]. With the example given, this is achieved like so:
var importantObject = data.items[0];
because items is an array, and the object we want is the first item in that array.
Then we can use the foreach technique, which effectively iterates all properties of an object. In this example, the properties are the date values:
for(var item in importantObject ){ ... }
Because we are iterating the properties, item will be the property value (i.e. the date bit), so item is the date value:
var theDate = item;//the KEY
Finally we get the number part. We can access the value of any given object property by using the string value of the property index (relative to the object), like so:
var theNumber = importantObject[item];//the VALUE
If you already know which date you want the value for, then you can access it directly like so:
var myValue = data.items[0]["2013-04-16"];//myValue will be 1395 in this example
Using jQuery.each() loop through the items
$.each(data.items[0], function (key, value) {
console.log(key + ": " + value);
var date = key;
var number = value;
});
DEMO HERE
You can use the jQuery each function to do this. For example like this:
$.each(data, function(k, v) {
// Access items here
});
Where k is the key and v is the value of the item currently processed.
//get your detail info.
var detail = data.items[0];
$.each(detail, function(key, val) {
console.log(key + ": " + val);
}

Slickgrid not displaying JSON data from PHP unless I edit cells

As the title says, I have slickgrid getting/parsing JSON data from PHP, but while I can get it to update to the proper row count, nothing is displayed in a cell unless I edit it first. When I do, the correct data is displayed, but only for cells I have edited. Here is the relevant code:
$(function () {
$.getJSON("./test3.php", function(jsondata) {
$.each(jsondata, function(i, arr) {
var d = (data[i] = {});
$.each(arr, function(key, value) {
d[key] = value;
});
});
grid.updateRowCount();
grid.render();
});
grid = new Slick.Grid("#myGrid", data, columns, options);
//continues function prepping the grid
You might want to go for simpler implementation, there's no need to loop through all your data just dump your "jsondata" directly inside the SlickGrid Object creation.
As long as you have the "data" array into a JSON Object then you're fine. Something like this:
{ "data":[{"id":"84","name" : "Someone" ... ]}
// then pass it to your Slick Object.
grid = new Slick.Grid("#myGrid", jsondata, columns, options);
That's all... Oh and don't forget to have at least have a unique "id" on all rows
You can see example from this web site:
http://joeriks.com/2011/07/03/a-first-look-at-slickgrid-with-read-and-update-in-webmatrix/
I needed to call grid.invalidateRow() on all of the added rows.

How to send Javascript/jQuery array over URL paramter to PHP?

Here's my script, this works fine... send_array_to_other_page.html
$(function(){
//DECLARE ARRAY
var arr = new Array();
var i = 0;
$('#form').submit(function(e){
e.preventDefault();
var value = $('#box').val();
var index = arr.length;
var list = '';
//ADD VALUE TO ARRAY
arr[index] = value;
//OUTPUT VALUES IN ARRAY
for (var index in arr){
list+=index+': '+arr[index]+'<br/>';
$('#arrLength').html(arr.length);
}
//DISPLAY ARRAY
$('#display').html(list);
$('#form').get(0).reset(); //RESET FORM
});
$('#submit').click(function(){
window.location = 'send_array_to_other_page_2.php?list='+arr;
});
});
This doesn't. It outputs Array content lost. Id also like to point out the the url of this page is send_array_to_other_page_2.php. Its missing the ?list=
<?php
$arr = $_GET['list'];
echo 'The contents of the array are still... <br/>';
if(isset($arr)){
print_r($arr);
} else {
echo 'Array content lost';
}
?>
$(function(){
//DECLARE ARRAY
arr = new Array();
var i = 0;
$('#form').submit(function(e){
e.preventDefault();
var value = $('#box').val();
var index = arr.length;
var list = '';
//ADD VALUE TO ARRAY
arr[index] = value;
//OUTPUT VALUES IN ARRAY
for (var index in arr){
list+=index+': '+arr[index]+'<br/>';
$('#arrLength').html(arr.length);
}
//DISPLAY ARRAY
$('#display').html(list);
$('#form').get(0).reset(); //RESET FORM
});
$('#submit').click(function(){
window.location = 'send_array_to_other_page_2.php?list='+arr;
});
});
Try without the var arr to make it global, I don't believe the sub functions are parsing it.
Don't sent 'long' data over a URL. Most browsers have a length limit and it's very easy to exceed that and end up with corrupted data. For 'big' data, use a POST, which is not limited.
To send the array itself, just do an AJAX request and let jquery encode the array into JSON. You then handle it in PHP with json_decode() and you'll end up with a native PHP array.
Edit: Updated the JavaScript on jsfiddle based on your comment. On "submit", the array is saved at the "#form" element using the .data() method. On "click" of the "#submit" button, that data is retrieved and the url is build up.
The click event does fire before the submit event (at least in my Firefox 7), so your array is empty when concatenated to the URL string.
I put together some JavaScript on jsfiddle that might help. You do not really need to bind to the click event of the submit-button, just do the "redirect" in the submit handler function. You are building your string list there anyways. So there would no confusion what fires first, the click or the form submit event.
As for the serialization of your array, I used jQuery's .each() function but there is nothing wrong doing it by hand (if done correctly).
I could also imagine that the form is actually posted and this is why you do not see the "?list" search part of the URL.
If you don't need a complete redirect, why don't you send the data using jQuery.get()?

Categories