Alright so I have this code which basically finds the user inside the table users and displays it in alert, but it seems that I am doing something wrong. The log shows "Function is not set" and the alert itself displays that.
This is the HTML form I have for it
<center><form method='POST' >
<input id="search_fix" type="text" name="search" placeholder="Search..">
<input type="submit" name="submit_menu_search" style="display: none;">
</form></center>
This is the ajax processing
$(document).ready(function() {
$("#search_fix").keyup(function() {
var search_text = $(this).val();
if(search_text != '') {
$.ajax({
url:"handler.php",
method:"POST",
data:{"function":"search_ajax", search:search_text},
dataType:"text",
success:function(data){
$('#search_result').html(data);
console.log(data);
alert(data);
}
});
}
else {
}
});
});
And these are my PHP functions that I used to basically search for the term
public function search_ajax($term) {
$handler = new sql();
$sql = $handler->connect();
$sql->real_escape_string($term);
$result = $sql->query("SELECT ime FROM users WHERE ime LIKE '%".$term."%'") or die (mysql_error());
if($result->num_rows >= 1){
while($row = $result->fetch_assoc()) {
echo $row['ime'];
}
}
}
if(isset($_POST['function'])) {
switch($_POST['function']) {
case "search_ajax": {
require_once "assembly/user.php";
$user = new User();
$user->search_ajax($_POST['search']);
break;
}
default: {
echo "Unknown AJAX function handler";
break;
}
}
}
else {
echo "Function is not set";
}
It sounds like you're using a version of jQuery before 1.9.0. The method: option didn't exist in the older versions, it was called type:. That's why you're seeing the parameters appended to the URL, because type: "GET" is the default.
So change
method: "POST",
to:
type: "POST",
try this:
$.ajax({
url:"handler.php",
method:"POST",
data:'{"function":"search_ajax", search:search_text}',
dataType:"text"
})
.done(function(data){
$('#search_result').val(data);
console.log(data);
alert(data);
} ) ;
Related
When form submission finishes, the page DISPLAYS the raw json data instead of logging it to the console. The php and html code are both on the same page so I wasn't expecting the page to change at all.
POST
jQuery(function($) {
$("#idSearch").submit(function(event) {
$.ajax({
url: "/index.php",
type: "POST",
data: $(this).serialize(),
dataType: "json",
sucess: function(data) {
console.log(data);
}
})
})
});
php form handling
<?php
if (isset($_POST['orderId'])){
header('Content-Type: application/json');
require 'private/database.php';
$sql = "SELECT * FROM form";
$result = mysqli_query($conn, $sql);
$data = array();
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
$data[] = $row;
}
}
die(json_encode($data));
}
?><!DOCTYPE html>
I've implemented something similar on another webpage but it works as I intended.
POST
function loadInfo() {
jQuery(function($) {
$.ajax({
method: "POST",
url: "/admin.php",
data: {loadInfo: 1},
dataType: "json",
success: function(data) {
console.log(data);
for (var i = 0; i < data.length; i++) {
setMarker(data, i, "red");
printInfo(data, i);
}
}
})
});
}
php form handling
<?php
if(isset($_POST['loadInfo'])){
header('Content-Type: application/json');
require 'private/database.php';
$sql = "SELECT * FROM form";
$result = mysqli_query($conn, $sql);
$data = array();
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
$data[] = $row;
}
}
die(json_encode($data));
}
?><!DOCTYPE html>
Why do these two pages behave differently?
You should stop the default form event.
The browser continue the action and submit the form, so the page is reloaded using POST.
You could prevent using Event.preventDefault()
jQuery(function($) {
$("#idSearch").submit(function(event) {
event.preventDefault(); // << ADD
$.ajax({
url: "/index.php",
type: "POST",
data: $(this).serialize(),
dataType: "json",
success: function(data) { // << Here 'success' not 'sucess'.
console.log(data);
}
})
})
});
solved:
<form action="index.php" method="POST" id="idSearch">
<input type="text" name="orderId" placeholder="訂單號瑪" required><br>
<input type="submit">
</form>
I didn't think I needed an action parameter for the form as it was being sent to the same .php? The code worked once I added a path. Weird.
This is my product.php file which include the following php function
<?php
function getOfferName($conn,$companyID){
$sql="SELECT `id`, `offer_name`, `offer_discount` FROM `oiw_product_offers`
WHERE `company_id`='$companyID'";
if ($result=mysqli_query($conn,$sql)) {
while ($row=mysqli_fetch_assoc($result)) {
?>
<option value="<?php echo $row['id'] ?>"><?php echo $row['offer_name'] ?></option>
<?php
}
}
}
?>
This product.php file include the custom-js.js file in which i am creating a html element dynamically (Select dropdown).
$('.offerCheckBox').on('change', function() {
var id=$(this).data('id');
if (!this.checked) {
var sure = confirm("Are you sure want to remove offer ?");
this.checked = !sure;
}else{
$(this).parent().parent().append('<select name="" id=""><?php getOfferName($conn,$companyID) ?></select>');
}
});
Here i call php function getOfferName but it is showing me output like this
enter image description here
<select name="" id=""><!--?php getOfferName($conn,$companyID) ?--></select>
You can do by below code
getdata.php
if($_POST['action'] == 1){
$companyID = $_POST['id'];
$sql="SELECT `id`, `offer_name`, `offer_discount` FROM `oiw_product_offers`
WHERE `company_id`='$companyID'";
if ($result=mysqli_query($conn,$sql)) {
$html = '';
while ($row=mysqli_fetch_assoc($result)) {
$html .= '<option value="'.$row['id'].'">'.$row['offer_name'].'</option>';
}
}
echo json_encode($html);
exit(0);
}
?>
Ajax Call to Get Data
$('.offerCheckBox').on('change', function() {
var id=$(this).data('id');
if (!this.checked) {
var sure = confirm("Are you sure want to remove offer ?");
this.checked = !sure;
}else{
$.ajax({
url: "getdata.php",
type: 'POST',
data: {id:id,action:1},
dataType: "json",
contentType: false,
cache: false,
processData: false,
success: function(response) {
if (response) {
$(this).parent().parent().append('<select name="" id="">'+response+'</select>');
} else {
//Error
}
return true;
}
});
}
});
the JavaScript file is on the client side writing code in this file will not will not create a server call that runs the PHP file.
if you want to combine JavaScript with a server call you should use ajax.
JavaScript:
$('.offerCheckBox').on('change', function() {
var id=$(this).data('id');
if (!this.checked) {
var sure = confirm("Are you sure want to remove offer ?");
this.checked = !sure;
} else {
let fd = new FormData();
let companyID = $(this).val();
fd.append('companyID', companyID);
$.ajax
({
url: "getOffer.php",
type: "POST",
data: fd,
processData: false,
contentType: false,
complete: function (results) {
let response = JSON.parse(results.responseText);
my_function.call(this, response);
}
});
}
});
// in this function you will put the append of the select box that php has created
function my_function(response) {
console.log("response", response);
}
PHP code (the file name is : getOffer.php)
<?php
$companyID = $_REQUEST['companyID'];
$options = array[];
$sql="SELECT `id`, `offer_name`, `offer_discount` FROM `oiw_product_offers`
WHERE `company_id`='$companyID'";
if ($result=mysqli_query($conn,$sql)) {
while ($row=mysqli_fetch_assoc($result)) {
$options[$row['id']] = $row['offer_name'];
}
}
$resBack = (json_encode($options, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE));
echo ($resBack);
?>
Now in the callback function my_function as we wrote above you have an array of key value pair from the PHP.
iterate on this array in JavaScript build your option select items and append them to the select box.
I am trying to get the results from the database whether username is available or not . But it is not giving any results i am not getting ajax response this is the html code
<form id="user_form">
<input placeholder="username here" type="text" name="ajax-data" id="ajax-data">
<input type="submit" name="btnSubmit" id="btnSubmit" Value="Submit">
</form>
<span class="php_responce_here"></span>
This is the ajax code which i have used
$(document).ready(function()
{
$("form#user_form").click(function()
{
var textboxvalue = $('input[name=ajax-data]').val();
$.ajax(
{
type: "POST",
url: 'second.php',
data: {ajax-data: textboxvalue},
success: function(result)
{
$(".php_responce_here").html(result);
}
});
});
});
</script>
final code of php where i have used the validation and the query to find whether the username is available in the database or not the problem is that it is not giving any of the result
<?php
error_reporting(0);
require "config.php";// configuration file holds the database info
$user_name = $_POST['ajax-data']; // textbox in the html
if($user_name)
{
$usernamecheck= mysql_query("SELECT count(*) FROM users WHERE username='$user_name'");
$check= mysql_fetch_row($usernamecheck);
if($check[0]==0)
{
if($user_name!=""){
if(strlen($user_name)>25){
echo "You have reached the maximum limit";
}
else{
echo "User name is valid";
}
}
else
{
echo "username is empty";
}
}
else{
echo "Username Already Taken";
}
}
?>
should be submit event not click:
$("form#user_form").submit(function(e) {
e.preventDefault();
var textboxvalue = $('input[name=ajax-data]').val();
$.ajax(
{
type: "POST",
url: 'second.php',
data: { "ajax-data": textboxvalue },
success: function(result) {
$(".php_responce_here").html(result);
}
});
});
and as #Cyril BOGNOU pointed out;
data: { "ajax-data": textboxvalue }
You should too add data type to be returned with the parameter if you want to return JSON for example
dataType: 'JSON',
and Yes I think you should better write
data: { "ajax-data": textboxvalue }
So the update should be
$(document).ready(function()
{
$("form#user_form").click(function()
{
var textboxvalue = $('input[name=ajax-data]').val();
$.ajax(
{
type: "POST",
url: 'second.php',
dataType: 'JSON',
data: {"ajax-data": textboxvalue},
success: function(result)
{
$(".php_responce_here").html(result.message);
}
});
});
});
and return json string from PHP script
<?php
error_reporting(0);
require "config.php"; // configuration file holds the database info
$user_name = $_POST['ajax-data']; // textbox in the html
if ($user_name) {
$usernamecheck = mysql_query("SELECT count(*) FROM users WHERE username='$user_name'");
$check = mysql_fetch_row($usernamecheck);
if ($check[0] == 0) {
if ($user_name != "") {
if (strlen($user_name) > 25) {
$message = "You have reached the maximum limit";
} else {
$message = "User name is valid";
}
} else {
$message = "username is empty";
}
} else {
$message = "Username Already Taken";
}
echo json_encode(["message" => $message]);
}
?>
NOTE : mysql is deprecated. you should use mysqli or PDO
There are some mistakes in your code. check the below code. it should work.
<script>
$(document).ready(function () {
$("form").submit(function (event) {
var textboxvalue = $("#ajax-data").val();
$.ajax({
data: {ajaxdata: textboxvalue},
type: "POST",
url: 'second.php',
success: function (result)
{
$(".php_responce_here").html(result);
}
});
return false;
});
});
</script>
You can not create variable ajax-data with -.
PHP
$usernamecheck = mysql_query("SELECT * FROM users WHERE username='$user_name'");
$check = mysql_num_rows($usernamecheck);
you should use mysql_num_rows instead of mysql_fetch_row. it will auto calculate the rows.
Check working example
Empty page? Nothing prints out?
<?php
error_reporting(-1);
ini_set('display_errors', 1);
require "config.php";// configuration file holds the database info
if(isset($username = $_POST['ajax-data'])){
if($l = strlen($username) <= 25 && $l > 2){
$sql = "SELECT * FROM users WHERE username='$username'"; // wide open for SQL injections. use mysqli or PDO instead.
if($rsl = mysql_query($sql) != false){ // ALWAYS verify if your query's ran successfully.
if(mysql_num_rows($rsl) != 0){
echo 'Username already exists';
} else {
echo 'Username is available';
}
} else {
echo 'Query failed: ' . mysql_error();
}
} else {
echo $l > 25 ? 'Reached limit' : 'Needs to be longer';
}
} else {
echo "post['ajax-data'] not set<\br>";
print_r($_POST);
}
?>
Then there is your Javascript code that I have questions on. Yet you have a submit button but you want to check if its valid upon change?
$(document).ready(function(){
$("#user_form").submit(function(event){
event.preventDefault();
$.ajax({
url: "second.php",
type: "post",
data: $(this).serialize(),
success: function(result){
$(".php_responce_here").html(result);
}
});
});
});
This is the ajax function
$(document).ready(function() {
$('#submit').click(function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: 'searchphp.php',
data: {suburb_id: $('#suburb_id').val()},
success: function(data)
{
$("#tableContent").html(data);
}
});
});
});
this is the php file need to receive data, it worked perfect.
<?php
//Check the form if submit by post
if (isset($_POST["searchBtn"])) {
$strInputSuburb = "";
$strInputSuburb = $_POST["suburb_id"];
//Check if the input box is empty or not
//if BOTH "Suburb" AND "Street" is empty, it will display the error message.
if(!empty($strInputSuburb))
{
//Connect to database server and table
include("connection.php");
#mysqli_select_db($conn, "db")
or die ("Database not available");
$querySql1 = "select * from Infringement
where suburb like '%".mysqli_real_escape_string($conn, $strInputSuburb)."%' and Street1 like '%".mysqli_real_escape_string($conn, $strInputStreet)."%'
order by Suburb, Fines DESC";
$result1 = mysqli_query($conn, $querySql1)
or die ("No information return...");
$count = mysqli_num_rows($result1);
$i=1;
if(!$count==0){
//do stuff, like echo
}
else {
//do stuff
}
//Release the SQL clause
mysqli_free_result($result1);
//Close the connection to database
mysqli_close($conn);
}
else {
//do stuff
}
}
?>
i want load to this div
<div id="tableContent"></div>
the css style is
#tableContent {
width:100%;
height:400px;
}
The input box is below
<input type="textbox" class="form-control" name="suburb" placeholder="Suburb" id="suburb_id" >
<input type="submit"class="btn" name="searchBtn" id='submit' value="Search" />
I used php to get data from form before. after using Ajax, I deleted "form" tag.
Thank you so much.
You're not sending the searchBtn parameter, which the PHP script is checking for. Add it to the data: option.
$(document).ready(function() {
$('#submit').click(function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: 'searchphp.php',
data: {
suburb_id: $('#suburb_id').val(),
searchBtn: 'Search'
},
success: function(data)
{
$("#tableContent").html(data);
}
});
});
});
Or remove that check from the PHP script, and test if (isset($_POST['suburb_id'])) instead.
On blur of an e-mail textbox, I want it to do an ajax call back and verify if the e-mail is already in use.
The call is finding the webmethod, however, it's returning a null value. I trimmed the code and I'm getting a null value with the following:
function chkEmail(email) {
var prom = $.Deferred();
console.log(email);
$('#emailCheckGIF').show();
$('input[type="submit"]').prop('disabled', true);
$.ajax({
url: 'emailAvailable',
data: { 'email': email },
success: function (data) {
console.log(data + ' good');
prom.resolve(data);
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(errorThrown + ' error');
prom.reject(errorThrown);
}
});
return prom;
}
My simplified web method
public function emailAvailable($email = null) {
echo json_encode($email);
}
In the firefox dev tools, it says the email param is being passed correctly and the response from the service is NULL
If I remove the json_encode it comes over as a blank string.
Please Try This --
My Controller --
public function checkEmail()
{
$email = $_POST['email'];
$result = $this->federation_model->checkEmail($email);
echo json_encode($result);
}
My Model --
public function checkEmail($email)
{
$this->db->where('user_email', $email);
$result=$this->db->get('users')->row_array();
if(is_array($result))
{
return $result;
}
else
{
return false;
}
}
My View --
<div class="col-md-4">
<input name="assoc_email" id="assoc_email" type="email" class="form-control"/>
<span id="line2" class="text-left"></span>
</div>
My Script --
<script type="text/javascript">
$(document).ready(function(){
$('#assoc_email').keyup(function(){
var email = $('#assoc_email').val();
var filter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
// my ajax function will call after enter the valid email
if(email == "" || !filter.test(email))
{
$('#line2').html("");
$('#submit_assoc').attr('disabled', false);
}
if(filter.test(email) && email != "")
{
$.ajax({
url:"<?php echo base_url(); ?>federation/checkEmail",
type:"post",
data:"email="+email,
success: function(data){
var result = JSON.parse(data);
if(result == "")
{
$('#line2').html("<?php echo $this->lang->line('email'); ?> <?php echo $this->lang->line('available'); ?> ");
$('#line2').css('color', 'green');
}
else
{
$('#line2').html("<?php echo $this->lang->line('email'); ?> <?php echo $this->lang->line('already'); ?> <?php echo $this->lang->line('exists'); ?>");
$('#line2').css('color', '#f3565d');
}
}
});
}
});
});
</script>