Get php id with ajax? - php

$.ajax({
url: "salvar.php",
type: "post",
async: false,
dataType : "html",
data: {
"feito": 1,
"id": id,
"html": html,
"css": css,
"js": js
},
success: function(data) {
alert(data.id);
}
});
I am using the following code made in ajax to send data to the php page doing the processing along with the database.
<?php
require_once 'banco/conexao.php';
if(isset($_POST['feito'])){
$id_setado = $_POST["id"];
if($id_setado === ''){
$id = base_convert(time(), 10, 36);
$busca = mysqli_query($conn,"SELECT id FROM codigos WHERE id = '$id'");
$buscaId = mysqli_fetch_array($busca);
if ($buscaId == false) {
$html = base64_encode($_POST['html']);
$css = base64_encode($_POST['css']);
$js = base64_encode($_POST['js']);
$inserir = mysqli_query($conn,"INSERT INTO codigos (id,html,css,js) VALUES ('$id','$html','$css','$js')");
}
}else{
$id = $id_setado;
$html = base64_encode($_POST['html']);
$css = base64_encode($_POST['css']);
$js = base64_encode($_POST['js']);
$atualizar = mysqli_query($conn,"UPDATE codigos SET html='$html',css='$css',js='$js' WHERE id = '$id'");
}
}
?>
What I would like is to know how I can get the $id that receives base_convert(time(), 10, 36); in the "success" response of ajax. Specifically this data that I want. How can I get this php variable with ajax?

Use echo to get the value of $id
echo $id

Related

e.preventDefault / return false breaks ajax script firing properly

I'm creating an ajax script to update a few fields in the database. I got it to a point where it worked but it sent the user to the php script instead of staying on the page so I did some googling, and people suggested using either return false; or e.preventDefault() however, if I do this, it breaks the php script on the other page and returns a fatal error. I might be missing something being newish to AJAX but it all looks right to me
JS:
$(document).ready(function() {
var form = $('form#edit_child_form'),
data = form.serializeArray();
data.push({'parent_id': $('input[name="parent_id"]').val()});
$('#submit_btn').on('click', function(e) {
e.preventDefault();
$.ajax({
url: form.prop('action'),
dataType: 'json',
type: 'post',
data: data,
success: function(data) {
if (data.success) {
window.opener.$.growlUI(data.msg);
}
},
error: function(data) {
if (!data.success) {
window.opener.$.growlUI(data.msg);
}
}
});
});
})
AJAX:
<?php
//mysql db vars here (removed on SO)
$descriptions = $_GET['descriptions'];
$child_id = $_GET['child_id'];
$parent_id = $_GET['parent_id'];
$get_child_ids = $dbi->query("SELECT child_ids FROM ids WHERE parent = ". $parent_id ." ORDER BY id"); //returns as object
$count = 0;
$res = array();
while ($child_row = $get_child_ids->fetch_row())
{
try
{
$dbi->query("UPDATE ids SET description = '$descriptions[$count]', child_id = '$child_id[$count]' WHERE parent_id = $child_row[0]");
$res['success'] = true;
$res['msg'] = 'Success! DDI(s) updated';
} catch (Exception $e) {
$res['success'] = true;
$res['msg'] = 'Error! '. $e->getMessage();
}
$count++;
}
echo json_encode($res);
it's probably something really small that I've just missed but not sure what - any ideas?
my solution:
I var_dumped $_GET and it returned null - changed to $_REQUEST and it got my data so all good :) thanks for suggestions
Try the following instead.
I moved the form data inside click and enclosed the mysql queries values in single quotes.
JS:
$(document).ready(function() {
var form = $('form#edit_child_form');
$('#submit_btn').on('click', function(e) {
e.preventDefault();
var data = form.serializeArray();
data.push({'parent_id': $('input[name="parent_id"]').val()});
$.ajax({
url: form.prop('action'),
dataType: 'json',
type: 'get',
data: data,
success: function(data) {
if (data.success) {
window.opener.$.growlUI(data.msg);
}
},
error: function(data) {
if (!data.success) {
window.opener.$.growlUI(data.msg);
}
}
});
});
})
AJAX:
<?php
//mysql db vars here (removed on SO)
$descriptions = $_GET['descriptions'];
$child_id = $_GET['child_id'];
$parent_id = $_GET['parent_id'];
$get_child_ids = $dbi->query("SELECT child_ids FROM ids WHERE parent = '". $parent_id ."' ORDER BY id"); //returns as object
$count = 0;
$res = array();
while ($child_row = $get_child_ids->fetch_row())
{
try
{
$dbi->query("UPDATE ids SET description = '$descriptions[$count]', child_id = '$child_id[$count]' WHERE parent_id = '$child_row[0]'");
$res['success'] = true;
$res['msg'] = 'Success! DDI(s) updated';
} catch (Exception $e) {
$res['success'] = true;
$res['msg'] = 'Error! '. $e->getMessage();
}
$count++;
}
echo json_encode($res);
You are using an AJAX POST request so in your PHP you should be using $_POST and not $_GET.
You can just change this:
$descriptions = $_GET['descriptions'];
$child_id = $_GET['child_id'];
$parent_id = $_GET['parent_id'];
to this:
$descriptions = $_POST['descriptions'];
$child_id = $_POST['child_id'];
$parent_id = $_POST['parent_id'];

