I'm trying to display the search result of my page under the the search area. So I used AJAX to display the result in a div. but I could'nt get it work.
I have three main pieces, the div, the searchResult page and the ajax function
<input type="text" name="studentName">
<button type="submit" name="searchByName" onclick='get_info();'>بحث</button>
<div id="searchResult"><b></b></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type="text/javascript">
function get_info() { // Call to ajax function
$.ajax({
type: "POST",
url: "NameSearchResult.php", // Name of the php files
data: {name: <?php echo $_POST['studentName']; ?>},
success: function(html)
{
$("#searchResult").html(html);
}
});
}
and my search Page:
<?php
include_once 'dbConfigBDO.php';
$studentName = $_POST["name"];
$counter=0;
$emptyString = "لايوجد";
$sql = "SELECT * FROM Student";
$result = $conn->query($sql);
$row_count = $result->rowCount();
if ($row_count > 0){
.......... }
Now when I search nothing appears, although it works when I put all the code in one page (which would be messy in term of the appearance of the result!).
From function return the output as per below:
return json_encode($result);
In ajax call use dataType:"json" and show your html
Example ajax call:
$.ajax({
type: "POST",
dataType:"json",
url: "NameSearchResult.php", // Name of the php files
data: {name: $("#studentName").val()},
success: function(html)
change code like this
<input type="text" name="studentName" id="studentName">
<button type="submit" name="searchByName" onclick='get_info();'>بحث</button>
<div id="searchResult"><b></b></div>
<script>
$.ajax({
type: "POST",
url: "NameSearchResult.php", // Name of the php files
data: {name: $("#studentName").val()},
success: function(html)
{
$("#searchResult").html(html);
}
});
}
</script>
inside ajax success method try catch what you are getting
success: function(html)
{
console.log(html);
}
if you getting something then your code must be work.
Related
I am trying to conctenate/embed database value from php script into my api URL
but i don't know how to get it right, I am not familiar with php
it needs to embed the varible from DB in order to access API values like this
api/rfq/1 (example)
I tried this so far
php code:
<?php
require_once('connection.php');
session_start();
if(!$con){
die('Please Check Your Connection'.mysqli_error());
}else{
$query="select BusinessID from business where username='".$_SESSION['User']."'";
$result=mysqli_query($con,$query);
while($row =mysqli_fetch_array($result)){
$results[]=implode($row['BusinessID']);
}
echo json_encode($results);
// echo 'Works ASF '+$hey;
}
?>
jQuery file:
$(function() {
$.getJSON('getID.php', function(data) {
$.each(data, function() {
alert(data.column);
})
})
var $hello = $('#hello');
$.ajax({
type: 'GET',
dataType: "json",
url: 'http://slimapp/api/rfq/"'+$_SESSION['User']+'"',
success: function(hello){
$.each(hello, function(i,order){
$hello.append('<div class="panel panel-default"><div class="panel-thumbnail"></div><div class="panel-body"><p class="lead"><b><img src="assets/img/Profile.png" height="28px" width="28px">'+order.Title+'<i class="glyphicon glyphicon-plus"></i>Make Bid</b></p><p><img src="assets/img/RFQ.png" height="28px" width="28px">'+order.Description+'</p><p><img src="assets/img/Clock.png" height="28px" width="28px">'+order.Date+'</p><hr/><p><img src="assets/img/email.png" height="28px" width="28px">'+order.email+'</p><p><img src="assets/img/Phone.png" height="28px" width="28px">'+order.cellphone+'<p><textarea class="form-control" placeholder="Comment"></textarea><br/><li id="btn1"></li><button class="btn btn-success pull-left" type="button" style="border-radius:12px">Comment</button></p></div></div>');
})
}
})
});
I expect to get data from url like this http://slimapp/api/rfq/1
You Jquery file should look like this:
function apiCall(user) {
var url = 'http://slimapp/api/rfq/'+ user +''; // This var is creating the right URL, using the parameter USER of the function
$.ajax({
type: 'GET',
dataType: "json",
url: url, // Calling the new right URL
success: function(hello){
// Handle your success
}
})
};
Here you are creating a new function, that receives the parameter User that you wanna pass in the URL.
Your PHP file should look like this:
<?php
$results = '1';
?>
<script>
apiCall(<?php echo $results ?>); // Passing the value 1 as a parameter for the function
</script>
Here you are calling the function apiCall and passing the value of the variable $results as parameter.
What I'm trying to do is to edit mysql records using php. I've used Ajax/Json to edit a single record, but the problem is my codes isn't working. I tried to alert the value of input element after I clicked the save button and the alert output is verified. And also I don't get any message in console.
Here's what I got right now. Any help will appreciate.
Index.php
<div class="entry-form1">
<form action="" method="post">
<input type="text" name="id_edit" id="id_edit" class="inputs_edit">
<input type="text" name="approved_edit" id="approved_edit" class="inputs_edit">
<input type="submit" name="save_edit" id="save_edit" value="Save"/>
</form>
</div>
Search.php
$query1 = $mysqli->query(""); // not to include
while($r = $query1->fetch_assoc()){
<td><a href='#' name='".$r['id']."' id='".$r['pr_id']."' class='edits'>Edit</a></td>
}
<script>
$(document).ready(function(){
$(".edits").click(function(){
$(".entry-form1").fadeIn("fast");
//not to include some parts of codes
$.ajax({
type: "POST",
url: "auto-complete.php",
data :edit_post_value,
dataType:'json',
success:function(data){
var requested=data.requested;
var id=data.id;
//send to element ID
$('#id_edit').val(id);
$('#requested_edit').val(requested);
}
});
$("#save_edit").click(function () {
var two = $('#id_edit').val();
var five = $('#requested_edit').val();
alert(five);
$.ajax({
type: "POST",
url: "item_edit.php",
data: "id_edit="+two+"&requested_edit="+five,
dataType:'json',
success: function(data){
console.log(JSON.stringify(data))
if(data.success == "1"){
$(".entry-form1").fadeOut("fast");
//setTimeout(function(){ window.location.reload(); }, 1000);
}
}
});
});
});
</script>
Item_edit.php
<?php
$mysqli = new mysqli("localhost", "root", "", "app");
if(isset($_POST['id_edit'])) {
$id_edit= $_POST['id_edit'];
$requested_edit= $_POST['requested_edit'];
$sql = $mysqli->query("UPDATE pr_list SET requested='$requested_edit' WHERE id='$id_edit'");
if($sql){
echo json_encode(array( "success" => "1"));
}else{
echo json_encode(array("success" => "0"));
}
}
?>
1) First, you're not capturing the click event, because $("# save_edit") is within a function that is not being called. So, you're not even sending the form to the server.
2) Second, the way a form works by default send the data and then reload the page, you must call the preventDefault() function from the event object captured to prevent it, before making the ajax call.
try this:
$(document).ready(function(){
$("#save_edit").click(function (e) {
e.preventDefault(); //prevent a page reload
var two = $('#id_edit').val();
var five = $('#requested_edit').val();
alert(five);
$.ajax({
type: "POST",
url: "/item_edit.php",
data: "id_edit="+two+"&requested_edit="+five,
dataType:'json',
success: function(data){
console.log(JSON.stringify(data));
if(data.success == "1"){
$(".entry-form1").fadeOut("fast");
//setTimeout(function(){ window.location.reload(); }, 1000);
}
}
});
});
});
I am using Twitter Bootstrap Typeahead for an autocomplete field.
End state goal: The user first enters details into field 1. When they enter details in field 2, ajax passes the query as it is written to a PHP file which queries a database based on what was also entered into field 1.
How do I pass both the query from field 2 and the contents of field 1 to the PHP file and access them.
Here is what I have so far:
HTML FILE:
<div class="field1">
<input type="text" id="field1" data-provide="typeahead" name="field1">
</div>
<div class="field2">
<input type="text" id="field2" data-provide="typeahead">
</div>
<script src="js/jquery-1.9.1.min.js"></script>
<script src="js/bootstrap.js"></script>
<script>
$(function() {
$("#field2").typeahead({
source: function(query, process) {
var textVal=$("#field1").val();
$.ajax({
url: 'field2.php',
type: 'POST',
data: 'query=' + query,
dataType: 'JSON',
async: true,
success: function(data) {
process(data);
console.log(textVal);
}
});
}
});
});
</script>
PHP FILE:
if (isset($_POST['query'])) {
$db_server = mysql_connect("localhost", "root", "root");
mysql_select_db("db_test");
$query = $_POST['query'];
$other = '**This needs to be field 1**';
$sql = mysql_query("SELECT * FROM table WHERE row1 LIKE '%{$query}%' AND row2 = '$other'");
$array = array();
while ($row = mysql_fetch_assoc($sql)) {
$array[] = $row['row1'];
}
echo json_encode($array);}
At the moment, the query part works perfectly and the results are returned (the console also displays the value from 'Field1'. Just need to get that value into the php file at the same time!
Any help would be great
If I understood this correctly, you want to parse both the values of field 1 and 2 to the same AJAX call. This is how you do it.
<script>
$(function() {
$("#field2").typeahead({
source: function(query, process) {
var textVal=$("#field1").val();
$.ajax({
url: 'field2.php',
type: 'POST',
data: 'query=' + query + '&field1=' + textVal,
dataType: 'JSON',
async: true,
success: function(data) {
process(data);
console.log(textVal);
}
});
}
});
});
</script>
Now you just make another $_POST['field1'] in your PHP file.
var userQuery = $('#ID of query input element').val();
var field1 = $('#ID of input 1 element').val();
$.ajax({
type: "POST",
url: '',
data: {query: QueryVariable, input1: input1variable},
success: function(data) {
// code within this block
},
error: function() {
alert('System Error! Please try again.');
},
complete: function() {
console.log('completed')
}
}); // ***END $.ajax call
Apologies if this has been answered before (I couldn't find the answer when I searched the archives)
I've got a page protected by a password:
<?php
if($_POST['pw'] == 'pw')
{
//Page content
} else
{
//Display password form
}
?>
Within the page content, I've got another form, which I want to submit using jQuery, and have the following code:
<script type='text/javascript'>
var dataString = $('input#input1').val();
$(function() {
$('#submit').click(function()
{
$.ajax({
type: 'POST',
url: 'p2.php',
data: dataString,
dataType: html,
success: function(data2) {
$('#testResult').html(data2);
}
});
return false;
});
});
</script>
<form name='form1' id='form1' action=''>
<fieldset>
<label for='input1' id='input1_label'>Input 1</label>
<input type='text' name='input1' id='input1' size='30' />
<input type='submit' value='Update / reset' id='submit' class='buttons' />
</fieldset>
</form>
<div id='#testResult'></div>;
However, clicking submit then sends the form to p1.php?input1=test (i.e., the data string is being sent to p1.php, not p2.php). If I edit the code and remove dataType:html and the 2 references of data2, then this doesn't happen (infact, nothing happens, so I assume that jQuery is submitting the data to the form). I've also changed the type to 'GET', incase the 2 POST requests on the same page were causing problems, but this didn't change the result.
What am I missing to get the information from p2.php (i.e. data2) and displaying it?!
EDIT
Thanks to a comment pointing out a typo, I've changed dataType: html to dataType: 'html' - this now doesn't cause the page to redirect to p1.php?input1=test, but once again, it doesn't do anything (when it should still be returning the value of data2)
EDIT 2
I've updated the code so dataString is now:
var dataString = $('input#input1').val();
dataString = 'var1='+dataString;
but this hasn't made any difference
For clarification, my p2.php just contains the following:
<?php
echo "<p>HELLO!</p>";
?>
EDIT 3
I made the changes to my code has suggested by Damien below; I get the alert of "works!" but still nothing seems to be returned from p2.php, and nothing is inserted into the #testResult div.
var dataString = $('input#input1').val();
$(function() {
$('#submit').click(function(evt)
{
evt.preventDefault();
$.ajax({
type: 'POST',
url: 'p2.php',
data: "someval="+dataString,
dataType: 'html',
success: function(data2) {
$('#testResult').html(data2);
}
});
return false;
});
});
$(function() {
$('#submit').click(function()
{
var dataString = $('#form1').serialize();
$.ajax({
type: 'POST',
url: 'p2.php',
data: dataString,
success: function(data2) {
alert('works!'); // ADDED AFTER UPDATE
$('#testResult').html(data2);
},
/* ADDED AFTER UPDATE */
error:function(obj,status,error)
{
alert(error);
}
});
return false;
});
});
Edit:
In p2.php:
<?php
var_dump($_POST['pw']);
?>
In p2.php you then need to output ( using echo, for example) what you want to be returned as 'data2' in your ajax success call.
UPDATE:
Since you're Ajax request fires succesfully, that means either your post is not passed correctly, or you're not outputting anything. I've re-looked at your code and I saw this:
<input type='text' name='input1' id='input1' size='30' />
that means you're fetching the wrong $_POST variable!
Do this:
Since you're sending a name="input1", in your p2.php try with:
<?php
if(isset($_POST['input1'])
{
echo $_POST['input1'];
}
else
{
echo 'No post variable!';
}
And in your jquery success:
success: function(data2) {
alert(data2);
$('#testResult').html(data2);
},
That oughta work, if you follow it literally. In the remote possibility it won't work, forget AJAX, remove the javascript and do a normal post submitting with p2.php as an action of your form :)
I think you have to prevent the default action of the form.
Try this:
$('#submit').click(function(e)
{
e.preventDefault();
$.ajax({
type: 'POST',
url: 'p2.php',
data: dataString,
dataType: html,
success: function(data2) {
$('#testResult').html(data2);
}
});
return false;
});
});
The data should be formatted like this:
variable1=value1&variable2=varlue2
I also think you can remove the dataType property.
Ok, so I have this search box in which people typein a food item. When they press the button I need that input to be send to a .php file. That php file will look op the calories of that food item (thats in my database) and output the food item name and calories. All this need to be done without reloading the page so I started figuring out how JQuery works.
However I am stuck, I don't know what to put in the data field of the jquery function and how I can 'catch' that data in the .php file. Can someone give me an idea? thanks a lot! (see the ??????'s for things i don't understand). Also, the data that comes back needs not to be in an alert box in the end, but update some table on my page, how can i do this? which JSON (?) Jquery function do I need?
what I have up until now:
in head:
<script type="text/javascript">
function contentDisp()
{
$.ajax({
type: 'POST',
url: 'getFood.php',
data: '????????',
success: function(data){
alert("Data Loaded: " + data);
}
});
}
</script>
and in body:
<form autocomplete="off">
<p>
Product:
<input type="text" name="food" id="food" class="food_name_textbox" onmouseover="javascript: this.className='food_name_textbox_mouseover';" onmouseout="javascript: this.className='food_name_textbox';" / >
</p>
<button id="zoek" type="button" onClick="contentDisp();">Zoek</button>
</form>
and in getFood.php:
<?php
require_once "config.php";
$id = "??????"
$result = mysql_query("SELECT * FROM voedingswaarden WHERE voedsel='$id'");
$row = mysql_fetch_array($result);
echo json_encode($row);
?>
$.ajax({
type: 'POST',
url: 'getFood.php',
data: {'foodnametextbox' : $('#food').val() },
datatype: "json",
success: function(data){
$('#table').html(data);
}
});
<?php
require_once "config.php";
$id = $_POST['foodnametextbox']; //escape and validate this input before using it in a query
$result = mysql_query("SELECT * FROM voedingswaarden WHERE voedsel='$id'");
$row = mysql_fetch_array($result);
echo json_encode($row);
?>
<script type="text/javascript">
function contentDisp()
{
var textSearch = $("#myText").text();
$.ajax({
type: 'POST',
url: 'getFood.php',
data: textSearch,
success: function(data){
alert("Data Loaded: " + data);
}
});
}
</script>
PHP:
$id = $_POST['textSearch'];