ajax method ($.post) with mysql not working simple code - javascript

i have problem this code not working , i want display result of mysql without send no data
my simple code ajax
$('.myClass').on('click',function(){
$.post('resultAll.php');
});
code html
<li class="myClass" > click this </li>
code php / mysql for display result on page (name resultAll.php)
$stmt = $connect->prepare('SELECT * FROM table WHERE price = :aff');
$stmt->execute(array(':aff'=>'5'));
$res = $stmt->fetchAll();
foreach ($res as $row) {
?>
<div class="noon" style="width: 1000px;height: 500px">
<?php print_r($row['id'].' '); ?>
</div>
result these nothing

As per your code snippet, you want to fetch data from resultAll.php file into your HTML page. If I am correct then your code is wrong, you have to use below method instead of $.post() method
$('.myClass').on('click',function(){
$("#result").load('resultAll.php');
});
Your HTML code should be
<li class="myClass" > click this </li>
....
...
<div id="result"></div>
I mean in your page must have one div tag with id="result".
I hope this is works for you.

As you say that your Jquery is not working. Is your element .myClass is created with JS dynamically? Ensure this:
$(document.body).on('click', '.myClass', function(){
$.post('resultAll.php');
});
Edit
Add response from $.post to body:
$('.myClass').click(function(){
$.post('resultAll.php', function(response){
$(body).append(response);
});
});

Related

Dynamically send javascript value via form

I don't know if it's possible, but I need to send some information across a form ou inside url come from checkbox value.
This code below is inside a products loop and create a checkbox on every products (product comparison approach).
In my case, it's impossible to make this code below across a form.
<?php
echo '<div><input type="checkbox" value="' . $products_id .'" id="productsCompare" title="Compare" onclick="showProductsCompare()" /> Compare</div>';
?>
To resolve this point, I started to use an ajax approach and put the result inside a $_SESSION
My script to for the checbox value
$(function() {
$('input[type=checkbox]').change(function() {
var chkArray = [];
$('#container').html('');
//put the selected checkboxes values in chkArray[]
$('input[type=checkbox]:checked').each(function() {
chkArray.push($(this).val());
});
//If chkArray is not empty create the list via ajax
if (chkArray.length !== 0) {
$.ajax({
method: 'POST',
url: 'http://localhost/ext/ajax/products_compare/compare.php',
data: { product_id: chkArray }
});
}
});
});
And at the end to send information on another page by this code. Like you can see there is no form in this case.
<div class="col-md-12" id="compare" style="display:none;">
<div class="separator"></div>
<div class="alert alert-info text-md-center">
<span class="text-md-center">
<button class="btn">Compare</button>
</span>
</div>
</div>
No problem, everything works fine except in my compare.php file, I have not the value of my ajax. I inserted a session_start in ajax file
But not value is inserted inside compare.php.
I tried different way, include session_start() inside compare.php not work.
My only solution is to include in my products file a hidden_field and include the value of ajax across an array dynamically, if it's possible.
In this case, values of hidden_fields must be under array and sent by a form.
This script must be rewritten to include under an array the chechbox value
without to use the ajax. How to insert the good code?
$(function() {
$('input[type=checkbox]').change(function() {
var chkArray = [];
$('#container').html('');
//put the selected checkboxes values in chkArray[]
$('input[type=checkbox]:checked').each(function() {
chkArray.push($(this).val());
});
//If chkArray is not empty show the <div> and create the list
if (chkArray.length !== 0) {
// Remove ajax
// some code here I suppose to create an array with the checkbox value when it is on true
}
});
});
and this code with a form
<?php
echo HTML::form('product_compare', $this->link(null, 'Compare&ProductsCompare'), 'post');
// Add all the js values inside an array dynamically
echo HTML::hidddenField('product_compare', $value_of_javascript);
?>
<div class="col-md-12" id="compare" style="display:none;">
<div class="separator"></div>
<div class="alert alert-info text-md-center">
<span class="text-md-center">
<button class="btn">Compare</button>
</span>
</div>
</div>
</form>
Note : this code below is not included inside the form (no change on that).
<?php
echo '<div><input type="checkbox" value="' . $products_id .'" id="productsCompare" title="Compare" onclick="showProductsCompare()" /> Compare</div>';
?>
My question is :
How to populate $value_of_javascript in function of the checkbox is set on true to send the information correctly inside compare.php
If my question has not enought information, I will edit this post and update in consequence.
Thank you.
You cannot pass JavaScript Objects to a server process. You need to pass your AJAX data as a String. You can use the JavaScript JSON.stringify() method for this...
$.ajax({
method: 'POST',
url : 'http://localhost/ext/ajax/products_compare/compare.php',
data : JSON.stringify({product_id: chkArray})
});
Once that has arrived at your PHP process you can turn it back into PHP-friendly data with PHP JSON methods...
<?
$myArray = json_decode($dataString, true);
// ... etc ... //
?>
See:
JSON # MDN
JSON # PHP Manual
Example: Form Submission Using Ajax, PHP and Javascript

How to call a function in a php file using jquery load?

I am trying to display the data i retrieve from the database but it is not being displayed. I have a function in the file getComments.php called "getComments(page)" page is just a integer parameter to choose that database. and as you can see that i need to call this function to print the users comments. I am trying to use "load" but it is not being successful i just want to call this function to load the comments on the page. thank you in advance.
<?php
use TastyRecipes\Controller\SessionManager;
use TastyRecipes\Util\Util;
require_once '../../classes/TastyRecipes/Util/Util.php';
Util::init();
function getComments($page){
echo "<br><br>";
$controller = SessionManager::getController();
$controller->getComments($page);
SessionManager::setController($controller);
}
and in my web page where i want to display it using java script, i tried the following
<div class="page" id="comments">
<p class="style">Comments</p>
<button class="btn" id="load-comments">See Previous Comments</button><br>
<br><br>
<?php
if(isset($_SESSION['u_id'])){
echo " <input type='hidden' id='uid' value = '".$_SESSION['u_uid']."'>
<input type='hidden' id='date' value = '".date('Y-m-d H:i:s')."'>
<textarea id='message'></textarea><br>
<button class = 'btn' type = 'submit' id = 'submitCom'>Comment</button>";
}
else{
echo "<p>Please log in to comment</p>";
}
?>
</div><br>
<script>
$(document).ready(function(){
$("#load-comments").click(function(){
document.getElementById('#comments').innerHTML =
$("#comments").load("../extras/getComments.php", getComments(1));
});
});
</script>
Just change your click handler to this:
$("#load-comments").click(function(){
$("#comments").load("../extras/getComments.php", { page: 1 }); //i also added where the elements are loaded
});
and in getComments.php (if practical, otherwise you might need to create a new PHP file which calls the getComments() function and call that from the click handler instead) add something like:
if (isset($_POST['page'])) {
getComments($_POST['page']);
// do any other necessary stuff
exit;
}

echo-ed HTML Element from PHP is not read in JAVASCRIPT

so i have some html elements generated from PHP since most contents are fetched from the database
i.e.
<?php
...
while($row = $sqlQry->fetch_object()) {
echo "<li class = 'lstOption' id = 'opt$row->name' data-value = '$row->total_count'>
<h3>$row->given_reference<h3>
</li>";
}
...
?>
and this is a sample structure based on my javascript
<script>
$("ul li").click(function(){
alert($(this).data('value'));
});
</script>
but if i inject an onClick= attribute while inside the echo. the script executed properly. what i need is for the script to work with the echo-ed html elements from php.
Try using variable interpolation syntax, i.e. wrap your variables around curly braces
"{$var}"
take note that you have to use double quotes("") for this
"<li class = 'lstOption' id = 'opt{$row->name}' data-value = '{$row->total_count}'>
<h3>{$row->given_reference}<h3>
</li>"
Just put your script inside document ready as below. That will fix the issue
$(document).ready(function(){
$("ul li").click(function(){
alert($(this).data('value'));
});
});
You should try the code binding with the $(document).ready() method.
This is because once your all DOM elements are ready then after code bind with document ready will appear.
so do the following code.
<?php
...
while($row = $sqlQry->fetch_object()) { ?>
<li class = 'lstOption' id = 'opt<?php echo $row->name?>' data-value = '<?php echo $row->total_count?>'>
<h3><?php $row->given_reference?><h3>
</li>";
}
<?php ...
?>
<script>
$(document).ready(function(){
$("ul li").click(function(){
alert($(this).data('value'));
});
});
</script>
or write as follows
<script>
$(document).ready(function(){
$("ul li").on("click",function(){
alert($(this).data('value'));
});
});
</script>
You can try to select by id and use the on() method:
$(document).on('click', '[id^="opt"]', function () {});
Works only if you don't have anything else with id starting with "opt".
In my opinion id selectors are always stronger than any other selector.
The on() method is also preferable as it is also valid for dynamically generated elements (in case of adding content via ajax for example)
Also if you want to print the actual value and not the formula in your data-value, your quotes are wrong, here is the correct version :
while($row = $sqlQry->fetch_object()) {
echo "<li class = 'lstOption' id = 'opt".$row->name."' data-value = '".$row->total_count."'>
<h3>".$row->given_reference."<h3>
</li>";
}
try like
$(document).ready(function(){
$("ul li").on('click', function(){
console.log($(this).data('value'));
});
});
Since your html elements are generating dynamically you have to use on()

JQuery: Post variable to the second file, and when the enter key pressed, the web will direct me to the first search result page

I created an instant search similar to google search using JQuery.
Q1.
The post to search.php using search function searchq() then print out the returned result works fine, but the createq() function doesn't work at all, it didn't triggered when I using alert() to test, any ideas on how to fix it so the variable txt could be post to create_object.php (which has been post successfully to search.php).
Q2
I want to create a function that allow the user to direct to the first search result(which is anchored with an url) when the enter is pressed, any idea how to achieve this? I tried something but it messed up.
Note that I didn't include the connect to database function here. Coz I think the database username and password setting would be different to yours.So please create your own if you want to test it. The mysql is set with a table is called "objects", and it has one column named "name".
Thanks in advance!
<html>
<!-- google API reference -->
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<!-- my own script for search function -->
<center>
<form method="POST">
<input type="text" name="search" style="width:400px " placeholder="Search box" onkeyup="searchq();">
<input type="submit" value=">>">
<div id="output">
</div>
</form>
</center>
<!-- instant search function -->
<script type="text/javascript">
function searchq(){
// get the value
var txt = $("input").val();
// post the value
if(txt){
$.post("search.php", {searchVal: txt}, function(result){
$("#search_output").html(result+"<div id=\"create\" onclick=\"creatq()\"><br>Not found above? Create.</div>");
});
}
else{
$("#search_output").html("");
}
};
function createq(){
// allert for test purpose
alert("hi");
$.post( "create_object.php",{creatVal:txt} );
}
</script>
</html>
PHP file (search.php)
<?php
if(isset($_POST["searchVal"])){
//get the search
$search=$_POST["searchVal"];
//sort the search
$search=preg_replace("#[^0-9a-z]#i","",$search);
//query the search
echo "<br/>SELECT * from objects WHERE name LIKE '%$search%'<br/>";
$query=mysqli_query($conn,"SELECT * from objects WHERE name LIKE '%$search%'") or die("could not search!");
$count=mysqli_num_rows($query);
//sort the result
if($count==0){
$output="there was no search result";
}
else{
while($row=mysqli_fetch_assoc($query)){
$object_name=$row["name"];
$output.="<div><a href='##'".$object_name."</a></div>";
}
}
echo $output;
}
?>
php file (create_object.php)
<?php
if(isset($_POST["createVal"])){
$name=$_POST["createVal"];
var_dump($name);
}
?>
Two questions in one!
Q1: The problem appears to be a misspelling in the onclick function:
onclick=\"creatq()\"
should be
onclick=\"createq()\"
Q2: Pressing enter will submit the form, so you use the submit handler to catch the enter press then redirect:
$(function() { //shorthand document.ready function
$('form ').on('submit', function(e) { //use on if jQuery 1.7+
e.preventDefault(); //prevent form from submitting
$url = $('#search_output div:first a').attr('href'); // find first link
window.location.href = $url; // redirect
});
});
(credit to this answer for most of the work)

reading a drag and drop ordered list via JavaScript

I have an application (drag and drop using JqueryUI.GridSort) that allows the user to upload photos, and then sort the photos in the order that they would like using drag and drop.
On page load, the user is prompted to upload photos which are posted to the next page. When they arrive on the next page my php script creates a <ul id="sortable"> containing <li> for each of the files they uploaded. For each picture that they have uploaded to the site, a new <li> is created. Inside of that <li> is a <img> that sets the picture for <li> with the image they have uploaded.
My goal is to be able to "save" the order of the pictures after they have arranged them in the drag and drop interface. For example, once they have finished arranging and sorting the pictures in the order they want them in, I would like to be able to send them another page that creates an xml file ( I don't need help with the XML, only saving the order) with using the list that they created in the correct order.
After hours of tinkering with PHP, I have come to realization that because PHP is a serverside language, it cannot see what is sorted post render. So my question is, is there a way to have JavaScript or Ajax read the current order of the list, and post it to the next page? If you do know how, could you please provide an example of both the POST from one page, and the post receiving on the other? I am not very familiar with Ajax.
Thank you greatly for any assistance you could provide.
Sample Code (The contents of the foreach statement that creates a LI for each file uploaded)
$imgID++;
echo '<li class="ui-state-default"><img id="'.$imgID.'"'.' src="user_files/'.$file_name.'" draggable="true" height="90" width="95"></li>';
EDIT
main page :
<script>
$('#my_form').on('submit', function() {
var ordered_list = [];
$("#sortable li img").each(function() {
ordered_list.push($(this).attr('id'));
});
$("#ordered_list_data").val(JSON.stringify(ordered_list));
});
</script>
<div id="tesT">
<form id="my_form" action="update_data.php">
<!-- other fields -->
<input type="hidden" id="ordered_list_data"></input>
<input type="submit" value="Proceed to Step 2"></input>
</form>
</div>
update_data.php:
<?php
// process other fields as normal
if(isset($_POST['ordered_list_data'])) {
$img_ordering = json_decode($_POST['ordered_list_data']);
echo "1";
} else {
echo "nodata";
}
// do things with the data
?>
I built a JSFiddle doing basically the same thing that David posted.
I added a piece to write out the result to a div on the page, so you can see what's going on:
<input type="button" id="savebutton" value="save"/>
<div id="output"></div>
<form id="listsaveform" method="POST" action="script.php">
<input type="hidden" name="list" id="hiddenListInput" />
</form>
Javascript:
$(function() {
$( "#sortable" ).sortable();
$( "#sortable" ).disableSelection();
$( "#savebutton" ).click(function() { LISTOBJ.saveList(); });
});
var LISTOBJ = {
saveList: function() {
var listCSV = "";
$( "#sortable li" ).each(function() {
if (listCSV === "") {
listCSV = $(this).text();
} else {
listCSV += "," + $(this).text();
}
});
$("#output").text(listCSV);
$("#hiddenListInput").val(listCSV);
//$("#listsaveform").submit();
}
}
If you're using a <form> you can do something like this (assuming jQuery is being used):
$('#my_form').on('submit', function() {
var ordered_list = [];
$("#sortable li img").each(function() {
ordered_list.push($(this).attr('id'));
});
$("#ordered_list_data").val(JSON.stringify(ordered_list));
});
In essence, what you're doing is looping over the <ul>, fetching each <img> and appending the ids (in order of appearance) to an array. Arrays preserve ordering in JavaScript and JSON, so one can turn it into a JSON string using the JSON.stringify function, set it as the value of a <input type="hidden"> field and then submit the form.
If you want to use AJAX, the functionality is very similar. However, instead of using an onsubmit (or onclick) you'd use $.post.
Let's go with the <form> option since it's simpler. All told you'll have something similar to the above JS along with HTML like this:
<form id="my_form" method="post" action="./update_data.php">
<!-- other fields -->
<input type="hidden" name="ordered_list_data" id="ordered_list_data"></input>
<input type="submit" value="Submit"></input>
</form>
Then, in update_data.php (or whatever your script is named):
<?php
// process other fields as normal
if(isset($_POST['ordered_list_data'])) {
$img_ordering = json_decode($_POST['ordered_list_data']);
} else {
// handle case where there is no data
}
// do things with the data
?>

Categories

Resources