How to run a first instance of ajax jquery when page loads - php

I have a jquery and ajax that performs a query and shows a table when a button is clicked. The problem is that when the page loads for first time, the query not run and do not shows anything, so the button has to be clicked to start showing the query result.
Is there a way that the query runs when page loads? and then just use the button.
My code is:
$(document).ready(function() {
$("#display").click(function() {
$.ajax({ //create an ajax request to display.php
type: "GET",
url: "genquery.php",
dataType: "html", //expect html to be returned
success: function(response) {
$("#responsecontainer").html(response);
//alert(response);
}
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table border="1" align="center">
<tr>
<td> <input type="button" id="display" value="Buscar" /> </td>
</tr>
</table>
<div id="responsecontainer" align="center">
</div>
Thanks in advance!

Just call click() on the element to simulate a click.
$(document).ready(function() {
$("#display").click(function() {
$.ajax({ //create an ajax request to display.php
type: "GET",
url: "genquery.php",
dataType: "html", //expect html to be returned
success: function(response) {
$("#responsecontainer").html(response);
//alert(response);
}
});
}).click();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table border="1" align="center">
<tr>
<td> <input type="button" id="display" value="Buscar" /> </td>
</tr>
</table>
<div id="responsecontainer" align="center">
</div>

You could extract the function you're calling in the click handler and call it within ready.
$(document).ready(function() {
const displayContent = () => {
$.ajax({ //create an ajax request to display.php
type: "GET",
url: "genquery.php",
dataType: "html", //expect html to be returned
success: function(response) {
$("#responsecontainer").html(response);
//alert(response);
}
});
}
displayContent();
$("#display").click(displayContent());
});

Related

How to use a value imported from a database

Hey Everyone here is my question .
The code below gets data from my database and displays it both in an input field and a button. I want it to be in such a way that if i click the button it should get the value(which is imported from the db).But the problem i am facing is that all the inputs and buttons have the same ids so it only captures the value of the first button(or so i think). How can i make it in such a way that for every button i click it should have its own separate value.
<?php
$dbcon=mysqli_connect("localhost","root","");
mysqli_select_db($dbcon,"codex");
require('config/server.php');
?>
<table class="table table-striped">
<th>ID</th>
<?php
$view_users_query="select * from users";//select query for viewing
users.
$run=mysqli_query($dbcon,$view_users_query);//here run the sql
query.
while($row=mysqli_fetch_array($run))//while look to fetch the result
and store in a array $row.
{
?>
<!--here showing results in the table -->
<form id="loginForm" method="" action="" novalidate>
<tr>
<div class="panel2">
<main class="content">
<td><input name="hanis" id="hanis" type="text" value="<?php echo
$row['email']?>" autofocus /></td>
<td><button type="button" class="btn btn-success btn-block"
name="hanis" id="hanis" onclick="hanisdata()" value="<?php echo
$row['email']?>" ><?php echo $row['email']?></button><</td>
</main></div>
</div>
</div>
</form>
<?php } ?>
</tr>
<script type="text/javascript">
function hanisdata() {
var hanis=$("hanis").val();
alert(hanis);
// AJAX code to send data to php file.
$.ajax({
type: "POST",
url: "hanis.php",
data: {hanis:hanis},
dataType: "JSON",
success: function(data) {
$("#message").html(data);
$("p").addClass("alert alert-success");
},
error: function(err) {
alert(err);
}
});
}
</script>
NOTE :- Don't use same id for elements
You can get values by passing this with onclick function like onclick="hanisdata(this)"
Example
<button type="button" class="btn btn-success btn-block"
name="hanis" id="hanis" onclick="hanisdata(this)" value="<?php echo
$row['email']?>" ><?php echo $row['email']?></button>
Then you can get specific element in js and then can find parent and search for input field in that like below example.
JS CODE
<script type="text/javascript">
function hanisdata(el) {
var hanis=$(el).parent().find("input").val();
alert(hanis);
// AJAX code to send data to php file.
$.ajax({
type: "POST",
url: "hanis.php",
data: {hanis:hanis},
dataType: "JSON",
success: function(data) {
$("#message").html(data);
$("p").addClass("alert alert-success");
},
error: function(err) {
alert(err);
}
});
}
</script>

not able to pass data to controller using Ajax with jquery ,CodeIgniter (PHP framework)

passing data to controller using AJAX
this is script i have written to pass data to controller but data is not passed to the controller
this is the input data i want to pass
<div class="form-group">
<table class="table table-striped b-t b-light text-sm">
<thead>
<tr>
<th>ID</th>
<th>Question</th>
<th>answer</th>
</tr>
</thead>
<tbody>
<?php foreach ($quet as $row) { ?>
<tr>
<td ><?php echo $row['id']; ?></td>
<td>
<?php echo $row['question']; ?>
</td>
<td><input type='text' name='name' required="required" class="form-control" placeholder='Enter Your Answer'></td>
</tr>
<?php } ?>
</tbody>
</table>
</div>
<button class="btn btn-primary nextBtn btn-lg pull-right" id ="next" type="button" >Next</button>
and the script
<script>
$(document).ready(function($){
$("#next").click(function(){
var array = $("name").val()
$.ajax({
type: "POST",
datatype:"json",
url: BASE_URL+"/student/add",
data: 'data='+array,
contentType:'application/json',
processData: false,
error: function(response) {console.log('ERROR '+Object.keys(response)); },
success: function(response) {
console.log(response)
}});
return false;
});
});
</script>
and the student controller
function add(){
if($this->student_model->add($this->input->post()))
{
$response['success'] = TRUE;
}
else
{
$response['success'] = FALSE;
}
echo json_encode($response);
}
Try this. Your data may be in wrong format
data: {'data':array}
EDIT
<input type='text' name='answer' id='answer' required="required" class="form-control" placeholder='Enter Your Answer' />
<script>
$(document).ready(function($){
$("#next").click(function(){
var array = $("#answer").val() // see the change name to id, see the html also
$.ajax({
type: "POST",
url: BASE_URL+"/student/add",
data:{'data':array},
error: function(response) {console.log('ERROR '+Object.keys(response)); },
success: function(response) {
console.log(response)
}});
});
});
</script>
Also check the array is received properly in you JS
<script>
$(document).ready(function($){
$("#next").click(function(){
var array = $("#id").val()
$.ajax({
type: "POST",
datatype:"json",
url: BASE_URL+"/student/add",
data: {
'data':array
},
contentType:'application/json',
processData: false,
error: function(response) {console.log('ERROR '+Object.keys(response)); },
success: function(response) {
console.log(response)
}});
return false;
});
});
</script>
In your controller you should change $this->input->post() to$this->input->post('data')
From your mentioned code, you need to check these points :
1) As you are using contentType:'application/json', so use the data format as data: {'data':array}
2) Finally check whether the url url: BASE_URL+"/student/add", is accessible or not.
Hope this helps :)
You need to change following in your code.
In the Script
<script>
$(document).ready(function($){
$("#next").click(function(){
var array = $("input[name]").val();
$.ajax({
type: "POST",
url: BASE_URL+"/student/add",
data: {'data':array},
error: function(response) {console.log('ERROR '+Object.keys(response)); },
success: function(response) {
console.log(response)
},
datatype:"json"
});
return false;
});
});
</script>
In the Student Controller
function add(){
if($this->student_model->add($this->input->post('data')))
{
$response['success'] = TRUE;
}
else
{
$response['success'] = FALSE;
}
echo json_encode($response);
}
I hope this help.

Ajax multiple input not showing all data?

I'm stuck in multiple input. My code is not showing all data. below is the html I am using:
<form id="matkul" class="form-horizontal" method="POST">
<table class="table table-condensed">
<thead>
<tr>
<th>Matakuliah</th>
<th>Data Lain</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</form>
<button id="post" type="submit">Save</button>
<button id="get">Get Data!</button>
below is the code to get the data
<script>
$(document).ready(function() {
$("#get").click(function() {
var url = 'https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20html%20where%20url%3D%22https%3A%2F%2Funisys.uii.ac.id%2Fuii-ras%2Fmatakuliah.asp%3Fidx%3D1%26session_id%3DxxbKiKJawuyrbaaiJ3Kabybabi3JJiKJrJyb3wiuKbbry0JbKiKbKr0yyrKK15933511%26no_mhs%3D%22&format=json';
$.getJSON(url,
function(data) {
var id = data.query.results.body.table.tr.td.table.tr[2].td.table.tr;
for (var i = 1; i <= id.length; i++) {
$("<tr> <td> <input name='fmatakuliah' value='"+id[i].td[1].a.content+"'> </td> <td> <input name='fdata' value='" + id[i].td[1].a['href'] + "'> </td> </tr>").appendTo("#matkul tbody");
};
});
});
});
</script>
from the above code output will be
Matakuliah Data Lain
StringOne OtherData
StringTwo OtherData
below is the ajax post code, but when it is already sending the data, the alert does not show all the data
<script type="text/javascript">
$(document).ready(function(){
$("#post").click(function(){
string = $("form").serialize();
alert(string); // this alert is normal, show all data
$.ajax({
type: "GET",
url: "/save.php",
data: string,
success: function(data){
alert("Success!"+data); //this not normal, not show all data
}
});
});
});
</script>
below is the code on save.php
print_r($_GET);
The latest response is showing like this
Array
(
[fmatakuliah] => Wide Area Network
[fdata] => matakuliahdetail.asp?session_id=xxbKiKJawuyrbaaiJ3Kabybabi3JJiKJrJyb3wiuKbbry0JbKiKbKr0yyrKK15933511&mk=52323605&kur=2010
)
My question is how to show all data and save it to the database?
It looks like you need to change the AJAX type from GET to POST:
$.ajax({
type: "POST",
url: "/save.php",
data: string,
success: function(data){
alert("Success!"+data); //this not normal, not show all data
}
});

Send input value to php using ajax with result printed to div

I'm trying to send an input value to a php script and have the returned value posted to a div, using ajax, but I can't seem to get this right. Any help/suggestions would be appreciated. Thanks!!
This is what I have by now, but console says: "Failed to load resource: the server responded with a status of 404 (Not Found)".
test1.php:
<script>
$.ajax({
type: 'POST',
url: 'test2.php',
data: {url: $('#id1').val()},
success: function (data)
{
$(document).ready(function(){$("#content").load("test2.php");});
}
});
</script>
<form name="input">
<input type="text" id="id1">
<input type="submit">
</form>
<div id="content"></div>
test2.php:
<?php
$string=$_POST['id1'];
require_once('connect.php');
$inf = "SELECT * FROM `comments` WHERE date='$string'";
$info = mysql_query($inf);
while($info2 = mysql_fetch_object($info)) {echo $info2->username.$info2->date;}
?>
<script>
$(document).ready(function() {
$('#submit').click(function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: 'test2.php',
data: {id1: $('#id1').val()},
success: function(data)
{
$("#content").html(data);
}
});
});
});
</script>
<form name="input">
<input type="text" id="id1">
<input type="submit" id="submit">
</form>
<div id="content"></div>
When you submit the ajax request, you're already submitting your content to test2.php, so you don't need to load it again. In the success function, you can append the result to the div from the callback.
$(document).on('click','#submit',function(e) {
e.preventDefault();
$.post('test2.php',{url: $('#id1').val()},function(data){
$("#content").html(data);
}
});
});
404 (Not Found) Error is for page not found. Please make sure that file test2.php is exist in same folder. Check url.
Also you can copy the URL from console and paste it in the browser URL to check the url correct or incorrect.
jQuery
<script>
$(document).ready(function() {
$('#submit').click(function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: 'test2.php',
data: {id1: $('#id1').val()},
success: function(data)
{
$("#content").html(data);
}
});
});
});
</script>
HTML
<form name="input">
<input type="text" id="id1">
<input type="submit" id="submit">
</form>
You could try this:
<script>
$('#submitBtn').on('click',function(){
$.ajax({
type: 'POST',
url: 'test2.php',
data: {url: $('#id1').val()},
success: function (data)
{
$("#content").html(data);
}
});
return false;
});
</script>
<form name="input">
<input type="text" id="id1">
<input id="submitBtn" type="submit">
</form>
<div id="content"></div>

