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);
Related
I am using ajax call for sending value to php file and get response back into first page,(work fine), but when i am getting the result in loop form this response nothing will be return on first page.
My first page:
$.ajax({
url: "action.php",
method: "post",
data: {
'trader': selected_trader
},
dataType: 'JSON',
success: function (response) {
$('#date').html(response['date']);
$('#symbol').html(response['symbol']);
$('#status').html(response['status']);
$('#alert').html(response['alert']);
$('#company_name').html(response['company_name']);
}
})
My 2nd page:
if (isset($_POST['trader'])) {
$trader = $_POST['trader'];
$sql = "Select * from current_trader where status='$trader' ";
$result = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_assoc($result)) {
$data["date"] = date('Y:m:d', strtotime($row['date']));
$data["symbol"] = $row['symbol'];
$data["company_name"] = $row['company_name'];
$data["alert"] = $row['alert'];
$data["status"] = $row['status'];
echo json_encode($data);
}
}
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);
}
I would like to insert the date from datepicker into my msql database but the error function is called in ajax query instead of success and the date is not inserted.
HTML:
<form id="dForm">
<input type="date" name="date" id="date">
<input type="submit" name="submit" id="submit" value="Submit">
</form>
JAVASCRIPT:
$(function(){
$("#my-page").submit(function(e){
e.preventDefault();
var formData = $("#dForm :input")
.datepicker("getDate").serialize();
console.log(formData);
$.ajax({
url: "php/file.php",
type: "POST",
data: formData,
dataType: "json",
async: "false",
encode: true,
success: function(response)
{
if(response.status == 'success')
{
console.log(response);
$.mobile.changePage("#next-page");
}
},
error: function(response)
{
alert("error.");
console.log(response);
}
});
});
});
PHP:
include_once("db.php");
if(!empty($_POST["date"])){
$date = strtotime($_POST["date"]);
$date = date("Y-m-d",$date);
$q = "INSERT INTO table (date) VALUES ('$date')";
$res = ($q);
$array = array();
if (mysqli_query($conn, $res)) {
$array["status"] = "success";
$array["message"] = "successful";
$array["date"] = $form_date;
}else{
$array["status"] = "error";
$array["message"] = "failed";
header('HTTP/1.1 401 Unauthorized', true);
}
echo json_encode($array);
}
The date picker works correctly and shows the date selected in the textfield but I cannot insert the date selected. I believe it may be an error regarding the php. Help would very much be appreciated.
Just a typo mistake: Instead of $("#da") you have to write $("#dat")
See https://jsfiddle.net/kkybs254/
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();
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);
?>