Please help, I am trying to get the value of input field after ajax success, I don't know why is it always undefined?
ajax.js
$(document).on('click','.modify',function(){
var modId = $(this).attr('id');
var event_id = $(this).attr('class').split(' ')[1];
$.ajax({
cache: false,
url: '../ajax/paraphernalia/ajax_get_edit.php',
type: 'post',
data: { modId: modId, event_id: event_id},
success:function(data){
var mod_name = $(data).find('input#hidden_headerName').val();
alert(mod_name);
$('#display_modal_edit').html(data);
$('#judge_name_header').html(mod_name);
}
});
});
ajax_get_edit.php
session_start();
require ("../../global.php");
if (isset($_POST['modId']) && isset($_POST['event_id'])) {
$modId = $_POST['modId'];
$event_id = $_POST['event_id'];
$output = '';
$sql = mysql_query("SELECT * FROM tbl_judges WHERE judge_id = ".$modId." AND event_id = ".$event_id."");
$soc_sql = mysql_fetch_assoc($sql);
$output .= '<input type="text" value="GetThisvalue" id="hidden_headerName">';
$output .= '.....';//bunch of codes here
$output .= '</div>';
echo $output;
}
You can Return a JSON from PHP and Create the Divs you need/dont Need on the Client, further its also simpler if you just Need some values
Related
I am getting search results from a MySQL table from a string entered in an input text from a HTML page.
Using AJAX, when the user selects one of the result rows the browser is redirected to a PHP file.
What I need is to put the result on another TextField from the same page and not to open another page.
Here is the code that I have now:
PHP part that is sending the needed output results:
/************************************************
Search Functionality
************************************************/
// Define Output HTML Formating
$html = '';
$html .= '<li class="result" >';
$html .= '<img src="iconos_especialidades/logo" width="94" height="94" />';
$html .= '<a target="_blank" href="urlString" >';
$html .= ' '.'<h3>nameString</h3>';
$html .= '</a>';
$html .= '</li>';
// Get Search
$search_string = preg_replace("/[^A-Za-z0-9]/", " ", $_POST['query']);
$search_string = $tutorial_db->real_escape_string($search_string);
// Check Length More Than One Character
if (strlen($search_string) >= 1 && $search_string !== ' ') {
// Build Query
$query = 'SELECT * FROM tb_especialidades WHERE especialidad LIKE "%'.$search_string.'%" OR especialidad LIKE "%'.$search_string.'%" ORDER BY especialidad';
// Do Search
$result = $tutorial_db->query($query);
while($results = $result->fetch_array()) {
$result_array[] = $results;
}
// Check If We Have Results
if (isset($result_array)) {
foreach ($result_array as $result) {
// Format Output Strings And Hightlight Matches
$display_function = preg_replace("/".$search_string."/i", "<b class='highlight'>".$search_string."</b>", $result['especialidad']);
$display_name = preg_replace("/".$search_string."/i", "<b class='highlight'>".$search_string."</b>", $result['especialidad']);
$display_url = 'opinar_doc_loc.php?id='.$result['id_especialidad'];
if ($result['icono'] == ""){
$display_logo = "nada.jpg";
}
else {
$display_logo = $result['icono'] ;
}
// Insert Name
$output = str_replace('nameString', $display_name, $html);
// Insert URL
$output = str_replace('urlString', $display_url, $output);
// Insert LOGO
$output = str_replace('logo', $display_logo, $output);
// Output
echo($output);
}
}else{
// Format No Results Output
$output = str_replace('urlString', 'javascript:void(0);', $html);
$output = str_replace('nameString', '<b>No se ha encontrado la especialidad buscada.</b>', $output);
$output = str_replace('functionString', 'Sorry :(', $output);
// Insert LOGO
$display_logo = "nada.jpg";
$output = str_replace('logo', $display_logo, $output);
// Output
echo($output);
}
}
And here is the JQuery/Ajax Part:
// Start Ready
$(document).ready(function() {
// Icon Click Focus
$('div.icon').click(function(){
$('input#search').focus();
});
// Live Search
// On Search Submit and Get Results
function search() {
var query_value = $('input#search').val();
$('b#search-string').text(query_value);
if(query_value !== ''){
$.ajax({
type: "POST",
url: "php/search.php",
data: { query: query_value },
cache: false,
success: function(html){
$("ul#results").html(html);
}
});
}return false;
}
$("input#search").live("keyup", function(e) {
// Set Timeout
clearTimeout($.data(this, 'timer'));
// Set Search String
var search_string = $(this).val();
// Do Search
if (search_string == '') {
$("ul#results").fadeOut();
$('h4#results-text').fadeOut();
}else{
$("ul#results").fadeIn();
$('h4#results-text').fadeIn();
$(this).data('timer', setTimeout(search, 100));
};
});
});
How could I put the needed value from the database $result['id_especialidad'] on a TextField from the HTML page?
You can achieve this by returning a json object with more than one key. For example from php:
<?php
$result = array('id' => $result['id_especialidad'], 'data' => $output);
echo json_encode($result);
?>
Then from JS you can decode and handle as two separate pieces of data:
$.ajax({
type: "POST",
url: "php/search.php",
data: { query: query_value },
cache: false,
success: function(html){
var response = $.parseJSON(html);
$("#my_input_field").val(response.id);
$("ul#results").html(response.data);
}
});
EDIT -------
I've added the correct id field from the query result (see above again), you will also need to edit the output from the no results part of the php file (after the 'else') to echo the json encoded array... for example:
<?php
$result = array('id' => 0, 'data' => $output);
echo json_encode($result);
?>
You question is a little bit confusing...
After click in the result list (LIs), you want to put the redirect page to a text field instead of open a new page ?
If yes, you need to do another ajax to get the page content and them put the content in the text field.
I'm currently doing a PHP page that displays bans and also gives an option to unban users.
I can't seem to get the button to work and run the query to unban. Any help would be much appricated.
It currently does nothing and I'm also unsure as to how to display the Pnotice errors as I get
Uncaught TypeError: Cannot read property 'required' of undefined
Here is the function listed in lightcms.php for banlist.php;
function banListAll() {
global $db;
$getBanListAllQuery = "SELECT * FROM users_bans";
$getBanListAll = $db->query($getBanListAllQuery);
while ($showBanListAll = $getBanListAll->fetch_assoc()) {
echo "<tr id=\"banID" . $showBanListAll['id'] . "\">";
echo "<td>";
echo $showBanListAll['id'];
echo "</td>";
echo "<td>";
echo $showBanListAll['added_date'];
echo "</td>";
echo "<td>";
echo $showBanListAll['value'];
echo "</td>";
echo "<td>";
echo $showBanListAll['reason'];
echo "</td>";
echo "<td>";
echo $showBanListAll['expire'];
echo "</td>";
echo "<td>";
echo "<button data-id=\"" . $showBanListAll['id'] . "\" type=\"button\" class=\"btn btn-xs btn-danger btn-unban\">Unban</button>";
echo "</td>";
echo "</tr>";
}
}
Here is the javascript on banlist.php
<script type="text/javascript">
$(".btn-unban").click(function(){
var articleId = "#banID"+ $(this).attr("data-id");
var myData = "unban="+ $(this).attr("data-id"); //post variables
var formData = new FormData(this);
$.ajax({
type: "POST",
url: "./engine/post/unban.php",
dataType:"json",
data: myData,
success: processJson
});
function processJson(data) {
// here we will handle errors and validation messages
if (!data.success) {
if (data.errors.required) {
new PNotify({
title: 'Uh oh!',
text: data.errors.required,
type: 'error'
});
}
} else {
new PNotify({
title: 'Success!',
text: data.message,
type: 'success'
});
$(articleId).fadeOut("slow");
}
}
});
</script>
And here is the unban.php file
<?php
require_once $_SERVER['DOCUMENT_ROOT']."/admin_required.php";
$id = $_POST['id'];
$insert = "DELETE users_bans WHERE id = '$id'";// Do Your Insert Query
if($db->query($insert)) {
echo '{"success":true,"message":"User was unbanned!"}';
} else {
echo '{"error":true,"message":"Sorry this has not worked, try another time!"}';
}
//Need to work on displaying the error^
?>
Your JS looks for "errors.required" but your PHP sends "error" with no required.
Here's some code edits that (IMO) clean up the code. (any changes to sql are based on the assumption that you're using mysqli. that assumption based on the use of ->fetch_assoc()) Please consider atlest the change to unban.php as what you currently have is open to sql injection
Your new banListAll function:
function banListAll() {
global $db;
// don't use SELECT * if you can help it. Specify the columns
$getBanListAllQuery = "SELECT id, added_date, value, reason, expire FROM users_bans";
$getBanListAll = $db->query($getBanListAllQuery);
while ($showBanListAll = $getBanListAll->fetch_assoc()) {
$showBanListAll[] = "<button type='button' class='btn btn-xs btn-danger btn-unban'>Unban</button>";
// array_slice to get ignore the ['id']
echo "<tr data-banid='" . $showBanListAll['id'] . "'><td>" . implode("</td><td>", array_slice($showBanListAll,1)) . "</td></tr>";
}
}
New JS on banlist.php
<script type="text/javascript">
function processJson(data) {
// here we will handle errors and validation messages
if (data.error === false) {
row.fadeOut("slow");
}
// assuming we always get a "message"
new PNotify({
title : 'Uh oh!',
text : data.message,
type : 'error'
});
}
$(".btn-unban").click(function() {
var $this = $(this); // creating jQuery objects can be costly. save some time
var row = $this.closest('tr');
var banID = row.data('banid');
var postData = { unban: banID };
var formData = new FormData(this);
$.ajax({
type : "POST",
url : "./engine/post/unban.php",
dataType : "json",
data : postData,
success : processJson
});
});
</script>
And here is the unban.php file
<?php
require_once $_SERVER['DOCUMENT_ROOT']."/admin_required.php";
$id = $_POST['id'];
// Don't just concat variables that came from users into your DB queries.
// use paramterized queries. If $db is a mysqli connection
$insert = "DELETE FROM users_bans WHERE id = ?";// Do Your Insert Query
$deleteStmt = $db->prepare($insert);
// if id is a number change "s" to "i" below
$deleteStmt->bind_param("i",$id);
if($deleteStmt->execute()) {
echo jsonResult(false,"User was unbanned!");
} else {
echo jsonResult(true,"Sorry this has not worked, try another time!");
}
// add this function to return results to your JS functions
// should make it harder to put "errors" instead of "error" ;)
function jsonResult($hasErrors, $msg) {
return json_encode(array("error"=>$hasErrors,"message"=>$msg));
}
and just in case you thought unban.php was getting unnecessarily long, here it is without comments
<?php
require_once $_SERVER['DOCUMENT_ROOT']."/admin_required.php";
$id = $_POST['id'];
$insert = "DELETE FROM users_bans WHERE id = ?";// Do Your Insert Query
if ($deleteStmt = $db->prepare($insert)) {
$deleteStmt->bind_param("i",$id);
if($deleteStmt->execute()) {
echo jsonResult(false,"User was unbanned!");
} else {
echo jsonResult(true,"Sorry this has not worked, try another time!");
}
}
else {
print_r($db->error);
}
// the function should go into your general functions file
?>
Here is my JavaScript:
$.ajax({
url: 'CheckColorPrice.php',
type: 'POST',
data: {
url: '<?php echo $LINK;?>',
ColorId: ColorNumber
},
dataType: 'json',
success: function (data) {
$('#LoadingImage').hide();
$("#PRICE").text("£ " + data["price"]);
}
});
Here is CheckColorPrice.php:
<?PHP
$url = $_POST['url'];
$ColorId = $_POST['ColorId'];
if(isset($_POST['url']))
{
libxml_use_internal_errors(true);
$doc = new DOMDocument();
$doc->loadHTMLFile($url);
$xpath = new DOMXpath($doc);
$DataVariants = $xpath->query('//span[#class="ImgButWrap"]/#data-variants')->item(0)->nodeValue;
$jsonStart = strpos($DataVariants, '[');
$jsonEnd = strrpos($DataVariants, ']');
$collections = json_decode(substr($DataVariants, $jsonStart, $jsonEnd - $jsonStart + 1));
foreach ($collections as $item) {
$ColVarId = $item->ColVarId;
$SizeNames = [];
$SellPrice = [];
foreach ($item->SizeVariants as $size) {
$SizeNames[] = $size->SizeName;
$SellPrice[0] = $size->ProdSizePrices->SellPrice;
}
$names = implode(',', $SizeNames);
$price = implode('', $SellPrice);
if($ColVarId == $ColorId){
$healthy2 = array('£',' ','Â');
$yummy2 = array('','','');
$price = str_replace($healthy2, $yummy2, $price);
$PRICE = $price;
echo "price: ", json_encode($PRICE), "\n";
}
}
}
?>
The result from CheckColorPrice.php is looking just like this:
price: "37.99"
Where is my mistake, why it is not receiving the response properly. I don't get it at all... Can you help me out ?
Thanks in advance!
You're not returning json. You're returning plain text which contains some json:
echo "price: ", json_encode($PRICE), "\n";
^^^^^^^^^^
That'd look like
price: "$9.99"
which is NOT valid json.
You need to return an array for your JS code to work:
echo json_encode(array('price' => $PRICE));
which would output:
{"price":"$9.99"}
Add the following header to your script:
header('Content-type: application/json');
header("Content-Disposition: inline; filename=ajax.json");
Also change the line
echo "price: ", json_encode($PRICE), "\n";
to
echo json_encode(array('price'=>$PRICE));
Hope that helps
First thing, in your ajax request, add this parameter :
dataType : 'json'
Then, your response is not a correct json.
You can return this :
echo json_encode(array("price"=>$PRICE));
I have a PHP/Ajax function that returns a list of countries with the given characters in a textbox. Ofcourse Ajax updates this list everytime the textbox gets edited.
Index.PHP calls all the other files, classes and HTML. But when the textbox gets updated, Ajax sends a POST variable to index.PHP because this is where the Search.PHP file with the class name SearchEngine gets called. But because he sends this to the index.php everything keeps getting reloaded and the HTML will be returned twice.
Index.php
<?php
require_once("cgi_bin/connection.php");
require_once("Database_Handler.Class.php");
require_once("HTML_Page.Class.php");
require_once("search.php");
$hostname_conn = "localhost";
$database_conn = "ajax";
$username_conn = "root";
$password_conn = "";
$db = new DatabaseHandler();
$conn = $db->openConnection($hostname_conn, $username_conn, $password_conn, $database_conn);
$IndexPage = new page();
echo $IndexPage->render();
$SearchEngine = new SearchEngine($conn);
?>
Please ignore the poor and unsecure database connection. I am currently transforming all my code to PDO and refining it but that is for later.
Search.PHP
<?php
class SearchEngine{
private $html;
public function __construct($conn){
$this->html = '<li class="result">
<h3>NameReplace</h3>
<a target="_blank" href="ULRReplace"></a>
</li>';
if (isset($_POST["query"])) {
$search_string = $_POST['query'];
}
//$search_string = mysql_real_escape_string($search_string);
if (strlen($search_string) >= 1 && $search_string !== ' ') {
$query = 'SELECT * FROM country WHERE name LIKE "%' . $search_string . '%"';
$result = $conn->prepare($query);
$result->execute();
$result_array = $result->fetchAll();
foreach ($result_array as $result) {
$display_name = preg_replace("/" . $search_string . "/i", "<b>" . $search_string . "</b>", $result['name']);
$display_url = 'sadf';
$output = str_replace('NameReplace', $display_name, $this->html);
$output = str_replace('ULRReplace', $display_url, $output);
echo($output);
}
}
}
}
?>
And as final the Javascript
$(document).ready(function() {
function search() {
var query_value = $('input#search').val();
$('b#search-string').html(query_value);
if(query_value !== ''){
$.ajax({
type: "POST",
url: "index.php", //Referring to index.php because this is where the class SearchEngine is called
data: { query: query_value },
cache: false,
success: function(html){
$("ul#results").html(html);
}
});
}
return false;
}
$("input#search").keyup(function() {
clearTimeout($.data(this, 'timer'));
var search_string = $(this).val();
if (search_string == '') {
$("ul#results").fadeOut();
$('h4#results-text').fadeOut();
}
else {
$("ul#results").fadeIn();
$('h4#results-text').fadeIn();
$(this).data('timer', setTimeout(search, 100));
};
});
});
note: HTML is being returned from the "page" class called inside Index.php
How do i not let everything get called twice?
Thank you,
EDIT: A new file was suggested where i direct the ajax url to AutoComplete.php
AutoComplete.PHP
Please explain what should be in the file and why. I am clueless.
Basically, just add a parameter to your Ajax call to tell the index.php its being called by Ajax, and then wrap an if-statement around the two lines that print out your actual index page:
if(!isset($_REQUEST['calledByAjax']))
{
$IndexPage = new page();
echo $IndexPage->render();
}
and in your Ajax call:
data: { query: query_value, calledByAjax: 'true' },
Or make another php page, like ajaxsearch.php that's the same as your index.php but lacking those two lines, and call that in your Ajax call.
First thing (this is a sample, not tested yet)
autocomplete.php
<?php
$search_string = $_POST['query'];
$query = 'SELECT * FROM country WHERE name LIKE "%' . $search_string . '%"';
$result = $conn->prepare($query);
$result->execute();
$result_array = $result->fetchAll();
foreach ($result_array as $result) {
$display_name = preg_replace("/" . $search_string . "/i", "<b>" . $search_string . "</b>", $result['name']);
$display_url = 'sadf';
$output = str_replace('NameReplace', $display_name, $this->html);
$output = str_replace('ULRReplace', $display_url, $output);
}
echo($output);
?>
autocomplete.js
function search() {
var query_value = $('input#search').val();
$('b#search-string').html(query_value);
if(query_value !== ''){
$.ajax({
type: "POST",
url: "autocomplete.php", //Here change the script for a separated file
data: { query: query_value },
cache: false,
success: function(html){
$("ul#results").html(html);
}
});
}
return false;
}
$("input#search").keyup(function() {
clearTimeout($.data(this, 'timer'));
var search_string = $(this).val();
if (search_string == '') {
$("ul#results").fadeOut();
$('h4#results-text').fadeOut();
} else {
$("ul#results").fadeIn();
$('h4#results-text').fadeIn();
search(); // call the function without setTimeout
}
});
});
Have luck :)
I have a question I can't figure out.
<?php
$killtheboy = 0;
if($killtheboy == 1){
echo "<input type=\"text\" name=\"dwanummer\" id=\"dwanummer\">";
}else{
echo "<div id=\"dropdowndwa\">
<select name=\"dwanummer\" id=\"dwanummer\" class=\"dwanummer\">
<option selected=\"selected\">Kies uit lijst</option>";
include("config/instellingen.php");
$query = "SELECT DISTINCT `Klantvraag`,`Wensweek` FROM `DWA` WHERE `Status DWA` = 'DBAA' OR `Status DWA` = 'DBAP' OR `Status DWA` = 'DIUI' ORDER BY wensweek - '$wensweekber' ASC";
if ($result = mysqli_query($connect, $query)) {
while ($get = mysqli_fetch_assoc($result)) {
$week = date('W', strtotime("this week"));
$jaar = date('Y', strtotime("this week"));
$wens = ''. $jaar . ''. $week. '';
$wensweek = $get['Wensweek'];
$wensweekber = $wensweek - $wens;
echo '<div class="selectBlock"><option value="' . $get['Klantvraag'] . '" name="dwanummer" id="dwanummer" class="dwanummer">'.$get['Klantvraag'] . ' Wensweek : ' . $wensweekber . '</option></div>';
}
}
echo "</select></div><br />";
}
?>
The above code (PHP) fetches a list of numbers on pageload and I have to select one in order to fetch that information through JS.
<script type="text/javascript">
$(document).ready(function()
{
$(".kvraagnummer").change(function()
{
var id = $("#kvraagnummer option:selected").prop("value");
var dataString = 'id=' + id;
$.ajax
({
type: "POST",
url: "add_event_2.php",
data: dataString,
cache: false,
success: function(html)
{
$('.cnummer').html(html);
}
});
});
});
</script>
Basically I have a search system and u can find all 'cases' there and if you see one you want then you click it it goes to the above page with code and it auto selects that ID instead of still having to select it. (like additem.php?id=125533 or something)
Can someone please explain me how I can solve this.
Can you try this, You need to use selected attribute in select element
$Selected ='';
if(isset($_GET['id']) && ($get['Klantvraag'] == $_GET['id'])){
$Selected =" selected='selected' ";
}
echo '<option value="' . $get['Klantvraag'] . '" '.$Selected.' name="dwanummer" id="dwanummer" class="dwanummer">'.$get['Klantvraag'] . ' Wensweek : ' . $wensweekber . '</option>';
Javascript:
$(document).ready(function()
{
$(".kvraagnummer").change(function()
{
Populate();
});
Populate();
});
function Populate(){
var id = $("#kvraagnummer option:selected").prop("value");
var dataString = 'id=' + id;
$.ajax({
type: "POST",
url: "add_event_2.php",
data: dataString,
cache: false,
success: function(html)
{
$('.cnummer').html(html);
removeAllNameSelectBoxes();
var selected = $("#dropdowndwa option:selected").map(function (i, el) {
return el.value;
}).get();
getNamesFromSelectIds(selected);
}
});
}