load json data from database into slideToggle - php

I'm trying to load applicants info that i get from database (fisrt name, lasta name, ID number) in a slidetoggle that appears after clicking "Display applicants" button.
My code keeps showing ERROR DETECTED message, after I click the button "display applicants" an slidetoggle should appear and the json data be shown on the slide. can someone give me some directions about what i'm doing wrong here.
Query:
if(isset($_GET['id'])){
$id_oferta = $_GET['id'];
$sql ="SELECT postulacion.* FROM postulacion WHERE id_oferta = '". $id_oferta ."'";
$listapostulantes = mysql_query($sql) or die(mysql_error());
$return_arr= array();
$num = mysql_num_rows($listapostulantes);
if($num > 0){
while($row = mysql_fetch_array($listapostulantes, MYSQL_ASSOC)){
$return_arr[] = $row;
}
echo json_encode($return_arr);
}
}
Script:
$(document).ready(function(){
$('.myslide').hide();
$(".postulantes").on('click', function(e){
e.preventDefault();
if($(this).parent().next().css('display') == 'none'){
$('.myslide').hide('fast');
$(this).parent().next().slideToggle('slow');
var link = $(this).attr('href').split('&');
var idd= link[1].match(/id=([0-9]+)/)[1];
$.ajax({
url: link[0],
type: 'GET',
dataType:'json',
data:{'id': idd},
success:function(data){
// console.log();
var htmlStr = '';
$.each(data, function(key, value){
htmlStr += '<p>' + value.rut_usuario + '</p>';
});
$(".myslide").html(htmlStr);
},
error: function(){
$("#listaofertas").html("ERROR DETECTED");
//console.log();
}
});
}
});
});
json

Your response, as shown under the Respuesta tab, includes not only JSON, but some HTML as well. Get rid of the html, and make sure only JSON is returned, and then jquery should execute your success callback

Use this to split the response and "cut out" the html part.
$splitted = explode("<!DOCTYPE HTML>",json_encode($return_arr));
echo $splitted[0];

Related

How to pass php array to ajax function