PHP like/dislike button working only the first time

I'm trying to implement a like/dislike button on my page. I managed to get the button to work (it changes like to dislike and vice versa when clicked) and it also creates or deletes the like on the database table. The problem now is the counter of likes. It works only the first time i click the button, i.e. if initially there are 2 likes and i dislike the post the post shows 1 likes, but if I try to click again on it, it keeps showing 1 like and I have to reload the page to see it change to 2 likes.
This is what I have so far:
JQUERY
$(document).on('click', ".miPiace", function() {
trova = '';
commentoORisposta = '';
valCOR = '';
var comOrisp;
try{
trova = $(this).parentsUntil("#fermamiQui");
commentoORisposta = trova.find(".idCommento");
comOrisp = 'commento';
valCOR = commentoORisposta.val();
} catch(err){
trova = $(this).parentsUntil(".infoCommento");
commentoORisposta = trova.find(".idRisposta");
comOrisp = 'risposta';
valCOR = commentoORisposta.val();
}
valCOR = commentoORisposta.val();
if ($(this).hasClass('fa-thumbs-o-up')) {
$(this).removeClass('fa-thumbs-o-up');
$(this).addClass('fa-thumbs-up');
$.get( "lib/ottieniCose.php", { like: "", id: valCOR, comOrisp: comOrisp } )
.done(function( data ) {
trova.find('.numDiLikes').replaceWith('<p>' + data + ' likes</p>');
});
}else if($(this).hasClass('fa-thumbs-up')){
$(this).removeClass('fa-thumbs-up');
$(this).addClass('fa-thumbs-o-up');
$.get( "lib/ottieniCose.php", { remLike: "", id: valCOR, comOrisp: comOrisp } )
.done(function( data ) {
trova.find('.numDiLikes').replaceWith('<p>' + data + ' likes</p>');
});
};
});
PHP
if (isset($_GET['like'])) {
if ($_GET['comOrisp'] == 'commento') {
$commento->set_likes($_GET['id'], true);
return print $commento->get_likes($_GET['id'], true);
} elseif ($_GET['comOrisp'] == 'risposta') {
$commento->set_likes($_GET['id'], false);
return print $commento->get_likes($_GET['id'], false);
}
} elseif (isset($_GET['remLike'])) {
if ($_GET['comOrisp'] == 'commento') {
$commento->remove_likes($_GET['id'], true);
return print $commento->get_likes($_GET['id'], true);
} elseif ($_GET['comOrisp'] == 'risposta') {
$commento->remove_likes($_GET['id'], false);
return print $commento->get_likes($_GET['id'], false);
}
}
Other PHP file where there is the $commenti class
public function get_likes($id, $commento){
$idComm = 0;
$idRisp = 0;
$retVal = ($commento) ? $idComm = $id : $idRisp = $id;
if ($idComm != 0){
$query = "SELECT commento,
(SELECT COUNT(*) FROM likes
WHERE commento = {$idComm})
AS like_count FROM likes";
} elseif($idRisp != 0){
$query = "SELECT risposta,
(SELECT COUNT(*) FROM likes
WHERE risposta = {$idRisp})
AS like_count FROM likes";
}
$trovaQuanti = mysqli_query($_SESSION['connessione'], $query);
$trovaDavveroQuanti = mysqli_fetch_assoc($trovaQuanti);
if ($trovaDavveroQuanti == null) {
return '0';
}
return $trovaDavveroQuanti['like_count'];
}
You may want to try a normal $.ajax call. And turn off caching. Sometimes this causes an issue where you need to refresh to see the changes.
$.ajax({
type: 'GET',
cache: false,
url: "lib/ottieniCose.php",
data: { like: "", id: valCOR, comOrisp: comOrisp },
dataType: "html",
success: function(html){
trova.find('.numDiLikes').html('<p>' + data + ' likes</p>');
}
});

