jquery ajax() issue while printing array with each() - javascript

In my code I am returning an php array containing records of 7 Students. With jquery ajax() I want to print these records on success function.
DB table Students
+---------------------------+
| name | fathername | Email |
+---------------------------+
submit.php
$query=mysql_query("SELECT * from Students LIMIT 0,6");
$row= array();
$row=mysql_fetch_array($query);
return json_encode($row);
index.php
<script>
$(function(){
$("#form1").submit(function(event){
event.preventDefault();
$.ajax({
url:'submit.php',
type:'GET',
data:$(this).serialize(),
success:function(result){
$.each(result,function(){
$('.StudentName').text(result["name"]);
$('.FatherName').text(result["fathername"]);
$('.Email').text(result["email"]);
});
}
});
});
});
</script>
<div class="StudentName"></div>
<div class="FatherName"></div>
<div class="Email"></div>
EDIT
I tried to return only 1 result from php and it works i.e.
echo json_encode(mysql_fetch_array($query));
When I return all 6 records the jquery function dont execute i.e.
while($result=mysql_fetch_array($query))
{
echo json_encode($result);
}

There's difference between PHP arrays and JS arrays, you can't simply pass the PHP array to your javascript, so instead you should first json_encode it and send it to js.
This will convert your PHP array to JSON array, eg:
array(3) {
[0]=>
string(3) "foo"
[2]=>
string(3) "baz"
[3]=>
string(5) "blong"
}
to
string(33) "{"0":"foo","2":"baz","3":"blong"}"
So try -
return json_encode($row);
and then when you catch the response, use parseJSON:
result = jQuery.parseJSON(result);
$.each(result,function(){
$('.StudentName').text(result.name);
$('.FatherName').text(result.fathername);
$('.Email').text(result.email);
});
Edit:
Another thing, instead of return json_encode($row); write echo json_encode($row);
Edit 2
(to send all 6 records)
$final = array();
while($result=mysql_fetch_array($query))
{
array_push($final,$result);
}
echo $final;

