How to fix Ajax fetch nothing from database? - javascript

I have a hard time finding my mistake in this code. I have a search bar and I'd use ajax so that the data will fetch automatically.
This is my html file.
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="bootstrap4/jquery/jquery.js"></script>
<script>
function loadproducts()
{
var name = document.getElementById("search");
if(name)
{
$.ajax({
type: 'post',
contentType:false,
cache: false,
processData:false,
data: {
products:name,
},
url: 'loadproducts.php',
success: function (response){
$('#product_area').html(response);
}
});
}
else
{
$('#product_area').html("No Product found!");
}
}
</script>
</head>
<body>
<input type="text" name="search" id="search" onkeyup="loadproducts();">
<div id="product_area">
</div>
</body>
</html>
----------
This is my loadproducts.php file
<?php
include('server/connection.php');
if (isset($_POST['products'])){
$name = mysqli_real_escape_string($db,$_POST['products']);
$show = "SELECT product_name,sell_price FROM products WHERE product_name LIKE '$name%' ";
$query = mysqli_query($db,$show);
if(mysqli_num_rows($query)>0){
while($row = mysqli_fetch_array($query)){
echo "<p>".$row['product_name']."</p>";
echo "<p>".$row['sell_price']."</p>";
}
}
}
Ill tried putting alert("called"); function on the ajax success and the alert is activated but still no output show. I also edit the var name = document.getElementById("search"); to var name = document.getElementById("#search"); but it pass straight to the else statement.Can someone site the problem of this code?

Currently, you're accessing the actual HTML element. You want the value, so use .value:
var name = document.getElementById("search").value;
Or if you prefer, you can simplify this down with jQuery:
var name = $("#search").val();

Related

How To Send and Receive JSON With XAMPP PHP

I have a XAMPP 7.1.10-0 server running with this index.php
<?php
if(isset($_POST["username"])) {
echo $_POST;
header("Location:getbooks.php");
exit;
} else {
echo file_get_contents("login.html");
}
?>
This initially works and displays the login.html file. Then I want to make a ajax call to this file again to switch to another html file. So login.js does this.
window.onload = function() {
var button = document.getElementById("submit");
button.onclick = function() {
var user = document.getElementById("username").value;
var pass = document.getElementById("password").value;
var data = {"username": user, "password": pass};
data = $(this).serialize() + "&" + $.param(data);
$.post('index.php', data, function(response) {
console.log(response);
});
}
}
As you can imagine there is a button that is clicked and when it clicks the Ajax call is made. When I click the button it does not change the header and therefore does not change the page. Would anybody know what I am doing wrong?
If you want to redirect, you can do it in AJAX success method.
login.html:
<!DOCTYPE html>
<html>
<head>
<title>Login</title>
</head>
<body>
<div class="form">
Username: <input id="username" type="text"></input> <br>
Password: <input id="password" type="password"></input> <br>
<button id="submit">Submit</button>
</div>
<!-- jQuery -->
<script
src="https://code.jquery.com/jquery-1.12.4.min.js"
integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ="
crossorigin="anonymous"></script>
<script type="text/javascript">
$(document).ready(function(){
var button = document.getElementById("submit");
button.onclick = function() {
var user = document.getElementById("username").value;
var pass = document.getElementById("password").value;
$.ajax({
url: 'index.php',
data: {
"username" : user,
"password" : pass
},
type: 'POST',
success: function(response) {
window.location = response;
},
error: function(error) {
}
});
}
})
</script>
</body>
</html>
index.php:
<?php
if(isset($_POST["username"])) {
//process the array
echo "getbooks.php";
} else {
echo file_get_contents("login.html");
}
?>
Aside this, you can also handle the response from PHP in AJAX to update the view of the page without redirection.

How to send textbox value to server using ajax?