receive multiple values from db using ajax

i know how to validate form using it for 1 field. But i would like enter code and take back multiple values from my db. exmp: price, quantity etc.
It is posible to do using ajac?
php file:
$sql = "SELECT * FROM database WHERE code='$field_code'";
$params = array();
$options = array( "Scrollable" => SQLSRV_CURSOR_KEYSET );
$query=sqlsrv_query($conn, $sql, $params, $options);
$row = sqlsrv_fetch_array($query);
if ($row == true)
{
$code = ($row['code']);
$life = ($row['life']);
$agree = ($row['agree']);
}
echo $code;
echo $life;
echo $agree;
?>
And script is:
$("#field_code").change(function() {
$("#message").html("<img src='pictures/ajax_loader.gif' width='26px' height='26px' /> checking...");
var data1 = $("#field_code").val();
$.ajax({
type: 'POST',
url: 'validation.php',
data: $('form').serialize(),
success: function validate(code) {
if (data == ? ) {
to do something
} else {
to do something
}
How to receive all 3 values from php file?
}
})
you need to use json encode for this
$values[]= array('code'=>$row['code'],
'life'=>$row['life'],
'agree'=>$row['agree']);
echo json_encode($values);
and in ajax
var data = jQuery.parseJSON(data);
and access values like data.life,data.code and data.agree

passing a javascript variable to a php function and quoting it correctly

Im using Zend Framework ..in one of my phtml file's i have this code
<script>
function foobar(id,type){
var idarray = <?php AppNamespace_General::getparentids( ?>id, type<?php ) ?>; // here the id and type are from js
//the php function returns a json array to the js variable
......
location.href = baseurl +'/somepage/id/'+id;
}
How can i correctly pass the js elements to the php function
The php function(Already thought of doing it via ajax..its quite complex)
public static function getparentids($id, $type, $elmarray = '') {
if (empty($elmarray)) { //avoiding redeclaration of array
$elmarray = array();
}
switch (strtolower($type)) {
case 'group':
case 'product':
case 'specification':
$gp_handler = new PackAssist_Model_DbTable_Groups();
$q = "SELECT * FROM t_groups WHERE group_id = $id";
$sql = $gp_handler->getAdapter()->query($q);
break;
case 'part':
$pt_handler = new PackAssist_Model_DbTable_Parts();
$q = "SELECT * FROM t_parts WHERE part_id = $id";
$sql = $pt_handler->getAdapter()->query($q);
break;
}
$result = $sql->fetchAll();
$i = 0;
if (count($result) > 0) {
foreach ($result as $row) {
if (isset($row['group_parent_id']) && $row['group_parent_id'] != 0) {
if (in_array($row['group_id'], $elmarray)) {
$e = $row['group_parent_id'];
} else if ($row['group_parent_id'] != 0) {
$e = $row['group_id'];
}
} else if (isset($row['part_group_id'])) {
$e = $row['part_group_id'];
} else if ($row['group_parent_id'] == 0) {
break;
}
if (isset($e) && !empty($e)) {
array_push($elmarray, $e);
}
self::getparentids($e, 'group', $elmarray);
$i++;
}
} else {
array_push($elmarray, $id);
}
array_pop($elmarray); //removing the group of super parent group which we dont need
if ($i == 0) { // just encode the array only once
echo json_encode(array_reverse($elmarray));
}
}
If you use jQuery, you can do the following to execute the JSON request:
$.ajax({
type: 'GET',
url: '/path/to/script.php',
data: '{ id: '+id+', type: '+type+' }',
contentType: 'application/json',
dataType: 'json',
success: function(data) {
dataObject = JSON.parse(data);
// process data
},
error: function(e) {
console.log(e.message);
}
});
You can use your existing PHP code with this solution. The url you point to would just have to print the JSON result, as you are currently doing in getparentids().

Need help learning ajax, grabbing data from mysql

I have an ajax script, which I kinda understand, but still need some extra help.
$('.images').click(function(){
var imageId = $(this).attr('id');
alert(imageName);
$.ajax({
type: "get",
url: "imageData.php",
dataType: "json",
data: {getImageId: imageId},
error: function() {
alert("error");
},
success: function(data){
alert(imageId);
$("#images_"+imageId).html(data);
}
});
//$('#images_'+imageId).toggle();
});
I have that code, it goes to this imageData.php file
<?php
if(isset($_GET)){
$images = "";
$path = 'img/';
$imageId = $_GET['getImageId'];
$sql = mysql_query("SELECT * FROM images WHERE iID = '".$imageId."'");
while($row = mysql_fetch_array($sql)){
$images .= $path.$row['images'];
}
$json = json_encode($images);
?>
<img src='<?php echo $json;?>'/>
<?php
}
?>
Why does it output error when I try to echo a string from $images, but it outputs correctly when I do echo $imageId;? I'm trying to output something from mysql, but not trying to output just the id.
Need help please, thank you
You don't need use json_encode here, there is not data that needs to be in JSON format. There is also no reason to loop over the result set, if the query only returns one image.
Try this:
<?php
if(isset($_GET['getImageId'])) {
$path = '';
$imageId = mysql_real_escape_string($_GET['getImageId']); // SQL injection!
$result = mysql_query("SELECT images FROM images WHERE iID = '".$imageId."'");
$row = mysql_fetch_array($result);
if($row) {
$path = 'img/' . $row['images'];
}
}
?>
<?php if($path): ?>
<img src='<?php echo $path;?>'/>
<?php endif; ?>
If the iID is actually an integer, you need to omit the single quotes in the query.
You also have to change the dataType from json to html, as you are returning an image tag (HTML) and not JSON:
$.ajax({
type: "get",
url: "imageData.php",
dataType: "html",
data: {getImageId: imageId},
error: function() {
alert("error");
},
success: function(data){
$("#images_"+imageId).html(data);
}
});
Another option is to return only text (the link) and create the images on the client side:
<?php
if(isset($_GET['getImageId'])) {
$path = '';
$imageId = mysql_real_escape_string($_GET['getImageId']); // SQL injection!
$result = mysql_query("SELECT images FROM images WHERE iID = '".$imageId."'");
$row = mysql_fetch_array($result);
if($row) {
echo 'img/' . $row['images'];
}
}
?>
And in JavaScript:
$.ajax({
type: "get",
url: "imageData.php",
dataType: "text",
data: {getImageId: imageId},
error: function() {
alert("error");
},
success: function(data){
$("#images_"+imageId).html('<img src="' + data + '" />');
}
});
As you may get many images because you use while loop you probably want to do this like so:
in php:
$x = 0;
$another = array();
while($row = mysql_fetch_array($sql)){
$another[$x] = $path.$row['images'];
$x++;
}
echo json_encode($another);
and in jquery (in your success callback):
$.each(data, function(i, v){
// Do the image inserting to the DOM here v is the path to image
$('#somelement').append('<img src="'+v+'"');
});
For outputing an image you must set src attribute of the image tag, if you already have one, or you can create it on the fly. See here how to do that > jQuery document.createElement equivalent?

Categories