jquery post form

I have this code for send simple data using jquery , but no works , all time reload de page and no load contents i send by post
My code it´s this :
<script>
$(document).ready(function() {
$("#form_order").submit( function () {
$.ajax({
type: "POST",
data : $(this).serialize(),
cache: false,
url: "indexer_adm.php?send_order2=ok",
success: function(data){
$("#load_order").html(data);
}
});
return false;
});
</script>
<form name="forma" id="form_order" method="post" action="">
<table width="100%" border="1">
<tr>
<td height="30" align="center" valign="middle">
<select name="select_order">
<option value="articles">Articles</option>
<option value="blogs">Blogs</option>
<option value="products">Products</option>
</select>
<input type="submit" name="Submit" value="Acceder">
<input type="hidden" name="send_order2" value="ok">
<input type="hidden" name="action_load" value="<?php echo $_REQUEST['action_load'];?>">
</td>
</tr>
<tr>
<td height="30" align="center" valign="middle"> </td>
</tr>
</table>
</form>
<div id="load_order"></div>
In the div called load_order , it must load the result of this send by post from the form , but the page reload and no works , i see the code many times but i don´t understand what happen
Thank´s for All
There is a syntax error in your code, you haven't closed the submit handler.
$(document).ready(function() {
$("#form_order").submit( function () {
$.ajax({
type: "POST",
data : $(this).serialize(),
cache: false,
url: "indexer_adm.php?send_order2=ok",
success: function(data){
$("#load_order").html(data);
}
});
return false;
}); // <---
});
Try returning false inside of the submit block, rather than of the ready block.
You may have a syntax error since return false should stop the form from refreshing. I would use the post function instead:
<script>
$(function() {
$("#form_order").submit( function () {
$.post('indexer_adm.php?send_order2=ok', $(this).serialize(), function(data) {
$("#load_order").html(data);
});
return false;
});
</script>
Ok !!! , Thank´s everybody
The Right code :
<script>
$(document).ready(function() {
/*
$("#load_order").show(1000);
$("#load_order").load("<?php print "".$ruta_path_adm."".$ruta_modulos."/mod_order/indexer_adm.php?send_order2=ok";?>");
*/
$("#form_order").submit( function () {
$.ajax({
type: "POST",
data : $(this).serialize(),
cache: false,
url: "<?php print "".$ruta_path_adm."".$ruta_modulos."/mod_order/indexer_adm.php?send_order2=ok";?>",
success: function(data){
$("#load_order").html(data);
}
});
return false;
});
});
</script>
Thank´s for the help i put bad the script and no see this , thank´s

Categories