I have an HTML form which contains a username textbox and a submit button.
When a user inputs a name in the username textbox, I want to take that value and send it over to the server so I can check whether the username has already been taken by another user or not.
Here is my code for creating the form:
<!DOCTYPE html>
<html>
<head>
<script src="JquerySock.js"></script>
<meta charset="utf-8" name="viewport" content="width=device-width, initial- scale=1">
<script>
function Usernameerrorfunc(field, errordiv, Notallowcharserror_SPN){
}
</script>
</head>
<body>
<div id="Registeration_Div" class="Registeration_Div">
<form class="Registration_Form" id="Registration_Form" action="../postr" method="POST">
<div id="Registeration_Username_DIV" class="Registeration_Username_DIV">
<input type="text" id="Registeration_Username_box" class="Registeration_Username_box"
placeholder="" name="UserName" maxlength="30" onblur="Usernameerrorfunc(this, 'Usernameerror_spn', 'Usernamenowallow_spn');" onclick="textboxfocus(this)"/>
</div>
<div class="Registration_Submit_Div">
<input type="submit" value="Submit" id="SumbitForm_btn" class="SumbitForm_btn" name="Submit_btn"/>
</div>
</form>
</div>
</body>
</html>
You could use the $.ajax method in jQuery:
function postUsernameToServer() {
var username = $("#Registeration_Username_box").val();
$.ajax({
url: "http://YourServerUrl",
type: "POST",
data: { username: username },
success: function() {
alert('Successfully connected to the server');
},
error: function() {
alert('Something went wrong');
}
});
}
To invoke this using a button click (From my comment) you could do the following:
<button id="checkUsername">Check username</button>
$("#checkUsername").on("click", function() {
postUsernameToServer();
});
Ensure that you have the jQuery library imported to use the function.
If you did not want to use the jQuery and rather native JavaScript you can use the XMLHttpRequest.
Try this it will work :
Use jQuery.ajax()
Code :
function submitFormData() {
var name = document.getElementById("Registeration_Username_box").value;
// Returns successful data submission message when the entered information is stored in database.
var dataString = 'username=' + name;
if (username == '') {
alert("Please Enter the Username");
} else {
// AJAX code to submit form.
$.ajax({
type: "POST",
url: "checkUsername.php",
data: dataString,
cache: false,
success: function(data) {
alert(data);
},
error: function(err) {
alert(err);
}
});
}
return false;
}
I am giving example in php for checking the username. You can use any language accordingly.
checkUsername.php :
<?php
$connection = mysql_connect("localhost", "root", ""); // Establishing Connection with Server..
$db = mysql_select_db("dbname", $connection); // Selecting Database
//Fetching Values from URL
$username=$_POST['username'];
//Select query
$query = 'select * from user_table WHERE name = "'.$username.'";
$query_result = mysql_query($query);
$res = mysql_fetch_assoc($query_result);
do
{
echo json_encode($res);
}while($res = mysql_fetch_assoc($query_result));
}
mysql_close($connection); // Connection Closed
?>

Jquery Ajax is not working with Codeigniter

