I'm stuck here for about 4 hours do alot of research and cannot fin the answer.
I want to repopulate the table after updating the contents using jquery ajax and php so here is my code.
PHP script:
if(isset($_POST['myinputval']))
{
$uinput = $_POST['myinputval'];
$uinput = $mysqli->real_escape_string($uinput);
$query = ('INSERT INTO tbltest values (" ","'.$uinput.'") ');
if($mysqli->query($query))
{
} else
echo 'fail'. $mysqli->error;
}
$result= $mysqli->query("Select *from tbltest");
if($result->num_rows>0)
{
while($row=$result->fetch_assoc())
{
$sendtojq[]=$row;
}
echo json_encode($sendtojq);
}
mysqli_close($mysqli);
Here is my script
<script type="text/javascript">
function ajaxsubmit()
{
var myinputval = $("#input1").val();
$.ajax({url:'myphp.php', type:'post', data:{
myinputval:myinputval
},
success: function(data)
{
alert(data);
}
});
}
</script>
This is the output when submitted
[{"ID":"1","NAME":".$newinput."},{"ID":"2","NAME":".$newinput."},{"ID":"3","NAME":".$newinput."},{"ID":"4","NAME":".$newinput."},{"ID":"5","NAME":".$newinput."},{"ID":"6","NAME":".$newinput."},{"ID":"7","NAME":"$newinput"},{"ID":"8","NAME":"twst"},{"ID":"9","NAME":"twst"},{"ID":"10","NAME":"testtt"},{"ID":"11","NAME":"testtt"},{"ID":"12","NAME":"thisssss"},{"ID":"13","NAME":"thisssss"},{"ID":"14","NAME":"tstet"},{"ID":"15","NAME":"Last"},{"ID":"16","NAME":""},{"ID":"17","NAME":"dddddddd"},{"ID":"18","NAME":"aaaaaaaaaaa"},{"ID":"19","NAME":"gggggggggggggggggggggg"},
Now what I want to do is get every single element of the array which is stored in the variable 'data' and use is at as the value of my table. Any suggestions? Thanks in advance.
Related
Can anyone help me to solve this problem I want to populate the dropdown with ajax. when I insert data in database I want it to display on the select option without refreshing .This dropdown is not based on other dropdown. There is no other dropdown. only a single Dropdown.
html
<select name="id" id="id"></select>
jQuery
<script type="text/javascript">
function bedrooms(){
$('#id').empty();
$('#id').append("<option>loading........</option>");
$.ajax({
type:"POST",
url:"checking_database.php",
contentType:"json",
success:function(data){
$('#id').empty();
$.each(data,function(i,item){
$('#id').append('<option>"'+data[i].number_of_bedrooms+'"</option>');
});
},
complete:function(){
}
});
}
$(document).ready(function(){
bedrooms();
});
</script>
checking_database.php
<?php
$data = array();
$con=mysqli_connect("localhost","root","","price");
$query = mysqli_query($con,"select * from bedroom");
if(mysqli_num_rows($query)){
while($row = mysqli_fetch_array($query)){
$data[] = array("number_of_bedrooms" => $row['number_of_bedrooms']);
};
header('Content-type: application/json');
echo json_encode($data);
}
?>
Output
Required output: show the data as a option without refresing.
Can anyone tell me the answer how i resolve this problem.i am in learning phase of the ajax and the php. i also google about it but i found the dropdown which based on each other.Thank You
var last_bedroom_data
function bedrooms(){
if(!last_bedroom_data){
$('#id').empty();
$('#id').append("<option>loading........</option>");
}
$.ajax({
type:"POST",
url:"checking_database.php",
contentType:"json",
success:function(data){
if(last_bedroom_data==JSON.stringify(data)) // data is the same
return; // skip rendering of html
updateBedroomSelect(data);
last_bedroom_data = JSON.stringify(data);
},
complete:function(){
}
});
}
function updateBedroomSelect(data){
$('#id').empty();
$.each(data,function(i,item){
$('#id').append('<option>"'+data[i].number_of_bedrooms+'"</option>');
});
}
$(document).ready(function(){
bedrooms();
setInterval(bedrooms,3000);
});
i have a task which is very complicated for me and also explain to you.. I will give my summary on what i m supposed to do.. there are 3 files which are the
1.html file which perform ajax post to the passwrapper.php
2. passwrapper.php will receive the ajax post request and include another file which is 3.student.php which contain codes on how to perform connection to the database and convert all data to json and then show all the data..
I was asked to perform ajax post multiple items.. In other words, i was asked to receive name and religion from the last row of database.. here is my code below...
html file
<html>
<head>
<script type="text/javascript" src="/Cesium-1.34/ThirdParty/jquery-1.11.3.min.js"></script>
</head>
<div id="resulte"</div>
<script type="text/javascript">
showData();
function showData()
{
$.ajax({
type: "post",
url: "passwrapper.php",
dataType: "json",
data: {
lastName: true,
lastReligion: true,
},
success: function(data){
console.log(data);
},
error: function(jqXHR, textStatus, errorThrown) {
alert('An error occurred... Look at the console (F12 or Ctrl+Shift+I, Console tab) for more information!');
$('#resulte').html('<p>Status Code: '+jqXHR.status+'</p><p>ErrorThrown: ' + errorThrown + '</p><p>jqXHR.responseText:</p><div>'+jqXHR.responseText + '</div>');
console.log('jqXHR:');
console.log(jqXHR);
console.log('textStatus:');
console.log(textStatus);
console.log('errorThrown:');
console.log(errorThrown);
},
});
};
</script>
</body>
</html>
passwrapper.php
<?php
include 'student.php';
if ((!isset($_POST["lastName"])) and (!isset($_POST["lastReligion"]))){
executePass();
}
else
{
//how to get name and religion from the last row and then perform executepass() to show all data and also data from the last row
}
?>
student.php
<?php
function executePass()
{
$conn = mysqli_connect('localhost','root','netwitness') or die ("Could not connect database");
$db = mysqli_select_db($conn,'abdpractice') or die ('Could not select database');
$result = mysqli_query($conn,"select * from student");
$json_array = array();
while ($row = mysqli_fetch_assoc($result))
{
$json_array[] = $row;
}
echo json_encode($json_array);
}
my question is how to get last data from the last row which are student_name and student_religion in the passwrapper.php and also perform executepass() to show all data... please do not modify the sql code. i also do not want get data from the success. for example: data[count(data)-1]['student_name']...
my question is how to get the last values which are student_name and student_religion in the passwrapper.php... and also perform the executepass() function to show all data.. please help me... you can write the last data to the files or show in the html console..
Best would be to change executePass() so it ends with return $json_array; instead of echoing it. Then passwrapper.php could do:
$students = executePass();
if ((!isset($_POST["lastName"])) and (!isset($_POST["lastReligion"]))){
echo json_encode($students);
}
else {
file_put_contents("all_students.json", json_encode($students);
$last_student = end($students);
echo json_encode(array($last_student));
}
And other scripts that want to return all the students can do:
$students = executePass();
echo json_encode($students);
If you can't do that, use the output buffering functions to capture the output from executePass() instead of sending it to the client.
else {
ob_start();
executePass();
$json = ob_end_clean();
file_put_contents("all_students.json", $json);
$students = json_decode($json, true);
$last_student = end($users);
echo json_encode(array($last_student));
}
I have this section of code that is suppose to get the Values of the input fields and then add them to the database. The collection of the values works correctly and the insert into the database works correctly, I am having issue with the data posting. I have narrowed it down to the data: and $__POST area and im not sure what I have done wrong.
JS Script
$("#save_groups").click( function() {
var ids = [];
$.each($('input'), function() {
var id = $(this).attr('value');
//Put ID in array.
ids.push(id);
console.log('IDs'+ids);
});
$.ajax({
type: "POST",
url: "inc/insert.php",
data: {grouparray: ids },
success: function() {
$("#saved").fadeOut('slow');
console.log('Success on ' + ids);
}
});
});
PHP Section
<?php
include ('connect.php');
$grouparray = $_POST['grouparray'];
$user_ID = '9';
$sql = "INSERT INTO wp_fb_manager (user_id, group_id) VALUES ($user_ID, $grouparray)";
$result=mysql_query($sql);
if ($result === TRUE) {
echo "New records created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysql_error();
}
?>
You cannot send an array trough an ajax call.
First, use something like:
var idString = JSON.stringify(ids);
And use it: data: {grouparray: idString },
On the PHP side:
$array = json_decode($_POST['grouparray']);
print_r($array);
I'm developing a simple guestbook and I want to update the table with all messages without refreshing the page because if someone it's writing a comment and the page refreshes the comment will be lost.
So I began writing some code with ajax to update the table but I don't know how to send an array (with comment, username, date ecc) from php to ajax.
In the database I have a column named "wrote" and it can be 0 (unread) or 1 (read). 1 it's when the messages it's already on the table.
This is what I've done since now, maybe it's wrong
getGuest.php
<?php
include("Database.php");
$Database = new Database( "localhost", "root", "1234");
$Database->connectToServer();
$Database->connectToDatabase("test");
$result = $Database->unreadMessages();
$rows=mysql_fetch_array($result);
echo json_encode($rows);
?>
Script.js
window.onload = function(){
interval = window.setInterval('updateGuest()',5000);
}
function updateGuest() {
$.ajax({
url: 'getGuest.php',
method: 'get',
success: on_getGuest_success,
error: on_error
});
}
function on_getGuest_success(data) {
for(var i=0; i<data.length;i++) {
// HERE I WANT TO ADD A ROW WITH ALL MESSAGE UNREAD BUT I DONT KNOW WHAT I HAVE TO DO
}
}
function on_error() {
//do something
}
Make sure the JSON contains an array
Add headers
use getJSON
Like this:
PHP
$data = array();
while ($row = mysql_fetch_assoc($result)) {
$data[] = $row;
}
header("content-type: application/json");
echo json_encode($data);
JS:
$(function() { // when page has loaded
var tId = setInterval(function() { // save the tId to allow to clearTimeout if needed
$.getJSON("getGuest.php",function(data) { // call the server using jQuery's JSON access
$('.guestbook').empty(); // empty the container
var rows = []; // create an array to hold the rows
$.each(data,function(_,item) { // loop over the returned data adding rows to array
rows.push('<tr><td class="name" width="10%">' + item.name + '</td></tr>');
});
$('.guestbook').html(rows.join()); // insert the array as a string
});
},5000); // every 5 secs
});
I would personally only return what was new since last time
I am trying to call a PHP script in my main PHP file.Below is the Jquery/Ajax part of the main php file. The display_stationinfo.php is supposed to create the DIVs in the main but it isnt.
this is what I tried so far, im new to Jquery and AJAX. thanks in advance!
working fiddle: http://jsfiddle.net/52n861ee/
thats what I want to do but when I click on desk_box DIV, the toggle station_info DIV is not being created by my display_stationinfo.php script.
When I view source code both DIVs are supposed to be already created but only desk_box is.. what am I doing wrong?
JQuery/AJAX part:
<div id="map_size" align="center">
<script type="text/javascript">
//Display station information in a hidden DIV that is toggled
//And call the php script that queries and returns the results LIVE
$(document).ready(function() {
$(".desk_box").click(function() {
alert("before toggle");
var id = $(this).attr("data")
alert(id);
alert($(this));
$("#station_info_"+id).toggle();
alert("after toggle");
$.ajax({
url: 'display_stationinfo.php',
type: 'GET',
success: function(result) {
alert("before result");
$("#station_info_"+id).html(result);
alert("result: " + result); //it shoes every DIV being created and not the one that I clicked on
alert("after result");
}
});//end ajax
});//end click
});//end ready
</script>
</div> <!-- end map_size -->
display_station.php (script that I want to call):
<?php
include 'db_conn.php';
//query to show workstation/desks information from DB for the DESKS
$station_sql = "SELECT coordinate_id, x_coord, y_coord, section_name FROM coordinates";
$station_result = mysqli_query($conn,$station_sql);
//see if query is good
if ($station_result === false) {
die(mysqli_error());
}
//Display workstations information in a hidden DIV that is toggled
while ($row = mysqli_fetch_assoc($station_result)) {
//naming values
$id = $row['coordinate_id'];
$x_pos = $row['x_coord'];
$y_pos = $row['y_coord'];
$sec_name = $row['section_name'];
//display DIV with the content inside
$html = "<div class='station_info_' id='station_info_".$id."' style='position:absolute;left:".$x_pos."px;top:".$y_pos."px;'>Hello the id is:".$id."</br>Section:".$sec_name."</br></div>";
echo $html;
}//end while loop for station_result
mysqli_close($conn); // <-- DO I NEED TO INCLUDE IT HERE OR IN MY db_conn.php SINCE IM INCLUDING IT AT THE TOP?
?>
"SELECT coordinate_id, x_coord, y_coord, section_name FROM coordinates";
Is fetching every row from the table coordinates, is this what you want to do? Or do you just want to return only the row with the id the users clicked?
jQuery
$.ajax({
url: 'display_stationinfo.php',
data: { 'id': id },
type: 'POST',
success: function(result) {}
});
php
$id = $_POST['id']
"SELECT coordinate_id, x_coord, y_coord, section_name FROM coordinates WHERE coordinate_id == " $id;
Looking at you example, I would also guess that the problem could be that you are returning a string and putting it inside the target div so that the finished div looks somthing like this:
<div class="station_info_" id="station_info_84" style="position: absolute; left: 20px; top: 90px; display: block;">
<div class="station_info_" id="station_info_84" style="position:absolute;left:20px;top:90px;">
Hello the id is:84<br>
Section:Section B<br>
</div>
</div>
Instead of returning a string you could return a json object and append only data to the target div
php
while ($row = mysqli_fetch_assoc($station_result)) {
$id = $row['coordinate_id'];
$x_pos = $row['x_coord'];
$y_pos = $row['y_coord'];
$sec_name = $row['section_name'];
$result = array('id' => $id, 'x_pos' => $x_pos, 'y_pos' => $y_pos, 'sec_name' => $sec_name);
echo json_encode($array);
}
jQuery
$.ajax({
url: 'display_stationinfo.php',
data: { 'id': id },
type: 'POST',
dataType: "json",
success: function(json) {
$("#station_info_"+id)
.css({'left':json.x_pos ,'top': json.y_pos})
.append('<p>Hello the id is:'+ json.id +'</br>Section:'+ json.sec_name +'</p>');
}
});