what is the most accepted way of retrieving data without reloading, ive seen tutorials use echo encode_json(array), the tutorial im following doesnt use it, instead.. i think he opts to get the HTML area of a specific PHP page.
my index.php
$("#button").click(function() {
... some code here ....
$.ajax
({
type: "POST",
url: "update.php",
data: dataString,
dataType: 'html',
cache: false,
success: function(html)
{
$("#posts").prepend(html);
$("#posts").slideDown("slow");
document.getElementById('content').value='';
document.getElementById('content').focus();
}
});
});
Upon success, I want to retrieve the data from my MYSQL and print it on my #posts DIV.
my update.php includes
inserting data into mysql
selects/retrieve data from mysql
echoes the data from mysql_query
<?php
include("connect.php");
if (isset($_POST['submit']))
{
$status = $_POST['status']; //get textarea value
mysql_query("insert into messages (msg) values ('$status')");
}
$sql = mysql_query("SELECT msg,msg_id FROM messages order by msg_id desc");
$row = mysql_fetch_array($sql);
$msg = $row['msg'];
$msg_id = $row['msg_id'];
?>
<!-- get this part -->
<li id="posts">
id:<?php echo $msg_id; ?>
text: <?php echo $msg; ?>
</li>
basically, i just want to submit a post, and displays all the posts without reloading.
You are definitely on the right track.
However you are trying to insert something with an id="posts" into an element which is already on the page with the same ID which is not correct.
Perhaps make a wrapper div with a class of posts-container and then you can return say this from PHP:
<li class="post">
id:<?php echo $msg_id; ?>
text: <?php echo $msg; ?>
</li>
and add it to your page like this:
$.ajax
({
type: "POST",
url: "update.php",
data: dataString,
dataType: 'html',
cache: false,
success: function(html)
{
$(".post-container").prepend(html);
$(".post-container").slideDown("slow");
document.getElementById('content').value='';
document.getElementById('content').focus();
},
//adding an error function
error: function(error){
//do whatever you need to handle you error here
console.log(error);
}
});
Related
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.
I'm using the Wikipedia API to pull and display information about topics.
The code I have works fine for a single topic:
$(document).ready(function(){
$.ajax({
type: "GET",
url: "http://en.wikipedia.org/w/api.php?action=parse&format=json&prop=text§ion=0&page=Dementia&callback=?",
contentType: "application/json; charset=utf-8",
async: false,
dataType: "json",
success: function (data, textStatus, jqXHR) {
var markup = data.parse.text["*"];
var i = $('<div></div>').html(markup);
// remove links as they will not work
i.find('a').each(function() { $(this).replaceWith($(this).html()); });
// remove any references
i.find('sup').remove();
// remove cite error
i.find('.mw-ext-cite-error').remove();
$('#article').html($(i).find('p'));
},
error: function (errorMessage) {
}
});
});
<div id="article"></div>
In the code above, the topic is "Dementia" shown by:
&page=Dementia
The code above works fine for a SINGLE topic, but now I'd like to modify it to loop through an ARRAY of topics, and use the "wikipedia_page_url" value from each topic in the array to determine which page to pull, and then output the content for each topic on the page:
<?php foreach ($resident_conditions as $resident_condition) { ?>
<?php
$condition_id = $resident_condition['condition_id'];
$condition = sw::shared()->conditions->getForID($condition_id);
$wikipedia_page_url = $condition['wikipedia_page_url'];
?>
<h6><?php echo $condition['condition_name']; ?></h6>
<div id="<?php echo $condition['condition_name']; ?>">
<!-- This is where I want to place the content pulled from Wikipedia for each topic -->
</div>
<?php } ?>
The "wikipedia_page_url" value of each topic determines which page to pull from Wikipedia, demonstrated in the code below:
How can I modify the JS script above to work pull and display the content for each topic? I know I need to substitute the value of each "wikipedia_page_url" inside the script like this:
url: "http://en.wikipedia.org/w/api.php?action=parse&format=json&prop=text§ion=0&page=<?php echo $condition['wikipedia_page_url']; ?>&callback=?",
But I dont know where to take it from here. Any suggestions?
$(document).ready(function(){
$.ajax({
type: "GET",
url: "http://en.wikipedia.org/w/api.php?action=parse&format=json&prop=text§ion=0&page=Tourette_syndrome&callback=?",
contentType: "application/json; charset=utf-8",
async: false,
dataType: "json",
success: function (data, textStatus, jqXHR) {
var markup = data.parse.text["*"];
var i = $('<div></div>').html(markup);
// remove links as they will not work
i.find('a').each(function() { $(this).replaceWith($(this).html()); });
// remove any references
i.find('sup').remove();
// remove cite error
i.find('.mw-ext-cite-error').remove();
$('#article').html($(i).find('p'));
},
error: function (errorMessage) {
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="article"></div>
You can save the topics in an javascript array, then loop through them.
$(document).ready(function(){
var topics = ['Dementia', 'Topic2', 'Topic3'];
for(var i = 0; i < topics.length; i++) {
$.ajax({
type: "GET",
url: "http://en.wikipedia.org/w/api.php?action=parse&format=json&prop=text§ion=0&page="+topics[i]+"&callback=?",
... the rest of your ajax config
}); //end of ajax
} //end of loop
}); //end of .ready();
I am having real trouble with my AJAX request and I am not sure why. The following code seems to send to the entire web page script (as seen in both my alert box and in the console) rather than my checkbox values. Can anyone explain to me what I am doing wrong?
Here is my PHP checkbox, which has values generated by SQL, and has no submit button so the code is set up to run on change from the user:
<form id="numberOrderForm" action="testdatabase.php" method="post">
<div class="wrappers" id="multi-select1Wrapper">
<h2>Area Code</h2>
<select class="dropDownMenus" id="multi-select1" name="multi_select1[]" multiple="multiple">
<?php
//The query asking from our database
$areaCodeSQL = "SELECT ac.Number AS `AreaCode`, ac.Name AS `AreaName`
FROM `AreaCodes` ac"; //SQL query: From the table 'AreaCodes' select 'Number' and put into 'AreaCode', select Name and put into 'AreaName'
$areaCodeResults = $conn->query($areaCodeSQL); // put results of SQL query into this variable
if ($areaCodeResults->num_rows > 0) { // if num_rows(from $results) is greater than 0, then do this:
// output data of each row
foreach($areaCodeResults as $areaCodeResult) //for each item in $areCodeResults do this:
{
$areaNameAndCode = $areaCodeResult['AreaCode'] ." ". $areaCodeResult['AreaName']; //get AreaCode and AreaName from query result and concat them
$areaName = $areaCodeResult['AreaName']; // get AreaName
$areaCode = $areaCodeResult['AreaCode']; //get AreaCode
?><option class="menuoption1" name="menuAreaCode" value="<?php echo $areaCode ?>" ><?php echo $areaNameAndCode; ?></option><?php //Create this option element populated with query result variables
}
}
?>
</select>
</div>
</form>
And here is my jQuery AJAX code:
<script>
$('#multi-select1').on("change", function(){
var areaCode = $(this).val();
$.ajax({
type:"POST",
url: "testdatabase.php", //my PHP database
data: "areacode=" + areaCode,
success: function(response){
//do stuff after the AJAX calls successfully completes
alert (response);
console.log(response);
},
error : function(xhr, status, error) {
alert(xhr.responseText);
}
});
});
</script>
your data is incorrect for one.
replace:
data: "areacode=" + areaCode,
with:
data: {"areacode": areaCode},
you should also add: enctype='multipart/form-data' to your form element
Please add following line on jquery ajax call
dataType: 'json'
contentType: "application/json",
After add above code your code is like below
<script>
$('#multi-select1').on("change", function(){
var areaCode = $(this).val();
$.ajax({
type:"POST",
url: "testdatabase.php", //my PHP database
data: "areacode=" + areaCode,
dataType: 'json',
contentType: "application/json",
success: function(response){
//do stuff after the AJAX calls successfully completes
alert (response);
console.log(response);
},
error : function(xhr, status, error) {
alert(xhr.responseText);
}
});
});
</script>
I've been searching around the Internet and even in Website Development forums but luckily I Haven't found a solution to my problem.
This is the html code
<div id='bottom-right-display'>
<ul id='display-app'>
<li><a href='#' class='btn-test-1' id='123'>Testing1</a></li>
<li><a href='#' class='btn-test-2'>Testing2</a></li>
<li><a href='#' class='btn-test-3'>Testing3</a></li>
</ul>
</div>
This is the jquery code
$(".btn-test-1").click(function(){
//with the use of post
$.post("somefile.php",{id,this.id},function(data){
$("#outputarea").load("somefile.php");
});
//or
//with the use of ajax
$.ajax({
type: "POST",
url: "somefile.php",
data: {id:this.id},
success: function(result){
$("#outputarea").load("somefile.php");
}
})
});
This is the php code
<?php
require_once "connection.php";
$sorter = $_POST["id"];//------>THIS IS THE LINE OF CODE WHERE THE ERROR IS STATING ABOUT!!
$retrieve = $conn->prepare("SELECT * FROM `table1` WHERE `id` != '$sorter'");
$retrieve->execute();
$retrieve->bind_result($groupname);
while($retrieve->fetch()){
echo "<li>".$groupname."</li>";
}
?>
The problem is passing a this.id using $.post or $.ajax to php but returns an error saying Notice: Undefined index: id in C:\xampp\htdocs\somefile.php when using load but when using alert it display the result that I wanted, I even tried using isset but it is empty and no data at all. Please if you know any already answered question or solution for this please comment it T_T.
Check to see if the data is actually in the post request.
i.e.
if(isset($_POST['id'])) $sorter = $_POST['id'];
else die('ERROR: No ID set')
Then I would also check if you can send data to the server via AJAX that way. Otherwise try adding this code to your Javascript.
$(".btn-test-1").click(function(){
var $dta = new FormData();
$dta.append("id",this.id);
$.ajax({
type: "POST",
url: "somefile.php",
data: $dta,
contentType: false,
cache: false,
processData:false,
success: function(result){
$("#outputarea").html(result);
}
})
});
I think the problem is that you first send an ajax request with the id attached, but in the success callback you request somefile.php again. The second time no id is attached.
Instead you should use the result variable to get the "output" of somefile.php from the first request. The second request is not needed.
Like this:
$(".btn-test-1").click(function(){
$.ajax({
type: "POST",
url: "somefile.php",
data: {id:this.id},
success: function(result){
$("#outputarea").html(result);
}
});
});
change jquery to this and try :
$(".btn-test-1").click(function(){
var id_val = $(this).attr('id');
//with the use of ajax
$.ajax({
type: "POST",
url: "somefile.php",
data: {id:id_val },
success: function(result){
$("#outputarea").load("somefile.php");
}
})
});
Your codes seem okay. One thing that I cannot simulate though is your required 'connection.php'. Can you simplify your php code first? I mean just do echo $_POST['id'] just to make sure your preceding code(s) is not affecting your post data.
On my page I have a form that inserts a new record in to the database. On the same page there is a DIV that contains the current resultset.
What I am trying to do is refresh just that DIV (not the whole page) when the form is submitted. The DIV will then contain the latest records (including the one just added).
$('#add-variants-form').submit(function(){
$.ajax({
url: 'admin/addvariants',
type: 'POST',
dataType: 'html',
data: $(this).serialize(),
});
return false;
});
<div id="current-rows">
<?php while($variant=mysql_fetch_array($variants)) { ?>
<div class="row">
// resultset
</div>
<?php } ?>
</div>
I set $variants from within my controller (beforehand):
$variants=Catalog::getProductVariants($product['id']);
Ideally I don't want to be returning a whole load of HTML to be injected in to that DIV.
Set the new content in the success handler of ajax request. Try this
$('#add-variants-form').submit(function(){
$.ajax({
url: 'admin/addvariants',
type: 'POST',
dataType: 'html',
data: $(this).serialize(),
success: function(newContent){
$('#current-rows').html(newContent);
}
});
return false;
});
I think it is easier to use .load method, which injects the response from the server to the given div, something like:
$('#idOfYourDiv').load('/your/url', {params: params});
alternatively you can still use $.ajax, like:
$('#add-variants-form').submit(function(){
$.ajax({
url: 'admin/addvariants',
type: 'POST',
dataType: 'html',
data: $(this).serialize(),
success: function(data) {
$('#yourDiv').html(data); // html will insert response, response is stored in "data" variable
}
});
return false;
});
on php site just echo what you want to be displayed, for example
foreach($results as $result){
echo $result."<br />";
}
hope that helps
I have put the contents of the "current-rows" div into it's own seperate view file:
<div id="current-rows">
<?php include("_current-rows.php"); ?>
</div>
And in my controller 'addvariants' action I just do this:
$variants=Catalog::getProductVariants($_POST['product_id']);
include('application/view/admin/catalog/_current-rows.php');
That is the response that is passed back to my jQuery success function.