How can I pass a javascript value to php? - javascript

I want to add a javascript value to my php query. The code goes like this
<script>
$(document).on('click', '.dropdown-menu li a', function() {
var categoryName = $(this).html();
<?php
$one = mysqli_query($con, "SELECT id FROM tb_category WHERE category_name = '?' ");
?>
})
</script>
I want to put the value of categoryName to the query which I made in php. How will I do it.

Just spend a few hours trying to figure this out myself today. You can use ajax, and send the information using the data tag in an ajax query.
$.ajax({ url: 'file goes here',
data: {action: '0'},
type: 'post',
success: function(output) { //action }
});
The data tag gives you the information.
In your php:
$data = $_POST["action"];

you should use ajax to get the attribute from your clicked div and send it to a php page where you receive the "javascript variable" and use it as a php variable with $_POST like this:
<script type="text/javascript">
$(function() {
$(document).on('click', '.dropdown-menu li a', function() {
{
var categoryname = $(this).attr("id");
var dataString = 'categoryname'+ categoryname ;
$.ajax({
type: "POST",
url: "yourphppage.php",
data: dataString,
cache: false,
success: function(html)
{
$(".result").html(html);
}
});
return false;
});
});
Now in your php page:
$categoryname=$_POST['categoryname'];
$one = mysqli_query($con, "SELECT id FROM tb_category WHERE category_name = $categoryname
");

It doesn't go this way, unless you make AJAX calls (see http://api.jquery.com/jquery.get/ and other answers).
The simplest solution (if you do not have too many categories, say a few hundreds tops) would be to cache the categories client-side in a Javascript variable, as in:
<script type="text/javascript">
var categoriesCache = <?php
$cache = array();
$result = mysqli_query($con, "SELECT id, category_name FROM tb_category");
while ($row = $result->fetch_array(MYSQLI_ASSOC)) {
$cache[$row["category_name"]] = $row["id"];
}
echo json_encode($cache);
?>;
$(document).on('click', '.dropdown-menu li a', function() {
var categoryName = $(this).html();
var categoryId = categoriesCache[categoryName];
});
</script>

<script>
$(document).on('click', '.dropdown-menu li a', function(e) {
e.preventDefault();
var categoryName = $(this).text();
// !! be careful here !! send web safe category name, `$(this).text();` or even better a numeric value.
$.get('runquery.php', {'category': encodeURIComponent(categoryName)}).done(function (data) {
// on success do something if needed
});
})
</script>
Put your PHP/SQL script in runquery.php

You can do this with Ajax
http://www.w3schools.com/jquery/jquery_ajax_get_post.asp
Php-script in a separate File like:
First you JavaScript file:
$(document).on('click', '.dropdown-menu li a', function() {
var categoryName = $(this).html();
$.post("php-file.php",{cat_Name: categoryName});
});
then you php-file.php looks like:
<?php
$categoryname = $_POST['cat_Name'];
$one = mysqli_query($con, "SELECT id FROM tb_category WHERE category_name = '?' ");
?>
if you want to use them again:
add to your PHP on the end:
$return = new array();
$return[0] = ;//your results in this array
echo json_encode($return);
then in your JavaScript should look like:
$(document).on('click', '.dropdown-menu li a', function() {
var categoryName = $(this).html();
$.post("php-file.php",{cat_Name: categoryName}, function(data){
sccess_function(data);}, "json");
});
then add a function:
function succsess_function(data){
//do thing here
}

Related

How to make script tag work inside a div?

I am building an edit feature of a post on a website, so i am using jquery ajax and php as the script file that makes the edit inside a database. The problem is in the return script, i have a script tag which contains some jquery and then i place the returned data inside a div, but the script tag is being printed as if it was a text. Can someone help me please to let the script tag act as an actual script and not being printed as text ?
here is my html div :
<div class="board_post_span" id="<?php echo $board_id."-".$board_user_id;?>-spanBoardEdit"><?php echo $board_post;?></div>
and here is my php script :
<?php
require_once '../includes/session.php';
require_once '../includes/functions.php';
require_once '../includes/validation_functions.php';
require_once '../includes/create_thumbnail.php';
// this to prevent from accessing this file by pasting a link to it
if(!is_ajax_request()) {
exit;
}
if(isset($_POST['board_id'], $_POST['board_textarea'])) {
$board_id = (int)$_POST['board_id'];
$board_textarea = mysql_prep($_POST['board_textarea']);
// UPDATE table
$query = "UPDATE board_table ";
$query .= "SET board_post = '$board_textarea' ";
$query .= "WHERE board_id = $board_id";
$result = mysqli_query($connection, $query);
// now we select the updated board post
$query2 = "SELECT * FROM board_table ";
$query2 .= "WHERE board_id = $board_id ";
$result2 = mysqli_query($connection, $query2);
confirm_query($result2);
$result_array = mysqli_fetch_assoc($result2);
}
?>
<?php
echo $result_array['board_post'];
?>
<script>
// This takes care of the board Continue Reading feature ---------------------------------------------------------
$(".board_post_span").each(function(){
var boardPostText = $(this).text();
var boardPostLength = boardPostText.length;
var boardIdAttribute1 = $(this).attr("id");
var boardIdAttributeArray1 = boardIdAttribute1.split("-");
var boardPostId = boardIdAttributeArray1[0];
var boardPostUserId = boardIdAttributeArray1[1];
if(boardPostLength > 250) {
var boardPostTextCut = boardPostText.substr(0, 250);
$(this).text(boardPostTextCut+"...");
$("#"+boardPostId+"-continueReading").remove();
$(this).after('Continue Reading');
} else {
$(this).text(boardPostText);
}
});
</script>
and here is my jquery and ajax :
$.ajax({
url: url_edit_board,
method: "POST",
data: {
board_id: saveBoardButtonId,
board_textarea: editBoardTextareaVal
},
beforeSend: function() {
CustomSending("Sending...");
},
success: function(data){
$("#sending_box").fadeOut("Slow");
$("#dialogoverlay").fadeOut("Slow");
// this makes the scroll feature comes back
$("body").css("overflow", "scroll");
console.log(data);
$("#"+saveBoardButtonId+"-"+editBoardButtonUserId+"-spanBoardEdit").html(data);
$("#"+saveBoardButtonId+"-formBoardEdit").hide();
$("#"+saveBoardButtonId+"-"+editBoardButtonUserId+"-spanBoardEdit").show();
}
});
The reason is that you're setting boardPostText to the text of the entire DIV, which includes the <script> tag inside the DIV. You should put the text that you want to abbreviate inside another span, and process just that.
So change:
echo $result_array["board_post"];
to:
echo "<span class='board_post_text'>" . $result_array["board_post"] . "</span>";
Then in the JavaScript you're returning you can do:
$(".board_post_text").each(function(){
var boardPostText = $(this).text();
var boardPostLength = boardPostText.length;
var boardIdAttribute1 = $(this).attr("id");
var boardIdAttributeArray1 = boardIdAttribute1.split("-");
var boardPostId = boardIdAttributeArray1[0];
var boardPostUserId = boardIdAttributeArray1[1];
if(boardPostLength > 250) {
var boardPostTextCut = boardPostText.substr(0, 250);
$(this).text(boardPostTextCut+"...");
$("#"+boardPostId+"-continueReading").remove();
$(this).after('Continue Reading');
} else {
$(this).text(boardPostText);
}
});
First of all, it seems you don't need else part:
else {
$(this).text(boardPostText);
}
Then, before do anything, make sure that your return data from PHP file, the text has not become encrypted in some way. if < becomes < then the text never consider as JS code.
You can create a script tag then place your JS script into it as a function then call it yourself right after injecting.
replace your script in PHP file with this:
<script>
var scriptText = `function editPost() {
$(".board_post_span").each(function(){
var boardPostText = $(this).text();
var boardPostLength = boardPostText.length;
var boardIdAttribute1 = $(this).attr("id");
var boardIdAttributeArray1 = boardIdAttribute1.split("-");
var boardPostId = boardIdAttributeArray1[0];
var boardPostUserId = boardIdAttributeArray1[1];
if (boardPostLength > 250) {
var boardPostTextCut = boardPostText.substr(0, 250);
$(this).text(boardPostTextCut+"...");
$("#"+boardPostId+"-continueReading").remove();
$(this).after('<a href="board_comment.php?
user_id='+boardPostUserId+'&board_id='+boardPostId+'" class="board_continue_reading" target="_blank" id="'+boardPostId+'-continueReading">Continue Reading</a>');
}
});
}`
</script>
then change your js file to:
$.ajax({
// ...
success: function(data) {
// ...
var container = $("#"+saveBoardButtonId+"-"+editBoardButtonUserId+"-spanBoardEdit")
container.html(data)
var scriptEl = $('<script></script>').html(scriptText).appendTo(container)
// now call the editPost function
editPost()
$("#"+saveBoardButtonId+"-formBoardEdit").hide();
container.show();
}
});

jquery Ajax POST posted but not received?

I am completely confused:
This is my php script "add_credits.php". It runs perfectly if I create a form and call it via method="post".
$stmt = "UPDATE sites SET credits=:credits WHERE id=:id";
$stmt = $db->prepare($stmt);
$stmt ->execute( array( ":credits" => $_POST['cred'], ":id" => $_POST['id'] ) );
This is my input field that triggers the jquery/ajax.
<input id="<?php echo $row['id']; ?>" type="text" class="credits" value="<?php echo $row['credits']; ?>" />
This is my jquery, which will echo eitther variable in an alert box correctly on success.
$(".credits").bind('input', function() {
var add_id = $(this).attr("id");
var info = 'id=' + add_id;
var add_cred = $(this).attr("value");
var info2 = 'cred=' + add_cred;
$.ajax({
type : "POST",
url : "add_credits.php", //add credits on enter php script
data : {info:info, info2:info2},
success : function() {
alert(info2);
}
});
return true;
});
So why is it that its reporting success, yet no UPDATE is being performed, as if the php is not receiving the $_POST details? Am I missing something??
You don't have to manually serialize the data like that
$('.credits').on('input', function() {
var req = $.post('add_credits.php', {
info: $(this).attr('id'),
info2: $(this).attr('value')
});
req.done(function(res) {
console.log(res);
});
req.fail(function(err) {
console.error(err);
});
});
On the PHP side of things, make sure you're reading info and info2
// info and info2 were set in the POST request in the jQuery above
$info = $_POST['info'];
$info2 = $_POST['info2'];
do_something($info, $info2);
// respond in some way
header('content-type: application/json');
echo json_encode(['ok'=> true]);
You can name the fields id and cred if that's what you wish. That would change the jQuery data to this
var req = $.post('url', {
id: $(this).attr('id'),
cred: $(this).attr('value')
});
Then make sure you read $_POST['id'] and $_POST['cred'] in the PHP
Use the following jquery code:
$(".credits").bind('input', function() {
var add_id = $(this).attr("id");
var info = add_id;
var add_cred = $(this).attr("value");
var info2 = add_cred;
$.ajax({
type : "POST",
url : "add_credits.php", //add credits on enter php script
data : {id:info, cred:info2},
success : function() {
alert(info2);
}
});
return true;
});

Ajax not submitting $_Post

I have this section of code that is suppose to get the Values of the input fields and then add them to the database. The collection of the values works correctly and the insert into the database works correctly, I am having issue with the data posting. I have narrowed it down to the data: and $__POST area and im not sure what I have done wrong.
JS Script
$("#save_groups").click( function() {
var ids = [];
$.each($('input'), function() {
var id = $(this).attr('value');
//Put ID in array.
ids.push(id);
console.log('IDs'+ids);
});
$.ajax({
type: "POST",
url: "inc/insert.php",
data: {grouparray: ids },
success: function() {
$("#saved").fadeOut('slow');
console.log('Success on ' + ids);
}
});
});
PHP Section
<?php
include ('connect.php');
$grouparray = $_POST['grouparray'];
$user_ID = '9';
$sql = "INSERT INTO wp_fb_manager (user_id, group_id) VALUES ($user_ID, $grouparray)";
$result=mysql_query($sql);
if ($result === TRUE) {
echo "New records created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysql_error();
}
?>
You cannot send an array trough an ajax call.
First, use something like:
var idString = JSON.stringify(ids);
And use it: data: {grouparray: idString },
On the PHP side:
$array = json_decode($_POST['grouparray']);
print_r($array);

best option to get php array variable in Javascript produced by php script that requested through an ajax call

Currently I am trying to create a live search bar that only produce 5 results max and more option if there is over 5 results. So what I have done so far is a jquery ajax script to call a php script that runs asynchronously on key up in textbox I have.
I want to get the php array then I will code it further using javascript.
This is my code now:
Javascript code
<script type="text/javascript">
function find(value)
{
$( "#test" ).empty();
$.ajax({
url: 'searchDb.php',
type: 'POST',
data: {"asyn": value},
success: function(data) {
return $lala;
var lala = $lala;
$( "#test" ).html($lala);
}
});
}
</script>
SearchDb PHP code:
<?php
function searchDb($abc, $limit = null){
if (isset($abc) && $abc) {
$sql = "SELECT testa FROM test WHERE testa LIKE '%$abc%'";
if($limit !== null){
$sql .= "LIMIT ". $limit;
}
$result = mysql_query($sql) or die('Error, insert query failed') ;
$lists = array();
while ( $row = mysql_fetch_assoc($result))
{
$var = "<div>".$row["testa"]."</div>";
array_push($lists, $var);
}
}
return $lists;
}
$abc = $_POST['asyn'];
$limit = 6;
$lala = searchDb($abc);
print_r($lala);
?>
How can I get $lala
Have you considered encoding the PHP array into JSON? So instead of just echoing the array $lala, do:
echo json_encode($lala);
Then, on the Javascript side, you'll use jQuery to parse the json.
var jsonResponse = $.parseJSON(data);
Then you'll be able to use this jsonResponse variable to access the data returned.
You need to read jQuery .ajax and also you must view this answer it's very important for you
$.ajax({
url: 'searchDb.php',
cache: false,
type: 'post'
})
.done(function(html) {
$("#yourClass").append(html);
});
In your searchDb.php use echo and try this code:
function searchDb($str, $limit = null){
$lists = array();
if (isset($str) && !empty($data)) {
$sql = "SELECT testa FROM test WHERE testa LIKE '%$data%'";
if(0 < $limit){
$sql .= "LIMIT ". $limit;
}
$result = mysql_query($sql) or die('Error, insert query failed') ;
while ( $row = mysql_fetch_assoc($result))
{
$lists[] = "<div>".$row["testa"]."</div>";
}
}
return implode('', $lists);
}
$limit = 6;
$data = searchDb($_POST['asyn'], $limit);
echo $data;
?>
If you dont have or your page searchDb.php dont throw any error, then you just need to echo $lala; and you will get result in success part of your ajax function
ALso in your ajax funciton you have
//you are using data here
success: function(data) {
return $lala;
var lala = $lala;
$( "#test" ).html($lala);
}
you must try some thing like this
success: function(data) {
var lala = data;
$( "#test" ).html($lala);
}

Ajax pass id using POST with php (Error Undefined variable: id)

Im new In AJAx. My problem is I have ajax Function to pass variable ID in php when the page is load the error is Undefined variable: id but when I look in firebug post id is past successfully . Here is my ajax.
$('.btn_edit').click(function(e){
e.preventDefault();
var $this = $(this);
var id_id = $(this).attr('id');
alert(id_id);
$.ajax({
type: "POST",
url: "edit_query.php",
data:{id: id_id},
success: function() {
alert("Success Input");
and this is my php page to pass.
$id = $_POST['id'];
$sql = mysql_query("select * from user where uid = ".$id."");
$table = mysql_fetch_assoc($sql);
?>
$sql = mysql_query("select * from user where uid = ".$id."");
should be
$sql = mysql_query("select * from user where uid = $id ");
and
var id_id = $(this).attr('id');
alert(id_id);
$.ajax({
type: "POST",
url: "edit_query.php",
data:"id="+id_id,
success: function() {
alert("Success Input");
}
try this
$.post( "edit_query.php", { id: id_id })
.done(function( data ) {
alert( data );
});
try this
edit_query.php
<?php
$id = $_POST['id'];
$sql = mysql_query('SELECT * FROM user WHERE uid = '.$id);
$row = mysql_fetch_assoc();
header('Content-Type: application/json');
echo json_encode($row);
exit;
your.js
$(function(){
var onClick, successHandler;
onClick = function (e) {
e.preventDefault();
$.post('edit_query.php',{id:$(this).attr('id')},successHandler,'json');
};
successHandler = function (json) {alert(json.uid);};
$('.btn_edit').click(onClick);
});

Categories

Resources