function success(result){
$.each(result,function(){
$('.StudentName').text(result["name"]);
looks problematic. There doesn't really seem to be a reason to loop over the result, as you assign all of its contents to the same elements in the page.
However, assuming that result is an array of objects (like SQL queries usually produce it), then it should be
function(result){
$.each(result,function(obj) {
// missing parameter!!! ^^^
$('.StudentName').text(obj["name"]);
// access that here: ^^^
Also do a console.log(result) or simply browse the request URL to check whether the PHP scripts yields the expected response.

Here is an example of parsing JSON that may help you - http://jsfiddle.net/Su6QR/
Given that example, change your AJAX function -
$.ajax({
url:'submit.php',
type:'GET',
data:$(this).serialize(),
success:function(result){
var members = $.parseJSON(result);
$.each(members, function() {
var newStudent = '<span>' + this['name'] + '</span>';
var newFather = '<span>' + this['father'] + '</span>';
var newEmail = '<span>' + this['email'] + '</span>';
$('.StudentName').append(newStudent);
$('.FatherName').append(newFather);
$('.Email').append(newEmail);
});
}
});
This should return all of the data and place them into the divs that you have created. The formatting will not be what you want, but you should be able to fix that pretty easily.

This might help you.
Your AJAX
$("#form1").click( function(e){
var Somename = { };
$.each($('#form1').serializeArray(), function() {
Somename [this.name] = this.value;
});
e.preventDefault();
$.ajax({
type: "GET",
url: "submit.php",
data: { upddt_empID: upddt_empID, somevariable: "YES" },
success: function(data) {
alert('Successfull');
}
});
Your PHP
if(isset( $_REQUEST['somevariable'] ) )
{
$selItem = YourFunctionName( $_REQUEST['Somename ']['here your textbox id'], $_REQUEST['Somename ']['here your textbox id'],'yourtablename');
}
Your Query
function YourFunctionName(tablename)
{
$qry = "SELECT * FROM $tablename";
$result = mysql_query($qry);
return $result;
}

Related

Ajax call - PHP return value

I want php file to return data (from the database) on ajax call. Ajax call returns an error alert everytime. I tried everything, but have no idea how to return array from PHP to ajax call
So far, I made this..
ajax call
function dohvatiPrveTriAkcije(id){
var url = 'http://localhost/ljekarna/model/akcija.php';
$.ajax({
type: "POST",
url: url,
cache: false,
data: { "kategorija": id},
dataType: "json",
success: function (data) {
document.getElementById("kat_id").innerHTML += 'aaa';
},
error: function () {
alert('Pojavila se greška pri dohvacanju akcija za odabranu kategoriju');
}
});
return null;
}
php class
<?php
require_once 'baza_model.php';
$akcija = new Akcija();
if (isset($_GET['kategorija'])) {
echo $_GET['kategorija'];
$akcije = $akcija->dohvatiPrveTriAkcijeZaKategoriju($_GET['kategorija']);
echo $akcije;
}
class Akcija{
private $baza;
static function dohvatiPrveTriAkcijeZaKategoriju($kategorija){
$baza = new Baza();
$akcije = array();
$upit = 'SELECT lijek.naziv, akcija.postotak, akcija.datum_zavrsetka FROM akcija join lijek on akcija.lijek = lijek.id
join kategorija on lijek.kategorija = kategorija.id
where akcija.datum_zavrsetka > CURDATE() AND kategorija.id = ' . $kategorija . ' AND akcija.status = 1
ORDER BY akcija.datum_zavrsetka ASC LIMIT 3';
$rez = $baza->selectDB($upit);
while($red = $rez->fetch_assoc()){
echo "id: " . $red["id"];
$akcije[] = $red;
}
return $akcije;
}
}
I also tried this...
You need a json formatted string returned by the server. Use json_encode() instead of trying to echo out your array (which is what's giving you your array to string error).

Format Json returned by AJax call and assign it to javascript variable

I have script that return this from the server using ajax call
//ajax call
var comment_frm = $('#comment_form');
comment_frm.submit(function (ev) {
$.ajax({
type: comment_frm.attr('method'),
url: comment_frm.attr('action'),
data: comment_frm.serialize(),
success: function (data) {
if (data == 1){
$("#success_message").show();
$('#comment_form').trigger("reset");
}
},
error: function (jXHR, textStatus, errorThrown) {
alert(errorThrown);
}
});
//prevent the page from loading
ev.preventDefault();
});
[{"commentID":"5","name":"name 1","comment":"comment 1","comment_time":"1460652379","blog_unique_id":"19","comment_status":"1"},{"commentID":"6","name":"name 2","comment":"comment 2","comment_time":"1460652387","blog_unique_id":"19","comment_status":"1"},{"commentID":"7","name":"name 3","comment":"comment 3","comment_time":"1460652416","blog_unique_id":"19","comment_status":"1"},{"commentID":"8","name":"name 4","comment":"comment 4","comment_time":"1460652425","blog_unique_id":"19","comment_status":"1"},{"commentID":"9","name":"name 5","comment":"comment 5","comment_time":"1460652433","blog_unique_id":"19","comment_status":"1"}]
I want to format it to look like this and assign the json result to a javascript variable
var comment_array = {"Comments": [{"commentID":"5","name":"name 1","comment":"comment 1","comment_time":"1460652379","blog_unique_id":"19","comment_status":"1"},{"commentID":"6","name":"name 2","comment":"comment 2","comment_time":"1460652387","blog_unique_id":"19","comment_status":"1"},{"commentID":"7","name":"name 3","comment":"comment 3","comment_time":"1460652416","blog_unique_id":"19","comment_status":"1"},{"commentID":"8","name":"name 4","comment":"comment 4","comment_time":"1460652425","blog_unique_id":"19","comment_status":"1"},{"commentID":"9","name":"name 5","comment":"coment 5","comment_time":"1460652433","blog_unique_id":"19","comment_status":"1"}]}
//php code
$operation = $_POST['operation'];
if($operation == 'add_comment'){
$name = $_POST['name'];
$comment = $_POST['comment'];
$blog_id = $_POST['blog_id'];
$comment_status = 1;
if ($me->add_comment($name, $comment, $blog_id)){
//get the comment
$comment_array = $me-> fetch_moderated_comment($blog_id);
echo json_encode($comment_array);
}else{echo 10;}
}
I will also love to know how to read get that from the call... Can someone please help me
Working Example
You could assign a variable to hold your new 'Comments' array and then push to it:
var a = [{"commentID":"5","name":"name 1","comment":"comment 1","comment_time":"1460652379","blog_unique_id":"19","comment_status":"1"},{"commentID":"6","name":"name 2","comment":"comment 2","comment_time":"1460652387","blog_unique_id":"19","comment_status":"1"},{"commentID":"7","name":"name 3","comment":"comment 3","comment_time":"1460652416","blog_unique_id":"19","comment_status":"1"},{"commentID":"8","name":"name 4","comment":"comment 4","comment_time":"1460652425","blog_unique_id":"19","comment_status":"1"},{"commentID":"9","name":"name 5","comment":"comment 5","comment_time":"1460652433","blog_unique_id":"19","comment_status":"1"}]
var b = {"Comments": []};
for (var prop in a) {
b.Comments.push(a[prop]);
}
echo json_encode(['Comments' => $comment_array]);
If I understand correctly, just wrap the result in an object literal:
vat result = {"Comments": comment_frm};

Passing a PHP variable to JavaScript For AJAX Request

So my workflow is that onClick of an list element, my JS initiates a PHP AJAX request to build a card object. The $content is a card (similar to KickStarter) of topic data. What I'm trying to do is a pass the 'topic_id' of each topic-instance so that I can then use it in the success function, to then initiate ANOTHER AJAX request (but to Discourse).
With attempt 2), I get a null when viewing its value in the web inspector.
The AJAX requests (the console.log() of the variable I want to get returns a blank line in the web console):
$.post( "/wp-content/mu-plugins/topic-search.php", { topicID: $topicFilter, filterBy: $sortByFilter },
function( data ) {
console.log(topic_id);
data = data.trim();
if ( data !== "" ) {
//get the participants data for avatars
$.getJSON('http://ask.example.com/t/' + topic_id + '.json', function() {
The end of topic-search.php, which echoes out the built up card. Script is supposed to return the topic_id variable for use in the success function.
}
//One attempt: echo $content; //
//Another attempt: echo json_encode(array('data' => $content, 'topic_id' => $row['topicid']));//
}
?>
<script>
var topic_id = "<?php echo $row['topicid'] ?>";
</script>
Try this:
In php
$inputJson = file_get_contents('php://input');
$input = json_decode($inputJson, true); //Convert JSON into array
In javascript
var $url = '/wp-content/mu-plugins/topic-search.php';
var $json = JSON.stringify({topicID: $topicFilter, filterBy: $sortByFilter});
$.ajax({
url: $url,
type: "POST",
data: $json,
dataType: "json",
success: function(data){//you will have the body of the response in data
//do something
},
error: function(data){
//do something else
}
});
EDIT:
This will request $url with the $json data. You will have it available on $input on the server side as an array. You can then on the server prepare a response with a json body that you will have available on the success function as the data variable.

Return php variable?

I have made a little AJAX-script for my site, which executes a php-script in another file on submission. I managed to echo out the result in the original file with the AJAX-function, but I have not managed to transfer a variable from the php file to the original one.
I need this variable in order to add an event listener which will look for changes in that particular variable (not sure how to do that either).
Here's are what you are looking for it's working:-
Put this in your forsok.php
<div id="input">
<input type="text" id="number" name="value">
<b id="show_result"></b>
</div>`
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
$('#number').on('keyup',function(e){
if(e.which == 13){
var get_var_name = $(this).val();
$.get('result.php',{number:get_var_name},function(data,status){
if(status == 'success'){
alert(data['show']);
$('#show_result').text(data['show']);
}else{
alert('Nothing');
}
});
}
});
</script>
For hej.php:-
<?php
$one=$_GET['number'];
if(empty($one)) {
echo "Can't be blank";
$a['result']='null';
$a['error'] = 'No value!!';
} else {
if(is_numeric($one)) {
$show=$one*2;
$arr = array(
'show'=>$show
);
header('Content-Type:application/json');
echo json_encode($arr);
exit();
// echo $show;
} else {
echo "NaN";
$a['result']='null';
$a['error']='nan';
}
}
?>
First create an array of what should be the output. JSON encode that array and then you can parse the output in your ajax success handler. Like in your php file output like:
echo json_encode(array(
'result' => 'null',
'error' => 'nan'
));
Then in you ajax success turn the json into an object and parse data as you want:
success: function (data, textStatus, jqXHR) {
var obj = $.parseJSON(data);
$('#utmatning').html(obj.result); // result value from your json return
$('#utmatning').append(obj.error); // error value from your json return
}
At last of your php file, add,
json_encode($a);
In ajax success,
success: function(html) {
$.each(html, function(index, element) {
alert(element.result);
alert(element.error);
//append to which ever div you want.
});
}
Now with this, you can get n number of array indexes from php
Instead of echoing strings here and there in in hej.php it might better to return JSON data to your ajax call. so you can evaluate if an error occured, which error it is or which valid result has been returned.
hej.php:
<?php
$one=$_GET['value'];
if(empty($one)) {
$a['result']='null';
$a['error'] = 'No value!!';
} else {
if(is_numeric($one)) {
$a['result']=$one*2;
$a['error']='ok';
} else {
$a['result']='null';
$a['error']='nan';
}
}
die(json_encode ($a));
?>
if $value was 1 that would return
{"result":"2","error":"ok"}
In forsok.php you could check the reults and act accordingly
...
$.ajax({
type: "GET",
dataType: "json",
url: url,
data: $("#idForm").serialize(), // serializes the form's elements.
success: function(response)
{
if (response.error=='ok'){
$('#utmatning').html(response.result); // show response from the php script.
}
else{
console.log(response.result); // handle the error
}
}
});
...
Regards,
Stefan

Update and get the data in the same ajax call

I am trying to update and get the updated row at a time from database in ajax call
JS in ready function
$("button[name='teacher_lock_exam']").on(ace.click_event, function () {
var current_exams_id = $(this).attr('id');
bootbox.confirm("Are you sure you want to lock the exam? <br/><br/>" +
"Locked exam cannot be modified until exam committee unlock it.", function (result) {
if (result) {
lock_exam(current_exams_id);
bootbox.alert("Your Exam has been Locked !<br/><br/> Contact with Exam committee to modify that exam again.");
}
});
});
function lock_exam(current_exams_id) {
$.ajax({
url: "teacher_internal_exam_management/lock_exam/" + current_exams_id,
type: "POST",
dataType: "json",
success: function (row) {
alert('success');
alert(row[0].access_status);
}
});
}
My teacher_internal_exam_management controller
public function lock_exam($current_exams_id)
{
$this->load->model('teacher_internal_exam_management_model');
$this->teacher_internal_exam_management_model->lock_exam($current_exams_id);
echo (json_encode($this->teacher_internal_exam_management_model->get_exam_details($current_exams_id)));
}
My teacher_internal_exam_management_model Model
function lock_exam($current_exam_id, $data)
{
$this->db->query("update current_exams set access_status = 'locked' where current_exams_id='".$current_exam_id."'");
}
function get_exam_details($exam_id)
{
$query = $this->db->query("select * from current_exams
where
current_exams_id = '" . $exam_id . "'
");
return $query->result();
}
Now the ajax call is updating the data but the row is not returned by the echo in the controller.Means the success function of ajax is not running. Why this is not working? Is there any problem in the code?
The very last line of your model:
return $query->result();
http://ellislab.com/codeigniter/user-guide/database/results.html
This function returns the query result as an array of objects, or an empty array on failure.
This is returning an array of objects.
You have to convert it appropriately -
return $query->result_array();
According to the php manual at http://www.php.net/manual/en/class.mysqli-result.php, I do not see a result() method for the type mysqli_result. I think you need to use
return $query->fetch_all();
instead of
return $query->result();

Categories