So I would like to pass the php array values from this form id to my ajax form. Everything works fine except that it will only display the (1) id number.
Here is my form code: I am passing the $row[topic_id'] as a value to get the id for jquery.
public function forumview($query){
$stmt = $this->db->prepare($query);
$stmt->execute();
$results = $stmt->fetchAll();
if($stmt->rowCount()>0){
foreach($results as $row){
echo '<tr>';
echo '<td style="color: #333;"><span class="pull-right">';
//Problem is here with the $row['topic_id'] portion
if(isset($_SESSION['user_session'])){
echo '<a href="#" class="upVoteArrow"
onclick="upVoteIncrementValue('.$row['topic_id'].');">';
}else{
echo '<a href="#" id="loginForm" class="upVoteArrow" data-
toggle="modal" data-target="#loginModal"><i class="fa fa-arrow-up"></i>
</a>';
}
echo '<span id="voteCount">'.$this->cleanNumber($row['topic_likes']).'</span>';
}
Here is my Ajax call to send the info to my php file
function upVoteIncrementValue(postID){
event.preventDefault();
//var upVoteIncrement = $("#upVoteIncrement").val(); //not needed
$.ajax({
type: "POST",
url: "voting.php",
data: {
"upVoteIncrement": postID,
},
dataType: "json",
cache: false,
success: function(response){
if(response){
var response = $.trim(response);
if(response){
$('#voteCount').html(response);
}
else {
return false;
}
}
}
});
Then here is the php file that handles the call.
if(isset($_POST['upVoteIncrement'])){
$upVoteIncrement = $_POST['upVoteIncrement'];
$stmt = $conn->prepare('UPDATE topics SET topic_likes = topic_likes+1 WHERE topic_id = :id LIMIT 1');
$stmt->bindParam(':id', $upVoteIncrement);
$stmt->execute();
$upVote = $conn->prepare('SELECT topic_likes FROM topics WHERE topic_id = :id LIMIT 1');
$upVote->bindParam(':id', $upVoteIncrement);
$upVote->execute();
$upVoteCount = $upVote->fetchAll();
if($upVote->rowCount() > 0){
foreach($upVoteCount as $row){
$up = $row['topic_likes'];
$results[] = $up;
//exit(); //not needed
}
}
echo json_encode($results);
}
Essentially I am just making a simple up vote system that the user clicks on and it updates the database incrementing by 1. It increments the values and everything works except it will only increment it for the last posted item. So even if I upvote on a topic from earlier it will only add 1 vote to the last inserted topic. Any advice is much appreciated, thanks in advance!
If your using a loop to populate the row id, which it looks like you are here are your problems.
The loop is creating a hidden input element on every iteration of the loop and you are not changing the id of the element. So you will have a bunch of elements all with the same id. That will cause you problems a few different ways.
I changed your PHP code so that each element will have it's own id. I also changed the your javascript function so that the id value is passed to the function itself.
See if this helps:
PHP:
if(isset($_SESSION['user_session'])){
echo '<input type="hidden" id="' . $row['topic_id'] . '" name="upVoteIncrement"
value="' . $row['topic_id'] . '"><a href="#" class="upVoteArrow"
onclick="upVoteIncrementValue(' . $row['topic_id'] . ');">';
}
JS:
function upVoteIncrementValue(postID){
event.preventDefault();
//var upVoteIncrement = $("#upVoteIncrement").val(); //Don't need this anymore.
$.ajax({
type: "POST",
url: "voting.php",
data: {
"upVoteIncrement": postID, //Use the passed value id value in the function.
},
dataType: "html",
cache: false,
success: function(response){
if(response){
var response = $.trim(response);
if(response){
$('#voteCount').html(response);
}
else {
return false;
}
}
}
});
Hope it helps!
I also want to point out that in the code below:
if($upVote->rowCount() > 0){
foreach($upVoteCount as $row){
$up = $row['topic_likes'];
echo $up;
exit();
}
}
You are exiting the script on the first iteration of the loop and you will only ever get one result back.
If you need to return an array of data it should look like this:
if($upVote->rowCount() > 0){
foreach($upVoteCount as $row){
$up = $row['topic_likes'];
$results[] = $up;
//exit();
}
}
echo json_encode($results);
You will then need to set your datatype to json instead of html.
The response in your ajax will now be an array. To see the array:
success: function(response){
if(response){
console.log(response); //Look in your console to see your data.
var response = $.trim(response);
if(response){
$('#voteCount').html(response);
}
else {
return false;
}
}
}
The problem is that in the event handler you addressing element by id, and it's not always the same that you click on.
function upVoteIncrementValue(){
event.preventDefault();
// Always will be last inserted element
var upVoteIncrement = $("#upVoteIncrement").val();
You can use event to get valid element. It's default argument that passed to handler, but remember to define it without braces:
<input onclick="upVoteIncrementValue" />
Then your handler:
function upVoteIncrementValue(event){
event.preventDefault();
var upVoteIncrement = $(event.target).val();
Also if you have several elements with the same ID it's invalid HTML, at least it will hit warning at https://validator.w3.org/ .
So you should set id arg for your element only in case if it's unique, and having this mindset will help you to not hit similar issue again.

Can not retrieve data json from the server using ajax on cordova

I tried to call / search data by ID , from the server using ajax in cordova , but when I click to display the data " undefined" , what's wrong ???
This my html
<input type="text" id="result" value=""/>
<button>get</button>
<div id="result2"></div>
function get (){
var qrcode = document.getElementById ("result").value;
var dataString="qrcode="+qrcode;
$.ajax({
type: "GET",
url: "http://localhost/book/find.php",
crossDomain: true,
cache: false,
data: dataString,
success: function(result){
var result=$.parseJSON(result);
$.each(result, function(i, element){
var id_code=element.id_code;
var qrcode=element.qrcode;
var judul=element.judul;
var hasil2 =
"QR Code: " + qrcode + "<br>" +
"Judul: " + Judul;
document.getElementById("result2").innerHTML = hasil2;
});
}
});
}
This my script on server
include "db.php";
$qrcode= $_GET['qrcode'];
$array = array();
$result=mysql_query("select * from book WHERE qrcode LIKE '%{$qrcode}%'");
while ($row = mysql_fetch_array($result)) { //fetch the result from query into an array
{
$array[] =$row['qrcode'];
$array[] =$row['judul'];
$array[] =$row['jilid'];
}
echo json_encode($array);
}
try to change your parameter in calling ajax
var dataString = {qrcode : qrcode };
Change your php code as below
include "db.php";
$qrcode= $_GET['qrcode'];
$array = array();
$result=mysql_query("select * from book WHERE qrcode LIKE '%{$qrcode}%'");
while ($row = mysql_fetch_array($result)) { //fetch the result from query into an array
{
$array[] =['qrcode'=>$row['qrcode'],'judul'=>$row['judul'],'id_code'=>$row['jilid']];
}
echo json_encode($array);
}
RESOLVED the problem is. I try to replace with this script and the result was the same as I expected.
while ($row = mysql_fetch_object($result)){
$array[]=$row++;
}
echo json_encode($array);

How to pass mysql result as jSON via ajax

I'm not sure how to pass the result of mysql query into html page via ajax JSON.
ajax2.php
$statement = $pdo - > prepare("SELECT * FROM posts WHERE subid IN (:key2) AND Poscode=:postcode2");
$statement - > execute(array(':key2' => $key2, ':postcode2' => $postcode));
// $row = $statement->fetchAll(PDO::FETCH_ASSOC);
while ($row = $statement - > fetch()) {
echo $row['Name']; //How to show this in the html page?
echo $row['PostUUID']; //How to show this in the html page?
$row2[] = $row;
}
echo json_encode($row2);
How to pass the above query result to display in the html page via ajax below?
my ajax
$("form").on("submit", function () {
var data = {
"action": "test"
};
data = $(this).serialize() + "&" + $.param(data);
$.ajax({
type: "POST",
dataType: "json",
url: "ajax2.php", //Relative or absolute path to response.php file
data: data,
success: function (data) {
//how to retrieve the php mysql result here?
console.log(data); // this shows nothing in console,I wonder why?
}
});
return false;
});
Your json encoding should be like that :
$json = array();
while( $row = $statement->fetch()) {
array_push($json, array($row['Name'], $row['PostUUID']));
}
header('Content-Type: application/json');
echo json_encode($json);
And in your javascript part, you don't have to do anything to get back your data, it is stored in data var from success function.
You can just display it and do whatever you want on your webpage with it
header('Content-Type: application/json');
$row2 = array();
$result = array();
$statement = $pdo->prepare("SELECT * FROM posts WHERE subid IN (:key2) AND Poscode=:postcode2");
$statement->execute(array(':key2' => $key2,':postcode2'=>$postcode));
// $row = $statement->fetchAll(PDO::FETCH_ASSOC);
while( $row = $statement->fetch())
{
echo $row['Name'];//How to show this in the html page?
echo $row['PostUUID'];//How to show this in the html page?
$row2[]=$row;
}
if(!empty($row2)){
$result['type'] = "success";
$result['data'] = $row2;
}else{
$result['type'] = "error";
$result['data'] = "No result found";
}
echo json_encode($row2);
and in your script:
$("form").on("submit",function() {
var data = {
"action": "test"
};
data = $(this).serialize() + "&" + $.param(data);
$.ajax({
type: "POST",
dataType: "json",
url: "ajax2.php", //Relative or absolute path to response.php file
data: data,
success: function(data) {
console.log(data);
if(data.type == "success"){
for(var i=0;i<data.data.length;i++){
//// and here you can get your values //
var db_data = data.data[i];
console.log("name -- >" +db_data.Name );
console.log("name -- >" +db_data.PostUUID);
}
}
if(data.type == "error"){
alert(data.data);
}
}
});
return false;
});
In ajax success function you can use JSON.parse (data) to display JSON data.
Here is an example :
Parse JSON in JavaScript?
you can save json encoded string into array and then pass it's value to javascript.
Refer below code.
<?php
// your PHP code
$jsonData = json_encode($row2); ?>
Your JavaScript code
var data = '<?php echo $jsonData; ?>';
Now data variable has all JSON data, now you can move ahead with your code, just remove below line
data = $(this).serialize() + "&" + $.param(data);
it's not needed as data variable is string.
And in your ajax2.php file you can get this through
json_decode($_REQUEST['data'])
I would just..
$rows = $statement->fetchAll(FETCH_ASSOC);
header("content-type: application/json");
echo json_encode($rows);
then at javascript side:
xhr.addEventListener("readystatechange",function(ev){
//...
var data=JSON.parse(xhr.responseText);
var span=null;
var i=0;
for(;i<data.length;++i){span=document.createElement("span");span.textContent=data[i]["name"];div.appendChild(span);/*...*/}
}
(Don't rely on web browsers parsing it for you in .response because of the application/json header, it differs between browsers... do it manually with responseText);

loop over the PHP data Returned to jquery AJAX Call

below is my $.ajax call to php
$(document).ready(function() {
$('ul.sub_menu a').click(function(e) {
e.preventDefault();
var txt = $(this).attr('href');
$.ajax({
type: "POST",
url: "thegamer.php",
data:{send_txt: txt},
success: function(data){
$('#container').fadeOut('8000', function (){
$('#container').html(data);
$('#container').fadeIn('8000');
});
}
});
});
});
my php code
if(mysql_num_rows($result) > 0){
//Fetch rows
while($row = mysql_fetch_array($result)){
echo $row['img'];
}
}
I m getting this output
images/man/caps/army-black.pngimages/man/caps/army-brown.pngimages/man/caps/army-grey.pngimages/man/caps/army-lthr.pngimages
these are basically image paths now how to loop over them in jquery and fit each image in image tag
any code will be useful
Plz Note I DONT NEED JSON
regards sajid
JSON is probably your best bet here. In PHP do something like this:
$ret = array();
while( $row = mysql_fetch_assoc( $result ) )
{
$ret[] = $row['img'];
}
echo json_encode( $ret );
This will output something like the following
["image1","image2","image3"]
jQuery has a function which can convert this information into a javascript array. So put this code in your success callback.
var result = jQuery.parseJSON( data );
alert( result[1] );
EDIT: A method which does not use JSON
In PHP place each image url on a separate line
echo $row['img'], "\n";
Then in javascript, split the response by the new line character
var result = data.split( "\n" );
simply change your php code:
`if(mysql_num_rows($result) > 0){
while($row = mysql_fetch_array($result)){
echo ""<img src='".$row['img']."' /><br />";
} }

how to update PHP variable with Jquery Ajax?

I'm making a simple voter that takes either a "like" vote or "dislike" vote. Then, I count the total number of likes and dislikes and output the total numbers. I figured out how to put in the votes using Jquery Ajax, but the number of votes do not update after I put in a vote. I would like to update the $numlike and $numdislike variables using Jquery Ajax.
Here is the PHP script pertaining to the output:
$like = mysql_query("SELECT * FROM voter WHERE likes = 1 ");
$numlike = 0;
while($row = mysql_fetch_assoc($like)){
$numlike++;
}
$dislike = mysql_query("SELECT * FROM voter WHERE likes = 0 ");
$numdislike = 0;
while($row = mysql_fetch_assoc($dislike)){
$numdislike++;
}
echo "$numlike like";
echo "<br>";
echo "$numdislike dislike";
UPDATE:
Jquery Ajax for uploading vote
<script>
$(document).ready(function(){
$("#voter").submit(function() {
var like = $('#like').attr('value');
var dislike = $('#dislike').attr('value');
$.ajax({
type: "POST",
url: "vote.php",
data: "like=" + like +"& dislike="+ dislike,
success: submitFinished
});
function submitFinished( response ) {
response = $.trim( response );
if ( response == "success" ) {
jAlert("Thanks for voting!", "Thank you!");
}
return false;
});
});
</script>
<form id="voter" method="post">
<input type='image' name='like' id='like' value='like' src='like.png'/>
<input type='image' name='dislike' id='dislike' value='dislike' src='dislike.png'/>
</form>
vote.php:
if ($_POST['like'])
{
$likeqry = "INSERT INTO test VALUES('','1')";
mysql_query($likeqry) or die(mysql_error());
echo "success";
}
if ($_POST['dislike'])
{
$dislikeqry = "INSERT INTO test VALUES('','0')";
mysql_query($dislikeqry) or die(mysql_error());
echo "success";
}
If you want to change current like or dislike number after clicking it you must return result instead of printing it ! return json result and echo this and change div innerHTML to see new result !
............
............
............
$dislike = mysql_query("SELECT * FROM voter WHERE likes = 0 ");
$numdislike = 0;
while($row = mysql_fetch_assoc($dislike)){
$numdislike++;
}
echo json_encode( array( $numlike, $numdislike ) ) ;
exit();
Now in your html code :
$.ajax({
type: "POST",
url: "vote.php",
context:$(this)
data: "like=" + like +"& dislike="+ dislike,
success: submitFinished(data)
});
function submitFinished( response ) {
response = $.parseJSON( response );
//Now change number of like and dilike but i don't know where are shown in your html
$('#like').attr('value',response[0]);
$('#dislike').attr('value',response[1]);
return false;
});
You can send a $_GET or $_POST variable to the file that you are calling with AJAX.
.load("google.com", "foo=bar", function(){
});

Categories