jQuery, Ajax getting data from a database - php

I am trying to get data from an SQL Database through jQuery, Ajax and PHP.
Here is the jQuery Code
$.ajax({
url: 'OpenQuiz.php',
data: '',
dataType:'json',
success: function(data) {
var one = data[0];
}
}
$(document).ajaxComplete(function(event,request,settings) {
alert("check");
}
Here are the json encode lines at the end of the PHP file called "OpenQuiz.php"
echo json_encode($QuizName);
echo json_encode($options);
echo json_encode($votes);
echo json_encode($row_num);
echo json_encode($percentage);
echo json_encode($TruncPercentage);
Please note:
$options, $votes, $Percentage and $TruncPercentage are all two-dimensional arrays.
$row_num is an integer.
$Quiz_Name is a single-dimensional array.
I find that the jQuery runs fine and the ajax request is called because the alert box for "check" shows up. The problem is that I dont know how to access the variables after they have been transferred. I know that it has something to do with data[0] but I don't really understand what "data[0]" means or what it represents. Basically how to I access the variables that I have sent using json_encode in the PHP file?

data[0] is the first json_encoded item in the array returned. You shouldn't json_encode everything separately, you should build an array and json_encode this.
$items = array('QuizName'=>$QuizName,'options'=>$options, ... ,'TruncPercentage'=>$TruncPercentage);
echo json_encode($items);
Then you retrieve with:
success: function(data) {
var qn = data.QuizName,
opt = data.options;
}
And so on for each item, with data.[whatever], and [whatever] being the name of the item you gave it in the array. I know I originally said to retrieve by index (data[0]), but I prefer to retrieve explicitly so that the code is more maintainable.
As a side note, you can eliminate the datatype:'json' declaration in your ajax call by simply setting the header correctly on the PHP side:
header('Content-type: application/json');
Placing that at the top of the document will force the server to recognize the page as json. Far more consistent and explicit than having jQuery look for it.

Related

Json result into PHP variable

I have a script that calls dat from my table and returns it in JSON format. How do I echo out the var nps and data as php variable.
My script:
$.ajax({
type: "POST",
url: "../charts/1-2-4-reports_nps.php?TAG=<?php echo $_SESSION['SectionVar'];?>&From=<?php echo $_SESSION['StartDate'];?>&To=<?php echo $_SESSION['EndDate'];?>",
cache: false,
success: function(data){
var nps = data[0].name;
console.log(nps);
var data = data['data'];
console.log(data);
$("#div1").append($("<div/>", { id: "div2", text: nps }));
}
});
My Json returns:
[{"name":"nps","data":[35]}]
Something like $nps = data['nps'] and echo the result of $nps.
I think initially you were confused about the contexts your code is running in. var nps = data['nps']; is JavaScript. It runs in the browser, and it runs after the page is loaded.
$nps by contrast is a PHP variable, and PHP runs on the server, and it runs before the page is loaded. In fact it is the PHP which creates the HTML, CSS, Script etc which is then downloaded to the browser. After that is downloaded, the JavaScript executes separately.
There is no direct connection between the two languages, other than you can use PHP to generate JavaScript (just like you use it to generate HTML).
Once you understand that, then you realise that to display your nps variable further down the page, you need to use JavaScript to manipulate the web page and insert the data.
The first issue to resolve with that is that the data being returned from the server is coming back as a string that looks like JSON, but not an actual JSON object. You can add
dataType: "json"
to your ajax options, and that tells jQuery to treat the returned data as an object instead of a string.
The next problem is that data is an array, containing a single object, and you were trying to read it like it was just a plain object.
So you get data out of it, and, as you requested, display each value in a new div which gets inserted into an existing div, you can do the following :
function success(data)
{
var nps = data[0].name;
var dt = data[0].data[0];
$("#div1").append($("<div/>", { id: "div2", text: nps }));
$("#div3").append($("<div/>", { id: "div4", text: dt }));
}
You can see a working example (with simulation of the ajax call, but using the correct data structure) here: https://jsfiddle.net/yukot05x/5/

Extracted json url from example.com/myjsonsql.php to jquery mobile fail to return value

i am a new php developers i was trying to create a simple system where i use php to extract database from mysql and use json in jquery mobile.
So here is the situation,
I've created a custom .php json (to extract data from mysql) on my website and i've successfully upload it onto my website eg: www.example.com/mysqljson.php
This is my code extracting mysql data `
header('content-type:application/json');
mysql_connect('localhost','root','') or die(mysql_error());
mysql_select_db('mydb');
$select = mysql_query('SELECT * FROM sample');
$rows=array();
while($row=mysql_fetch_array($select))
{
$rows[] = array('id'=>$row['id'], 'id'=>$row['id'], 'username'=>$row['username'], 'mobileno'=>$row['mobileno'], 'gangsa'=>$row['gangsa'], 'total'=>$row['total']);
}
echo json_encode($rows);`
Which in returns gives me the following json # http://i.imgur.com/d4HIxAA.png?1
Everything seems fine, but when i try to use the json url for extraction on jquery mobile it doesn't return any value.
i extract the json by using the following code;
function loadWheather(){
var forecastURL = "http://example.com/mysqljson.php";
$.ajax({
url: forecastURL,
jsonCallback: 'jsonCallback',
contentType: "application/json",
dataType: 'jsonp',
success: function(json) {
console.log(json);
$("#current_temp").html(json.id);
$("#current_summ").html(json.id.username);
},
error: function(e) {
console.log(e.message);
}
});
}
The json.id # #current_temp and json.id.username # #current_sum dint return any result on my jquery mobile page.
I suspected i didn't extracted the json url correctly, but im not sure, could anyone help me identify the problem?
Thank you.
jsonp expects a callback function to be defined in the json being retrieved - for ecample see here.
Your data print screen is actually plain old fashioned json, not jsonp.
So I see 2 options:
change the php data to render jsonp (this assumes you have control over data source).
change your jquery request to expect plain old fastioned json (this assumes client and server are on same domain, otherwise CORS error happen), e.g,,
$.get(forecastURL)
.then(function(json) {
console.log(json);
$("#current_temp").html(json.id);
$("#current_summ").html(json.id.username);
})
.fail(function(e) {
console.log(e.message);
});
First of all, you don't have to use jsonp to retrieve JSON. You could just do a simple Ajax Call. jQuery convert automatically your json string to a json object if your HTTP response contains the good Content-Type. And you did this good in your PHP call.
I think your problem comes from your json data analysis in your javascript success callback. The json generated is an array containing some user objects. In your code you don't work on one item of the array but you directly call .id or .username on the array. So javascript give you undefined values.
Here is an example displaying the data for the first item (index 0) of your json array. You have after that to choose for your own purpose how to treat your array objects but it's an example:
function loadWheather(){
var forecastURL = "http://example.com/mysqljson.php";
$.ajax({
url: forecastURL,
success: function(json) {
console.log(json);
// See, I use [0] to get the first item of the array.
$("#current_temp").html(json[0].id);
$("#current_summ").html(json[0].username);
},
error: function(e) {
console.log(e.message);
}
});
}

Script stops returning value on adding dataType: 'json'

I've been stuck on this for days now...the problem is this: I want to get multiple values from a PHP file through jQuery Ajax Json. but as soon as i add the dataType: 'json', to it, that's the end of things. I am using the given code:
PHP - check.php
$oid=1;
$f=10;
echo json_encode(array("oid" => $oid, "cid" => $f));
PS: THE ABOVE CODE IS INSIDE A LOOP THAT RETURNS MANY oid's AND cid's AT ONE TIME!
I've not included the part above or below the script cause it can compromise the security of my site.. :P but this in a nutshell is what the script does.
and here goes the javascript:
jQuery - scripts.js
$.ajax({
type: "POST",
dataType: 'json',
url: "check.php",
data: {anu:"bhav"}
}).done(function( result ) {
if(result!='0'){
var res=result.oid[0];
alert(res);
}
});
If it is inside a loop, you need to build an array with all your arrays in it.
for ($i=0; $i<count($array); $i++) {
$oid=1;
$f=10;
$results[] = array("oid" => $oid, "cid" => $f));
}
echo json_encode($results);
Add below code before echo json_encode(array("oid" => $oid, "cid" => $f));
header('Content-type: application/json');
Change below line
var res = result.oid[0];
As below and try:
var res = result.oid;
You wrote:
PS: THE ABOVE CODE IS INSIDE A LOOP THAT RETURNS MANY oid's AND cid's AT ONE TIME!
That one line of information is almost certain to be the ultimate cause of your problem.
Echoing multiple blocks of JSON one after the other does not result in one large block of valid JSON.
It results in a string that may look like JSON but is not valid, and will not produce any data if you pass it through a JSON parser.
Your PHP program should print one, and only one JSON block, generated by a single call to json_encode().
You can do this by copying the data into an array inside your loop, rather than echoing it there, and then doing your json_encode()` call on that big array, rather than the individual blocks of data.
Hope that helps explain things.

How to POST a multi-dimensional PHP array via a hidden input field using $.ajax?

I realise there are a few other questions regarding this and I have read them and attempted the solutions however they are not working for me. It may be because I am serializing the post twice because I am passing the entire form serialized by jQuery/JavaScript.
My PHP array is a 2 dimensional? one containing filenames:
$aDocumentFilesArrayFileName[0][0];
I generally have 1 dimensional arrays in my PHP so I pass them by using:
<input type="hidden" name="arrayName[]" value="$value[$i]"> // (while in a loop
I am not sure what syntax I should use when I reference the first array in terms of name and also what value I should use.
I've tried to use the value as: serialize($aDocumentFilesArrayFileName) and decode at the other end but I get an error saying string expected found array?
** EDIT **
I think I could have made the question clearer but just to clarify. Here is my jQuery Ajax submit function:
var conflictData = $("input, select", conflictsTable.fnGetNodes()).serialize(); // fnGetNodes is just a datatables function to go through every row in a table - don't worry about that
$.ajax(
{
type: 'POST',
url: 'sqlHandleConflictsDocumentRegister.php?node='+nodeType+'&id='+nodeId,
cache: false,
data: conflictData,
success: function(result)
{
// Do stuff here
}
});
I have tried the solution to use json_encode rather than serialize on my PHP input statement. That isn't working. Here is the exact code I use in the PHP form. Please be aware that this line is within a loop that occurs for each row of the table in the form.
<input type="hidden" name="arrayFileName[]" value="<?php echo json_encode($aDocumentFilesArrayFileName[$i]); ?>">
Here is the code I use on the PHP ajax script:
$fileNames = json_decode($_POST['arrayFileName']);
Error is:
json_decode() expects parameter 1 to be string, array given in C:\wamp\www\document\sqlHandleConflictsDocumentRegister.php on line 65
Is the problem that I am serializing (in JavaScript) varying dimensions of array data?
My other inputs are from rows that have simple array data (one value for each row) and they work fine. This particular array input has an unlimited number of filenames associated per table row, so the input value is an array.
I also pass the value of the quantity of files (per table row) in another input. Perhaps I can use this to help extract the array on the other side.
<input type="hidden" name="quantityFiles[]" value="<?php echo $aDocumentQuantityFiles[$i]; ?>">
** UPDATE **
I used alert(conflictData) and found that the array data is fine apart from it is empty for the arrayFileName field.
If I echo json_encode($aDocumentFilesArrayFileName[$i]) then I get the expected result.
Hence, it looks as if the jQuery serialize() is destroying this data. Perhaps there is a way I can prepare the data variable better for ajax submission?
** UPDATE 2 **
Thank you all for your assistance and contributions to the answer. I was already using json_encode to get the data into javascript for operating on it there so I have abandoned using an input field to serialize and send the data and instead directly used the data parameter of $.ajax to send the array for processing.
As there was no distinctly correct solution provided I have posted a solution below and will mark it as the correct answer since I am now able to obtain the multidimensional array data in the destination PHP file.
Serialize over ajax(user involved) opens a range of security vulnerability's because the user could make you unserialize a object and try to execute that.
Try to use the appropriate function json, http://php.net/manual/en/book.json.php. Json is the way to go for using with Ajax(Javascript).
You can use json_encode function of php to send php array to javascript.
Please use
echo json_encode($phpArray);
and you have to set last parameter of $.post() is 'json' if you are using $.post() method or if you are usig $.ajax() method than you have to set dataType: 'json'
http://api.jquery.com/jQuery.post/
jQuery serialize works fine for regular arrays but not multidimensional arrays in this scenario. It seems to corrupt when mixing the data from various arrays.
Solution:
json_encode the multidimensional PHP array data and pass to javascript using the code below:
<script>
var aQuantityFiles = <?php echo json_encode($aDocumentQuantityFiles); ?>; // this is a regular array which is also related to the multidimensional array
var aDocumentFilesArrayFileName = <?php echo json_encode($aDocumentFilesArrayFileName); ?>; // this is a multidimensional array
</script>
Use the data parameter in the $.ajax request to individually pass the prepared javascript variable:
$.ajax(
{
type: 'POST',
url: 'sqlHandleConflictsDocumentRegister.php?node='+nodeType+'&id='+nodeId,
cache: false,
data:
{
aQuantityFiles: aQuantityFiles,
aDocumentFilesArrayFileName: aDocumentFilesArrayFileName
},
success: function(result)
{
//Do Something
}
});
On the destination PHP side it is now very simple (no need to decode)
<?php
$aQuantityFiles = $_POST['aQuantityFiles'];
$fileNames = $_POST['aDocumentFilesArrayFileName'];
for ($i = 0; $i < $numberRows; $i++)
{
// This is the bigger loop cycling through the rows of data which contain the multiple files
for ($j = 0; $j < $quantityFiles; $j++)
{
// Echo to illustrate that data is extracted multidimensionally as expected
echo $fileNames[$i][$j];
echo "<br/>";
}
}
?>
Optional
Now the multidimensional array data is accepted by the destination PHP file but you may need to bundle the additional form data with the extended array data before you send it with $.ajax. I found out how to do this using the $.param function from the site below.
http://www.jblotus.com/2011/07/12/combine-serialized-form-post-data-with-arbitrary-object-in-jquery/

How can I send an array to php through ajax?

I want to send an array constructed in javascript with the selected values of a multiple select. Is there a way to send this array to a php script using ajax?
You might do that with $.post method of jQuery (for example) :
var myJavascriptArray = new Array('jj', 'kk', 'oo');
$.post('urltocallinajax', {'myphpvariable[]': myJavascriptArray }, function(data){
// do something with received data!
});
Php will receive an array which will be name myphpvariable and it will contain the myJavascriptArray values.
Is it that ?
You can post back to your server with XML or JSON. Your javascript will have to construct the post, which in the case of XML would require you to create it in javascript. JSON is not only lighterweight but easier to make in javascript. Check out JSON-PHP for parsing JSON.
You might want to take a look at Creating JSON Data in PHP
IIRC, if PHP sees a query string that looks like http://blah.com/test.php?var[]=foo&var[]=bar&var[]=baz, it will automatically make an array called $var that contains foo, bar and baz. I think you can even specify the array index in the square brackets of the query string and it will stick the value in that index. You may need to URL encode the brackets... The usual way this feature is used is in creating an HTML input field with the name "var[]", so just do whatever the browser normally does there. There's a section in the PHP documentation on array variables through the request.
You may be looking for a way to Serialize (jQuery version) the data.
jQuery 1.4 was updated to use the PHP syntax for sending arrays. You can switch it into the old style by using:
here is the synatax:
jQuery.ajaxSetting.traditional = true;
here is the example
$.ajax({
traditional: true,
type: "post",
url: myURL,
dataType: "text",
data: dataToSend, //this will be an array eg.
success: function(request) {
$('#results').html(request);
} // End success
}); // End ajax method
You can create an array and send it, as Meador recommended:
(following code is Mootooled, but similar in other libraries / plain old JS)
myArray.each(function(item, index) myObject.set('arrayItems['+index+']', item);
myAjax.send(myObject.toQueryString());
That will send to php an array called arrayItems, which can be accessed through $_POST['arrayItems']
echo $_POST['arrayItems'] ;
will echo something like: array=>{[0]=>'first thing', [1]=> second thing}

Categories