I am a ajax beginner, Here I am trying to show a text box value in same page using Ajax.
My Controller code:
<?php
class Merchant extends CI_Controller
{
public function ajaxtest()
{
$this->load->helper('url');
$this->load->view('ajaxtest');
$fullname = $this->input->post("fullname");
echo $fullname;
}
}
?>
Here is my view code:
<head>
<script src="<?php echo base_url();?>assets/js/jquery-latest.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#getinfo").click(function()
{
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>merchant/ajaxtest",
data: {textbox: $("#fullname").val()},
dataType: "text",
cache:false,
success:
function(data){
$('#mytext').html(data);
}
});
return false;
});
});
</script>
</head>
<body>
<form method="post">
<input type="text" id="fullname"/>
<input type="button" value="getinfo" id="getinfo"/>
<span id="mytext"></span>
</form>
</body>
When I click on the button getinfo, I want to show the text inside the text box as span text. But now it shows nothing..
Updated:
After experts' opinion, I edited some text(see my edit note), Now When i click on the button, it shows again a textbox and a button.. !!
Did you set the base_url variable with a link on the Javascript?
Because your post url contains this variable and you need set this to make it work. So initialize the variable with the base_url link.
See the corrected example below . Set your domain instead of the yourbaseurl.com
<script type="text/javascript">
$(document).ready(function(){
var base_url='http://yourbaseurl.com/index.php/';
$("#getinfo").click(function()
{
$.ajax({
type: "POST",
url: base_url + "merchant/ajaxtest",
data: {textbox: $("#fullname").val()},
dataType: "text",
cache:false,
success:
function(data){
$('#mytext').html(data);
}
});
return false;
});
});
</script>
Your base_url variable seems to be undefined in your JavaScript.
One simple approach to get the base URL is to echo it out in a hidden input, and then grab the value of that input in your JS code:
HTML
<input type='hidden' id="baseUrl" value="<?php echo base_url(); ?>" />
JS
var base_url = $('#baseUrl').val();
$.ajax({
type: "POST",
url: base_url + "/merchant/ajaxtest",
data: {textbox: $("#fullname").val()},
dataType: "text",
// ...
you are passing in textbox as parameter from your ajax to controller and trying to get POST data with name fullname. That wont work, since you passed in the name of parameter as textbox, access that in your post, as :
class Merchant extends CI_Controller
{
public function ajaxtest()
{
$this->load->helper('url');
//you dont need to load view so comment it
//$this->load->view('ajaxtest');
$fullname = $this->input->post("textbox"); //not fullname
echo $fullname;
}
}
js
<script type="text/javascript">
$(document).ready(function(){
var base_url='http://yourbaseurl.com/index.php/';
$("#getinfo").click(function() {
var fullname = $("#fullname").val();
alert("Fullname:" + fullname); //do you get this alert
$.ajax({
type: "POST",
url: base_url + "merchant/ajaxtest",
data: {textbox: fullname},
cache:false,
success:function(data){
alert("Response:" + data); //do you get this alert
$('#mytext').html(data);
}
});
return false;
});
});
</script>
Try using this:
<base href="<?=base_url();?>">
<script src="assets/js/jquery-latest.min.js"></script>
And this in ajaxtest:
$this->load->helper('url');
And also Comment out this:
// $this->load->view('ajaxtest');
Might be a little late with this response - but someone might find this while searching for a solution.
I was having the same issues with Codeigniter and JQuery ajax/post response. I could not get this to work no matter what I tried.
In the end, it turned out to be php_error that was causing the problem. Once I removed it, everything worked fine with my post/response.

How to alter AJAX load

I need a script that can show results form my database dynamically. I found a method here: http://openenergymonitor.org/emon/node/107
My question is how to alter the code so that it will show all results instead of only one?
And is it possible to display all results on load and then add newly added lines afterwards?
I tried the following on the client.php:
<html>
<head>
<script language="javascript" type="text/javascript" src="http://code.jquery.com/jquery-1.4.4.js"></script>
</head>
<body>
<h2> Client example </h2>
<h3>Output: </h3>
<div id="output">Henter data.</div>
<script id="source" language="javascript" type="text/javascript">
$(function ()
{
setInterval(function() { $.ajax({
url: 'api.php', //the script to call to get data
data: "", //you can insert url argumnets here to pass to api.php
//for example "id=5&parent=6"
dataType: 'json', //data format
success: function(data) //on recieve of reply
{
var id = data[0]; //get id
var vname = data[1]; //get name
$('#output').append("<b>id: </b>"+id+"<b> name: </b>"+vname+"<br />"); //Set output element html
//recommend reading up on jquery selectors they are awesome
// http://api.jquery.com/category/selectors/
}
}); }, 1000);
});
</script>
</body>
</html>
And this is what I tried on the api.php page:
$result = mysql_query("SELECT * FROM $tableName ORDER BY id DESC");
while($row = mysql_fetch_assoc($result)){
echo json_encode($row);
}
Now it won't show anything. What am I doing wrong?
Thank you!

Get response of ajax when target content loads on document.ready

Hi i've got an ajax post and the response div i want from the other file will be generated after $document_ready function. But the div show empty string when i alert it. Here's my code
var cekJawaban = function(){
var form_data={
kode:$("#code").val(),
id_materi:$("#idmateri").val(),
id_user:$("#iduser").val(),
id_lesson:$("#idlesson").val()
};
$.ajax({
url: 'http://localhost/ta2/frontpage/cekKode',
type: 'POST',
async : true,
data: form_data,
dataType: 'html',
success: function(data){
/*var res = resp;
if(resp=="true")
{
$("#alertsukses").show();
$("#submit").hide();
$("#lanjut").show();
}
else
{
$('#salah').html(resp);
$("#alertsalah").show();
}*/
console.log($(data).find('#mocha').text());
},
error: function(xhr) {
}
});
return false;
};
And here's the target url file:
<!DOCTYPE html>
<html>
<head>
<script src="<?php echo base_url('assets/jquery-2.0.3.min.js')?>"></script>
<script src="<?php echo base_url('assets/expect/jquery.expect.min.js')?>"></script>
<script src="<?php echo base_url('assets/mocha/mocha.js')?>"></script>
<link href="<?php echo base_url('assets/mocha/mocha.css') ?>" rel="stylesheet">
</head>
<body>
<script>mocha.ui('bdd');
mocha.reporter('html');</script>
<div id="mocha"></div>
<?php echo $code; ?>
<div id="cek">
</div>
<script type="text/javascript">
describe("Index", function () {
it("Harus punya div",function(){
fn();
})
})
mocha.run();
$(document).ready(function(){
var notif=""
if($('.error').length>0)
{
var err = $('.error').html();
var sub = err.substr(0,err.indexOf('#'));
notif=sub;
}
else
{
notif="pass";
}
$('#cek').text(notif);
});
var fn = function(){
$expect('body').to.exist('Jangan lupa buat body')
.and.to.have.children('p', "Jangan lupa buat p");
};
</script>
</body>
</html>
I think this is not possible, javascript is executed on client side and if you're requesting the page by ajax you will get only the static content of it. You must consider to change the work flow of your code and stick to dynamic content generation of the target url on the server-side code.
if you pursue this workflow you may get the content and also the javascript code which I think you don't want
Instead of putting your javascript document.ready() function in the "target url file", you can put the javascript code into the success-function of the Ajax call.
So you call the url, the url returns your content, and after content has been returned you can execute javascript code in the success()-function.
Example:
$.ajax({
url: 'http://localhost/ta2/frontpage/cekKode',
type: 'POST',
async : true,
data: form_data,
dataType: 'html',
success: function(data){
//Call your document.ready() here instead.
var notif=""
if($('.error').length>0){
var err = $('.error').html();
var sub = err.substr(0,err.indexOf('#'));
notif=sub;
}
}
});

Categories

Resources