I want to send some data from a form to a PHP file using jQuery. I've searched and I noticed I have to send the data as JSON and receive multiple variables as an array. However I'm Completely confused it's not working.
<input id="username" type="text" class="inputBox">
<input id="password" type="password" class="inputBox">
<button id="submitLogin" class="submitLogin">login</button>
<div id="test"></div>
<div id="test1"></div>
$(document).ready(function() {
$("#submitLogin").click(function() {
var superuser = $("#username").val();
var superpass = $("#password").val();
$.ajax({
type: "POST",
url: 'http://localhost/mainclinic/controllers/login/login.php',
dataType: 'application/json',
data: {
loginid: superuser,
loginpass: superpass
},
cache: false,
success: function(result) {
$('#test').html(result[0]);
$('#test1').html(result[1]);
}
})
})
})
<?php
include "../config.php";
if (!$db)
{
die("Connection failed: " . mysqli_connect_error());
}
if ($_SERVER['REQUEST_METHOD'] === 'POST')
{
$username = mysqli_real_escape_string($db, $_POST['loginid']);
$password = mysqli_real_escape_string($db, $_POST['loginpass']);
$sql = "SELECT id FROM superusers WHERE docid = '$username' and doccpass = '$password'";
$result = mysqli_query($db, $sql);
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
if(mysqli_num_rows($result) > 0)
{
$array = array(success, $username);
echo json_encode($array);
}
else
{
$array = array(failed, nousername);
echo json_encode($array);
}
}
?>
Change This section to this:
$.ajax
({
type:"POST",
url:'http://localhost/mainclinic/controllers/login/login.php',
dataType: "json",
data:{loginid:superuser,loginpass:superpass},
cache: false,
success:function (result) {
$('#test').html(result.status);
$('#test1').html(result.result);
}
})
And Php code like this:
if(mysqli_num_rows($result) > 0)
{
$array = array('status' => 'success', 'result' => $username);
echo json_encode($array);
}else
{
$array = array('status' => 'failed', 'result' => 'nousername');
echo json_encode($array);
}
Related
I'm working on a live search and i need to transfer php data to ajax using json, but the problem is i can't pass an array contain 2 or more identical values, this is the php code:
<?php
class search{
public function gettingvalues($search_value){
require_once('db_conx.php');
$dir = "http://localhost/usersimage/";
$sql = "SELECT name,img,username FROM users WHERE username like '$search_value%' || name like '$search_value%'";
$query = mysqli_query($conx,$sql);
if ($query) {
if (mysqli_num_rows($query) > 0) {
while ($row = mysqli_fetch_array($query)) {
$img = $row['img'];
$name = $row['name'];
$username = $row['username'];
$json = array('img' => $img, 'name' => $name, 'username' => $username);
echo json_encode($json);
}
}
}
}
}
?>
And this is the index code:
<?php
if (isset($_POST['data'])) {
require('search.php');
$search = new search;
$search->gettingvalues($_POST['data']);
header('Content-Type: application/json; charset=utf-8');
die();
}
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('input').keyup(function(){
var value= $('input').val();
$.ajax({
type: "POST",
url: "",
data: {data: value},
datatype: "json",
success: function(json_data){
$('#feedback').html(json_data.name);
}
});
});
});
</script>
<input type="text" name="search" placeholder="looking for?">
<div id="feedback"></div>
So, if my array contain 2 or more identical names ajax wont get any data back, I hope someone have an answer.
You should create array with all results in your search function and then in ajax response loop results to get all names and print it separated by comma.
Search function
<?php
class search{
public function gettingvalues($search_value){
require_once('db_conx.php');
$dir = "http://localhost/usersimage/";
$sql = "SELECT name,img,username FROM users WHERE username like '$search_value%' || name like '$search_value%'";
$query = mysqli_query($conx,$sql);
$results = []; //<!---
if ($query) {
if (mysqli_num_rows($query) > 0) {
while ($row = mysqli_fetch_array($query)) {
$img = $row['img'];
$name = $row['name'];
$username = $row['username'];
$json = array('img' => $img, 'name' => $name, 'username' => $username);
$results[] = $json; //<!---
}
}
}
echo json_encode($results); //<!---
}
}
?>
Ajax
<script type="text/javascript">
$(document).ready(function(){
$('input').keyup(function(){
var value= $('input').val();
$.ajax({
type: "POST",
url: "",
data: {data: value},
datatype: "json",
success: function(json_data) {
var names = [];
$.each(json_data, function(index, element) {
names.push(element.name)
})
$('#feedback').html(names.join(','));
}
});
});
});
</script>
<input type="text" name="search" placeholder="looking for?">
<div id="feedback"></div>
Change this:
while ($row = mysqli_fetch_array($query)) {
$img = $row['img'];
$name = $row['name'];
$username = $row['username'];
$json = array('img' => $img, 'name' => $name, 'username' => $username);
echo json_encode($json);
}
To:
while ($row = mysqli_fetch_array($query)) {
$img = $row['img'];
$name = $row['name'];
$username = $row['username'];
$json[] = array('img' => $img, 'name' => $name, 'username' => $username);
}
echo json_encode($json);
Inside your response for jQuery, retrieve your json data by looping it. Make sure to use var obj = jQuery.parseJSON( json_data ); before looping
I have the following code:
<?php
session_start();
?>
<html>
<head>
<title>Dashboard</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
</head>
<body>
<button id="openjob">View open job requests</button>
<button id="jobtoday">View all job requests today</button>
<div id="responsecontainer"></div>
<script type="text/javascript">
$('#openjob').click(function() {
<?php
$_SESSION["flag"] = 0;
?>
$.ajax({
type: "GET",
url: "cssdashsubmit.php",
dataType: "html", //expect html to be returned
success: function(response){
$("#responsecontainer").html(response);
}
});
});
$('#jobtoday').click(function() {
<?php
$_SESSION['flag'] = 1;
?>
$.ajax({
type: "GET",
url: "cssdashsubmit.php",
dataType: "html", //expect html to be returned
success: function(response){
$("#responsecontainer").html(response);
}
});
});
</script>
</body>
</html>
cssdashsubmit.php includes
session_start();
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
echo $_SESSION['flag'];
if (isset($_SESSION['flag']) && $_SESSION["flag"] === 0) {
$sql = "SELECT * FROM Ticket WHERE ticket_close_open = 'open'";
$result = $link->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()){
echo $row['ticket_id'];
echo $row['ticket_equipment'];
}
}
unset($_SESSION['flag']);
}
if (isset($_SESSION['flag']) && $_SESSION["flag"] === 1) {
$sql = "SELECT * FROM Ticket WHERE DATE(ticket_open_datetime) = date('Ymd')";
$result = $link->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()){
echo $row['ticket_id'];
echo $row['ticket_equipment'];
}
}
unset($_SESSION['flag']);
}
?>
Now when I click on the buttons, it always echoes 3, irrespective of which button I click. I've tried changing the session variable name, but it still persists. Can anybody point where I am erroring?
Instead of session - use simple url parameter:
$('#openjob').click(function() {
$.ajax({
type: "GET",
url: "cssdashsubmit.php?type=jobs",
dataType: "html", //expect html to be returned
success: function(response){
$("#responsecontainer").html(response);
}
});
});
$('#jobtoday').click(function() {
$.ajax({
type: "GET",
url: "cssdashsubmit.php?type=requests",
dataType: "html", //expect html to be returned
success: function(response){
$("#responsecontainer").html(response);
}
});
});
On server side code can be:
session_start();
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
switch ($_GET['type']) {
case "jobs":
$sql = "SELECT * FROM Ticket WHERE ticket_close_open = 'open'";
break;
case "requests":
$sql = "SELECT * FROM Ticket WHERE DATE(ticket_open_datetime) = date('Ymd')";
break;
}
$result = $link->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()){
echo $row['ticket_id'];
echo $row['ticket_equipment'];
}
}
I am trying to submit a form without refreshing the page and I want an alert message to appear when the button id=fav in clicked. this is the code but I don't know what i did wrong. Should it be on button click or on form submit?
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#f1").submit(function(){
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "bookpage.php",
data: {'fav':'fav'} ,
cache: false,
success: function(response){
if(response.message){
alert(response.message);
}
}
});
}
return false;
});
});
</script>
<form action="#read" method="post" id="f1">
<div class="r1">
<button class="down" name="download" title="Add to favorites">Download</button>
<li><a class="full" href="full.php?id=<?php echo $id; ?>">Full page</a>
</li>
<button class="d-later" name="dlater">Download later</button>
<button class="fav-button" type="submit" id="fav"></button>
</div>
</form>
PHP
if(isset($_POST['fav']) && $_POST['fav'] == 'fav' && fav_exists($u , $ii)== true){
$query = "DELETE FROM favorites WHERE bid='$ii' AND email='$u'";
$result = mysql_query($query);
if(! $result ) {
die('Could not delete data: ' . mysql_error());
} $response['message'] = 'My message';
echo json_encode($response);
}else if(isset($_POST['fav']) && $_POST['fav'] == 'fav' && fav_exists($u , $ii)== false){
$query = "INSERT INTO favorites (email,book, bid) VALUES('$u','$bname','$ii')";
$result = mysql_query($query);
if(! $result ) {
die('Could not enter data: ' . mysql_error());
}
$response['message'] = 'My message';
echo json_encode($response);
}
function fav_exists($u , $ii){
$query = "SELECT id FROM favorites WHERE email='$u' AND bid='$ii'";
$result = mysql_query($query);
$count = mysql_num_rows($result);
if($count >= 1) {
return true;
} else {
return false;
}
}
I think you are passing empty data, see example below how to pass some data; If you want to run ajax+php you need to pass some data
<?php if(isset($_POST['action'] && $_POST['action'] == 'my_action') {
// do stuff;
// to send json response use json_encode;
$response['message'] = 'My message';
echo json_encode($response);
}
$.ajax({
url: "my_php.php",
type: "POST",
data: { 'action' : 'my_action' },
success: function(response){
if(response.message){
alert(response.message);
}
}
});
Also i highly recommend using PHP PDO to make SQL queries - http://php.net/manual/en/book.pdo.php
upd:
$('#fav').click(function(){
do_ajax_request('you can pass different type of acitons as param');
});
function do_ajax_request(action) {
$.ajax({
url: "my_php.php",
type: "POST",
data: { 'action' : action },
success: function(response){
if(response.message){
alert(response.message);
}
}
});
}
And at your php file you can switch or if/else different functions depending on your action;
<?php if(isset($_POST['action'])) {
$action = $_POST['action'];
switch($action) {
case 'favorites':
$msg = 'favorites action called';
breake;
case 'not fav':
$msg = 'not fav called';
breake;
default:
$msg = 'Nothing passed';
breake;
}
$Response['msg'] = $msg;
echo json_encode($Response);
}
This is what i use for the same task.
HTML
<form action="" method="post">
name:<input type="text" name="user" /> <br/>
<p><input type="submit" /></p>
</form>
JS
$(function() {
$('form').submit(function(e) {
e.preventDefault(); // Stop normal submission
data = $('form').serializeArray();
alert(JSON.stringify(data));
$.ajax({
type: 'POST',
contentType: "application/json; charset=utf-8",
url: 'inc/update.php',
data: {
json: JSON.stringify(data)
},
dataType: 'json'
}
});
});
return false;
});
PHP
$str_json = file_get_contents('php://input');
$str_json = urldecode($str_json);
$str_json = str_replace('json=[', '', $str_json);
$str_json = str_replace(']', '', $str_json);
$arr_json = json_decode($str_json, true);
$name = $arr_json['name'];
$pdo = new PDO("mysql:host=$db_host;dbname=$db_name", $db_user, $db_password);
$update = $pdo->prepare("UPDATE user SET name='".$name."' WHERE id='3';");
$update->execute();
I'm sending two values to another php via ajax and trying to get back two values and display one in a dropbox, and another in a input box.
This is the ajax code:
function searchq6(){
var searchstate = $("input[name='region']").val();
var searchTxt = $("input[name='suburb']").val();
$.ajax({
url: 'search-suburb.php',
type: 'POST',
dataType: 'JSON',
data: {
searchVal: searchTxt,
st:searchstate},
})
.done(function(response) {
var response = JSON.parse(response);
console.log(response);
})
.fail(function(jqXHR, textStatus, errorThrown) {
console.log(errorThrown);
});
}
And this is what I'm sending back from the php file:
$output = '' ;
if (isset($_POST['searchVal'])){
$searchq = $_POST['searchVal'];
$st = $_POST['st'];
$query = mysqli_query($link, "SELECT DISTINCT title FROM `wp_locations` WHERE state='".$st."' AND `title` LIKE '%".$searchq."%' LIMIT 10")or die("Could not search!");
if (!mysqli_query($link,$query))
{
echo("Error description: " . mysqli_error($link));
}
$count = mysqli_num_rows($query);
if($count == 0){
$output = '<option>No results!</option>';
}else{
$suburb = array();
$postcode = array();
while($row = mysqli_fetch_array($query)){
$suburb[] = $row['title'];
$postcode[] = $row['title'];
//echo $suburb;
} // while
$result = ['success'=> true, 'data'=> ['suburb'=> $suburb, 'postcode' => $postcode], 'error' => null];
echo json_encode($result);
} // else
} // main if
HTML:
Suburb:* <input type="text" name="suburb" list="sbb" required size="30" value="<?php echo $suburb; ?>" onkeyup="searchq6()" id="output">
<datalist id="sbb" name="taskoption6" >
<option> </option>
</datalist>
Postcode:* <input type="number" name="postcode" required value="<?php echo $postcode; ?>" id="postcode">
I'm getting this error in the console:
SyntaxError: Unexpected token E
at Object.parse (native)
at m.parseJSON (http://site/js/jquery.min.js:5:15998)
at Pb (http://site/js/jquery.min.js:5:18379)
at x (http://site/js/jquery.min.js:5:21793)
at XMLHttpRequest.send.b (http://site/js/jquery.min.js:5:26030)
$.ajax({
url: 'search-suburb.php',
type: 'POST',
dataType: 'JSON',//result is set to json
data: {
searchVal: searchTxt,
st: searchstate
},
})
.done(function(response) {//response parsed already
var response = JSON.parse(response);//no need to parse here
console.log(response);
})
.fail(function(jqXHR, textStatus, errorThrown) {
console.log(errorThrown);
});
You set the dataType:'json' so no need to parse
var response = JSON.parse(response);
console.log(response);
You can have this console.log(response); directly without var response = JSON.parse(response);
Hello im doing some try and error. This is the code where select-option populate from database but this gives me null value
echo "<option value=\"\">"."Select"."</option>";
$qry = "select * from try where name = '".$_POST['name']."'";
$result = mysqli_query($con,$qry);
while ($row = mysqli_fetch_array($result)){
echo "<option value='".$row['trynum']."'>".$row['tryname']."</option>";
}
$.ajax({
type: "POST",
url: "json_php_sub.php",
data: {instructor:$(this).val()},
datatype: 'json',
success: function(result){
alert(result);
document.getElementById("sub").innerHTML = result;
}
});
<select id="sub" name="subb"></select>
my problem is whether i select from dropdown the content is there but no value. pls help..
PHP:
$ajaxAnswer = "<option value=\"\">"."Select"."</option>";
$instructor = mysqli_real_escape_string($conn,$_POST['instructor']);
$qry = "select * from try where name = '".$instructor."'";
$result = mysqli_query($con,$qry);
while ($row = mysqli_fetch_array($result)){
$ajaxAnswer .= "<option value='".$row['trynum']."'>".$row['tryname']."</option>";
}
echo $ajaxAnswer;
Jquery:
$.ajax({
type: "POST",
url: "json_php_sub.php",
data: {instructor:$(this).val()},
success: function(result){
$("#sub").html(result);
}
});
data: {instructor:$('#SELECT_ELEMTN_ID').val()},
Depending on scope and stuff, you may not wanna use "this".
Jquery
$(document).ready(function () {
$.ajax({
type: "GET",
url: "phpfile.php",
dataType: "json",
success: function (data) {
$.each(data, function (idx, obj) {
$('#selectdata').append('<option value="'+obj.user_id+'">'+obj.user_name+'</option>' )
});
}
});
});
</script>
</head>
<body>
<select id="selectdata">
</select>
</body>
phpfile.php
<?php
$host = "localhost";
$user = "root";
$password ="";
$database= "databasename";
$con = mysqli_connect($host , $user , $password);
$database_connect = mysqli_select_db($con, $database);
$result = mysqli_query($con, "select Id as user_id,Name as user_name from users");
$data = mysqli_fetch_all($result, MYSQLI_ASSOC);
echo json_encode($data);
?>