I'm using the php-mvc and adding search functionality using ajax. How am going to pass the value from the input to model and query the value. I tried to add $_GET['searchData'] inside getAllUsersProfiles method but it doesn't get the value.
HTML:
<input type="text" id="searchData" placeholder="search name here..." />
...
<!--where I want to output the search result -->
<tbody id="account_results"></tbody>
JS:
$("#searchData").keyup(function(){
var searchValue = $.trim($(this).val());
if(searchValue !== ''){
$.get("<?php echo URL; ?>admin/index/", function(returnData){
if(!returnData)
$("#account_results").html("<p>No record(s) found.</p>");
else
$("#account_results").html(returnData);
});
}
});
PHP Model:
public function getAllUsersProfiles()
{
$sql = "SELECT id, username, email, active, firstname, lastname
FROM users";
if(isset($_GET['searchData'])) {
$sql .= " WHERE CONCAT(TRIM(firstname), ' ', TRIM(lastname))
LIKE '%:searchData%'";
$sth = $this->db->prepare($sql);
}
else
//if search input is not set, output all of the list.
$sth = $this->db->prepare($sql);
$sth->execute();
$all_users_profiles = array();
foreach ($sth->fetchAll() as $user) {
//code here..
}
return $users;
}
PHP Controller:
class Admin extends Controller
{
function __construct()
{
parent::__construct();
}
function index()
{
$admin_model = $this->loadModel('Admin');
$this->view->users = $admin_model->getAllUsersProfiles();
$this->view->render('admin/index');
}
Your PHP code doesn't get the searchData value because you don't send it with the GET request. Try this in your JS part:
$("#searchData").keyup(function(){
var searchValue = $.trim($(this).val()), url = '<?php echo URL; ?>/admin/index/?searchData=' + searchValue;
if(searchValue !== ''){
$.get(url, function(returnData){
if(!returnData)
$("#account_results").html("<p>No record(s) found.</p>");
else
$("#account_results").html(returnData);
});
}
});
And then you can get the value with $_GET['searchData'] in PHP
Related
I am sending values of a jQuery array to another PHP array from {file.js} to {file.php} but the transferred data won't show up on the database An empty row in the targeted column will show up in the the table of the DataBase while the ID will occur
The script that I wrote on file.js is the following :
var emailText;
var emailArray = new Array();
$("#emailAddress").keypress(function (event){
if(event.which === 13){
var emailText = $(this).val();
$(this).val("");
emailArray.push(emailText);
$('ul').prepend('<li>' + emailText + '<span><i class="fa fa-trash"></i></span>');
$.post(
"http://localhost/main_dir/dir/file.php",
emailArray,
function(){
alert('Your email has been added to the database successfully');
}
);
}
});
And the code that I wrote on file.php is the following :
<?php
require_once 'dbhandler.php';
$add_email = array("");
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$add_email = $_POST['emailArray'];
$sql = "INSERT INTO databse (new_added_email) VALUES ('$add_email');";
$result = mysqli_query($conn, $sql);
}
?>
1st: I don't know what is the purpose of using array for emails while ID must be unique and you must have only one email input So no need for array in your case
2nd: As I posted on the comment data should post between curly braces {}
3rd: Search for any kind of validation to validate the data posted to the database
4th: It will be better if you post the email to the php/database then when returned prepend the email to the user
In js
$("#emailAddress").keypress(function (event){
if(event.which === 13){
var $this = $(this);
var emailText = $this.val();
if(validateEmail(emailText)){
$.post(
"http://localhost/main_dir/dir/file.php",
{email : email},
function(data){
console.log(data);
$this.val("");
$('ul').prepend('<li>' + data + '<span><i class="fa fa-trash"></i></span>');
alert('Your email has been added to the database successfully');
}
);
}else{
alert(emailText+' Not valid email');
}
}
});
function validateEmail(email) {
const re = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
In php
<?php
require_once 'dbhandler.php';
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$add_email = $_POST['email'];
// check for email validation
// if(email_is_valid){
$sql = "INSERT INTO databse (new_added_email) VALUES ('$add_email');";
if($result = mysqli_query($conn, $sql)){
echo $add_email;
}
// }
}
?>
I added function validateEmail(email) in js to check email validation you'll need another one for php validation just search for it then use it in php file before dealing with the database
I have a JQuery script that submits user input to a PHP script in the same file, and then displays the result of what the PHP script does with the input. That part works fine. The issue that I’m having is that, upon submission, the JQuery script (at least, I think it's the script) also generates a new submission box below the original.
I’m not sure why. I thought at first that it was an issue with the input type, with the asynchronous part, or even with where I had the form in the overall code, but none of those seem to be playing any role. I'm still a beginner and I'm just not seeing the issue.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<form id = "my_form">
verb <input type = "text" id ="word1"/>
<input type = "submit"/></form>
<div id="name"></div>
<script>
$(document).ready(function(){
$("#my_form").on('submit', function(e)
{
e.preventDefault();
var verb = $ ("#word1").val();
var tag = "#Latin ";
var url = "http://en.wiktionary.org/wiki/"+verb+tag;
$.ajax({
url: "Parser.php",
data: {"verb": verb},
type: "POST",
async: true,
success: function(result){
$("#name").html(result);
$("#name").append(url);
}
});
});
});</script>
RESULT:
PHP
<?php
$bank = array();
function endsWith($haystack, $needle) {
return $needle === "" || (($temp = strlen($haystack) - strlen($needle)) >= 0 && strpos($haystack, $needle, $temp) !== false);
}
function check_end_array($str, $ends)
{
foreach ($ends as $try) {
if (substr($str, -1*strlen($try))===$try) return $try;
}
return false;
}
function db_connect() {
static $connection;
if(!isset($connection)) {
$connection = mysqli_connect('127.0.0.1','username','password','Verb_Bank');
}
if($connection === false) {
return mysqli_connect_error();
}
return $connection;
}
function db_query($query) {
$connection = db_connect();
$result = mysqli_query($connection,$query);
return $result;
}
function db_quote($value) {
$connection = db_connect();
return "'" . mysqli_real_escape_string($connection,$value) . "'";
}
$y = false;
if (isset($_POST['verb'])){
$y=db_quote($_POST['verb']);
echo $y;
echo "\n";
$m = db_query("SELECT `conjugation` FROM normal_verbs WHERE (" . $y . ") LIKE CONCAT('%',root,'%')");
if($m !== false) {
$rows = array();
while ($row = mysqli_fetch_assoc($m)) {
$rows[] = $row;
}
}
foreach ($rows as $key => $value){
if (in_array("first",$value)==true){
echo "first conjugation verb\n";}
$y = $_POST["verb"];
$x = $y;
foreach ($bank as $key => $value)
(series of IF-statements)
}}?>
As Roamer-1888 says's the problem lies in server side, you are returning a html which has a input too. You need to change your code to return only the result string which you append to the div. Else if this is not possible doing at server side as it might require you to change lot of code, then you can strip off the input element from the result and then append it to the div. Like below.
success: function(result){
var div = document.createElement('div');
div.innerHTML = result;
$(div).find('input').remove();
$("#name").html(div.innerHTML);
$("#name").append(url);
}
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);
I had developed a event management system using javascript php and mysql. It works perfectly in plain php but now I need to migrate it into codeigniter and need some advice on how to pass the data from js to php while in codeigniter.
My front end java script function is like this
// event creating
dp.onTimeRangeSelected = function (args) {
var name = prompt("New event name:", "Event");
dp.clearSelection();
if (!name) return;
var e = new DayPilot.Event({
start: args.start,
end: args.end,
id: DayPilot.guid(),
resource: args.resource, //Change to classroom name
text: name //Change to event name
});
dp.events.add(e);
args.text = name;
DayPilot.request(
"backend_create.php",
function(req) { // success
var response = eval("(" + req.responseText + ")");
if (response && response.result) {
dp.message("Created: " + response.message);
}
},
args,
function(req) { // error
dp.message("Saving failed");
}
);
};
The php file handling the create function is like this
<?php
require_once '_db.php';
$insert = "INSERT INTO events (name, start, end, resource) VALUES (:name, :start, :end, :resource)";
$stmt = $db->prepare($insert);
$stmt->bindParam(':start', $start);
$stmt->bindParam(':end', $end);
$stmt->bindParam(':name', $name);
$stmt->bindParam(':resource', $resource);
$received = json_decode(file_get_contents('php://input'));
$start = $received->start;
$end = $received->end;
$resource = $received->resource;
$name = $received->text;
$stmt->execute();
class Result {}
$response = new Result();
$response->result = 'OK';
$response->message = 'Created with id: '.$db->lastInsertId();
echo json_encode($response);
?>
Now on migrating to codeignitor I moved to segregated the backend_create.php file into model and controller and it looks like this.
The controller part
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class TimecalCon extends CI_Controller {
function __construct()
{
parent::__construct();
$this->load->model("Timecal_model");
}
public function insert()
{
$received = json_decode(file_get_contents('php://input'));
$start = $received->start;
$end = $received->end;
$resource = $received->resource;
$name = $received->text;
$this->Timecal_model->InsertDetails($name, $start, $end, $resource);
}
The Model
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Timecal_model extends CI_Model {
function __construct()
{
// Call the Model constructor
parent::__construct();
}
function InsertDetails($name, $start, $end, $resource)
{
$insert = "INSERT INTO events (name, start, end, resource) VALUES (:name, :start, :end, :resource) ";
$query = $db->prepare($insert);
$stmt->bindParam(':start', $start);
$stmt->bindParam(':end', $end);
$stmt->bindParam(':name', $name);
$stmt->bindParam(':resource', $resource);
$stmt->execute();
class Result {}
$response = new Result();
$response->result = 'OK';
$response->message = 'Created with id: '.$db->lastInsertId();
return json_encode($response);
}
The issue is when I change the javascript in the view page and use it like this
.....
DayPilot.request(
"TimecalCon/insert", .......
The functionality breaks and I am unable to insert events into the db. How should I be passing the data from js to the controller in this condition?
We can send the value from javascript to controller using Ajax. I have some code of mine which may help you.
function deleteEmp(empid){
var base_url = '<?php echo site_url(); ?>';
var r=confirm("Do You Really Want to Delete? ")
if (r==true)
{
objPost= new Object();
objPost.empid = empid;
$.ajax({
url:"employee_registration/deleteEmp?empid="+empid,
type:"POST",
data:objPost,
beforeSend:function(data){
},
error:function(data){
},
success:function(data){
alert(data);
result=JSON.parse(data);
alert(result);
if(result.status == 'success'){
alert('Deleted Successfully ');
window.location.reload();
return false;
}
}
});
}else{
return false;
}
}
As you can see I have pass the empid from my view to controller using ajax which gives me result back in variable. Which in this case is json.
Try this
DayPilot.request("<?php echo base_url().'TimecalCon/insert';?>",...)
You'll have to add "url" in "autoload.php" under config folder, then check if the url being loaded is the right one if not. Try modifying base_url() a bit like adding or removing the "index.php" part in the url.
Hope This helps
I try to get the cities according to the country which is passed as parameter and sent via ajax. But for some countries I can get cities and update my form with these cities, for against for other I have this error
{"readyState":0,"responseText":"","status":0,"statusText":"OK"}
When I look in logs for those countries that returns me an error I have the names of the cities retrieved from the database.
I do not understand why this error.
how can I fix it?
Please find below my code
Model
function get_ville_depart($country = null){
$this->db->select('NUMVILLEDEPART, NOMVILLEDEPART')->from('villedepart');
$this->db->join('pays','pays.NUMPAYS=villedepart.numpays');
$this->db->where('pays.NUMPAYS', $country);
$this->db->order_by("NOMVILLEDEPART","asc");
$query = $this->db->get();
$cities = array();
if($query->result()){
foreach ($query->result() as $city) {
$cities[$city->NUMVILLEDEPART] = $city->NOMVILLEDEPART;
}
return $cities;
}else{
return FALSE;
}
}
Controller
function get_ville_depart($country){
foreach($this->ville_model->get_ville_depart($country) as $ville){
log_message('debug',json_encode($ville));
}
header('Content-Type: application/json; charset=utf-8');
echo json_encode($this->ville_model->get_ville_depart($country));
}
View
$('#paysdepart').on("change",function(){
$("#villedepart > option").remove();
var country_id = $('#paysdepart').val();
var base_url="<?= site_url('annonce');?>";
$.ajax({
type: "GET",
url: base_url+"/get_ville_depart/"+country_id,
dataType:'json',
success: function(cities)
{
if(!jQuery.isEmptyObject(cities))
{
$("#ifnotvilledepartindatabase").hide();
$("#dynamicvilledepart").show();
$.each(cities,function(NUMVILLEDEPART,NOMVILLEDEPART)
{
var opt = $('<option />');
opt.val(NUMVILLEDEPART);
opt.text(NOMVILLEDEPART);
$('#villedepart').append(opt);
});
}else
{
$("#dynamicvilledepart").hide();
$("#ifnotvilledepartindatabase").show()
}
},
error:function(error)
{
alert("Error "+JSON.stringify(error));
$("#dynamicvilledepart").hide();
$("#ifnotvilledepartindatabase").show()
}
});
});
Error in those country which does not have any City.
if($query->result()){
foreach ($query->result() as $city) {
$cities[$city->NUMVILLEDEPART] = $city->NOMVILLEDEPART;
}
return $cities;
}else{
return new stdClass; /* Only this line have to change */
}
Use direct URL to see the error for the particuler Country ID.
I have tested in local everything if fine .
Everything seems fine to me, but here my guess about your code :
==> MAKE SURE THE COUNTRY ID IS NEVER EQUAL TO NULL
1 - in your Model, change this,
if($query->result()){
foreach ($query->result() as $city) {
$cities[$city->NUMVILLEDEPART] = $city->NOMVILLEDEPART;
return $cities;
}
else{
return FALSE;
}
to this :
if($result = $query->result_array())
$cities = array_column($result, 'NOMVILLEDEPART', 'NUMVILLEDEPART');
return $cities;
2 - in your Controller, change this :
function get_ville_depart($country){
foreach($this->ville_model->get_ville_depart($country) as $ville){
log_message('debug',json_encode($ville));
}
header('Content-Type: application/json; charset=utf-8');
echo json_encode($this->ville_model->get_ville_depart($country));
}
to this :
function get_ville_depart($country){
$countries = $this->ville_model->get_ville_depart($country);
return $this->output->set_content_type('application/json')
->set_output(json_encode($countries));
}
3 - In your View, Change this :
var country_id = $('#paysdepart').val();
to this :
var country_id = $(this).val();
Note : you can access directly to this page "http://{mywebsite}/get_ville_depart/{country_id}"
with {country_id} equal to the country ID you have a problem with, and check if everything's OK before using the Ajax Query.