Reload data continuously with Ajax - php

I have a page with some bootstrap cards. Information showing inside the card is retrieved from MySQL database.
What I need
I need these cards to be updated every 3 seconds without reloading the page. I know that Ajax is the way to do this (Update content without refreshing page). I am not familiar with Ajax. However, I tried as below
<script>
setInterval(
(function x() {
$.ajax({
type: "POST",
url: "vTagInfoCall.php",
processData: false,
contentType: false,
data: "",
success: function(result) {
$("#inputFieldDisplay").html(result);
}
});
return x;
})(), 3000);
</script>
Also I gave the following div with id inputFieldDisplay as below
<div class="container-fluid">
<div id="inputFieldDisplay"></div>
</div>
My Issue
When I redirect to the mentioned page vTagInfoCall.php with all my php codes and contents, it is not loading anything to the div with id inputFieldDisplay. Did anyone know what am I doing wrong here?
Edit 1
Following is my vTagInfoCall.php file contents
<?php ob_start();?>
<?php include "db.php"; ?>
<?php
$tagQuery = "SELECT * FROM vtagdetails WHERE status = 0";
$tagQueryExecute = mysqli_query($conn, $tagQuery);
$openItems = mysqli_num_rows($tagQueryExecute);
while($tagQueryRows = mysqli_fetch_array($tagQueryExecute)){
$srNumber = $tagQueryRows['srNumber'];
$Name = $tagQueryRows['Name'];
$Code = $tagQueryRows['Code'];
$customerName = $tagQueryRows['customers'];
$Type = $tagQueryRows['Type'];
session_start();
echo '<form method="post"> <div class="card cardBodyStyle">
<div class="card-body" >
<div class="row">
<input type="text" name= "srNum" value = "'.$srNumber.'" hidden>
<input type="text" name= "tpCode" value = "'.$Code.'" hidden>
<div class="col-sm"><i class="fab fa-500px"></i> '.$Name.'</div>
<div class="col-sm"><i class="fas fa-atom"></i> '.$Type.'</div>
<div class="col-sm"><i class="fas fa-globe fa-spin"></i> '.$customerName.'</div>
</div>
</div></div></form><br>';
}
?>
Edit 2
It is showing the following error in console. Can someone help why is the error?

I found two issues in code:
First in your script, please use below code:
<script>
setInterval(x, 3000);
function x() {
$.ajax({
type: "POST",
url: "vTagInfoCall.php",
processData: false,
contentType: false,
data: "",
success: function(result) {
$("#inputFieldDisplay").html(result);
}
})
}
</script>
Second one is remove # from your id of div because # is just use to indicate id of element in jquery and .(dot) for class name of element. Please update your code with below code:
<div class="container-fluid">
<div id="inputFieldDisplay"></div>
</div>

You can use directly in setInterval function
setInterval(function()
{
$.ajax({
type: "POST",
url: "vTagInfoCall.php",
processData: false,
contentType: false,
data: "",
success: function(result) {
$("#inputFieldDisplay").html(result);
}
});
}, 3000);//time in milliseconds
And the problem is in Html div also as showed by madhuri and haisen.
Whenever you used attributes(name,id,class whatever) you dont need to put dot,# or other symbols in the div or input.
So please fix it. I think it will work definitely.
<div id="#inputFieldDisplay"></div> // Wrong because of #
<div id="inputFieldDisplay"></div> //Right

you html code with some incorrect in id="#inputFieldDisplay"
<div class="container-fluid">
<div id="inputFieldDisplay"></div>
</div>

After many trials and methods, found out that I was using CDN of slim version of jQuery which caused this problem. Somehow there is some issue with Ajax in the slim version
I solved it by using the uncompressed version of jQuery CDN from here and that is it!!

Related

How yo post to a database without a form php mysql html

I want to post the fields price and plateId to a database table without using any form, when the user clicks the Order button. Would it be possible? Otherwise, could you suggest an other solution?
<div class="menu">
<img src="/images/wings.png" />
<div>
<span id="price">Price:$40.00</span>
<div class="description">
<span id="plateId">HOT WINGS</span>
</div>
</div>
<button id="btn">Order</button>
</div>
<div class="menu">
<img src="/images/chicken.png" />
<div>
<span id="price">Price:$70.00</span>
<div class="description">
<span>Cooked Chicken</span>
</div>
</div>
<button id="btn">Order</button>
</div>
You need to call AJAX first and in your case you should collect information about plateId and price and return the data to AJAX so it can store in your database.
$('#btn').click(function () {
var orderInformation = {
var price = $(#price).text();
var plateId = $(#plateId).text();
};
$.ajax({
type: 'POST',
url: 'post-information-in-your-db.php',
dataType: "json",
data:(orderInformation),
success: function (data) {
alert(data);
}
});
});
It is also possible to treat the data returned from the variable and different display shapes after success.
you can make a server call through ajax by calling a javascript function as:
function send_value() {
$.ajax({
type: 'POST',
url: 'get.php',
dataType: "json",
data:({"uniId":"test"}),
success: function (data) {
console.log(data);
}
});
return false;
}
Pass data as an argument and put them as json in data:({"uniId":"test"})

How to reset div data which I am appending on click?

Here I want to reset the appended data on click. So I can get the fresh data by removing the old data. Now actually data is coming, but the new data is getting appended with the old data which I need to remove.
$("#button").click(function(){
etc=$("#etc").val();
$.ajax({
url: 'db4.php',
type: 'POST',
data: {
etc: etc
},
error: function() {
$('#div1').html('<p>An error has occurred</p>');
},
success: function(data) {
var result = $.parseJSON((data));
$.each(result,function(i,field){
document.getElementById("div1").innerHTML=field.name;
$('body').append(document.getElementById("subasish123").innerHTML);
$('#subasish123').slice(0).hide();
});
}
});
});
<form>
<input id="etc" type="text" name="etc">
<label id="button">Click</label>
</form>
<div id="subasish123">
<div id="div1"></div>
</div>
Try redirecting your output to some other element instead of body.
Emptying the body of your HTML wouldn't be desirable.
Look at this fiddle for example:
jsfiddle.net

use parts of ajax results after form submit

I have a simple upload form that sends the request via ajax post. The result (data) is shown in a bootstrap modal - works like intended.
Parts of the upload.php are reading exif data from the uploaded image and I'd like to use these information on my start form (updating placeholders with exif info).
$(document).on('submit', '#uploadForm', function(e) {
e.preventDefault();
$.ajax({
url: './includes/upload.php',
type: 'POST',
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
success: function(data){
$('#modal .modal-body').html(data);
$('#modal').modal('show');
}
});
});
html result:
<img src="<?php echo $imgpPath; ?>" />
<div class='fp_upload'>
<div class="alert alert-success">
<?php
echo '<p class="body">'.$img_body.'</p>';
echo '<p class="lens">'.$img_lens.'</p>';
echo '<p class="iso">'.$img_iso.'</p>';
echo '<p class="aperture">'.$img_aperture.'</p>';
echo '<p class="exposure">'.$img_exposure.'</p>';
?>
</div>
</div>
What would be a good way to get the desired infos somewhere in data?
Greeings Fabio
I know, with JSON it would get easier, but I found a way to find specific values in my data and place them in inputs.
My submit code is untouched, inside the success I added.
var img_name = $(data).find('#img_name').attr('data-placeholder');
$('#input_name').val(img_name);
Greetings Fabio

Jquery Post Not Processing file

I am stil having issues with my code the file is not being processed when permalinks are set to anything other than default.
<div id="thanks" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">Redeem Points</h4>
</div>
<div class="modal-body">
<form class="form-horizontal" class="contact" name="commentform" >
<div class="form-group">
<h3>You may only redeem the maxium points of : <?php echo $maxpoints;?></h3>
<input type="hidden" name="playerid" value="<?php echo $playerId;;?>" />
<input type="number" valuemax="<?php echo $maxpoints;?>" name="points" class="form-control" placeholder="How many points do you wish to redeem." />
<label class="control-label col-md-4" for="Comments">Comments?</label>
<input type="text" name="comments" />
</div>
<div class="form-group">
<div class="col-md-6">
<button class="btn btn-success" id="submit">submit</button>
Close
</div>
</div>
</form>
</div><!-- End of Modal body -->
</div><!-- End of Modal content -->
</div><!-- End of Modal dialog -->
</div><!-- End of Modal -->
I thought the inital issue was the but when i turn permalinks off it appears to work ok I really dont no what the issue is here thanks. The html above is in the file /wp-content/themes/gogreensoccer5/kids-dashbaord.php as well as the jquery below i am at a loss.
type: "POST",
url: "/bin/sendredeempoints.php",
<script>
$('#thanks').modal('show').on('shown.bs.modal', function () {
//Ajax Method Call starts here
var points = $("#points").val();
$("#send_btn").click(function () {
var dataString = 'points=' + points;
alert(dataString);//Remove this
return false;//Remove this
$.ajax({
type: "POST",
url: "/bin/sendredeempoints.php",
data: $('form.contact').serialize(),
success: function (msg) {
$("#thanks").html(msg)
$("#form-content").modal('hide');
},
error: function () {
alert("failure");
}
});
//Ajax Method Ends
}); //Click Function ends
}); //Modal event Ends
</script>
Stop with the downvoting whoever it is.
Edit
Got A bit further
added this to my functions but its still saying file not found :-(
function load_these_scripts() {
wp_register_script( 'your_script', get_bloginfo('template_directory').'js/redeempoints.js', false, false, true );
wp_localize_script( 'my_ajax_script', 'myAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' )));
}
add_action("wp_ajax_php_function_name", "redeempoints");
add_action("wp_ajax_nopriv_php_function_name", "redeempoints");
function redeempoints() {
// Some stuff here
global $wpdb;
// $result = $wpdb->get_results( /* SQL code goes here */ );
// Do something with $result
}
You may only redeem the maxium points of :
" />
" name="points" class="form-control" placeholder="How many points do you wish to redeem." />
Comments?
</div>
<div class="form-group">
<div class="col-md-6">
<button class="btn btn-success" id="submit">submit</button>
Close
</div>
</div>
</form>
my js file
var formdata = $('form.contact').serialize();
var allData = {
action: 'redeempoints',
data: formdata
}
jQuery.ajax({
type : "post",
dataType : "json",
url : myAjax.ajaxurl,
data : allData,
success: function(response) {
if(response.type == "success") {
// Do something
}
else {
// Do something else
}
}
});
You need to change the way you use AJAX alongside WordPress :)
First up, in your functions.php (or plugin file), you'll have to localize admin-ajax.php and register a JS file where you'll make the AJAX calls - looks like this:
add_action( 'wp_enqueue_scripts', 'load_these_scripts' );
function load_these_scripts() {
wp_register_script( 'your_script', 'URI_OF_JS_THAT_MAKES_THE_AJAX_CALLS/scripts.js', false, false, true );
wp_localize_script( 'my_ajax_script', 'myAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' )));
}
Then in your scripts.js you need to make the AJAX calls like this:
Use this instead of the "data :"
$("#send_btn").click(function () {
var formdata = $('form.contact').serialize();
var allData = {
action: 'php_function_name',
data: formdata
}
jQuery.ajax({
type : "post",
dataType : "json",
url : myAjax.ajaxurl,
data : allData,
success: function(response) {
if(response.type == "success") {
// Do something
}
else {
// Do something else
}
}
});
});
The action: "php_function_name" actually tells WP which function to call but you also need register that well. Do it like this, back in your functions.php (or plugin file):
add_action("wp_ajax_php_function_name", "php_function_name");
add_action("wp_ajax_nopriv_php_function_name", "php_function_name");
function php_function_name() {
// Some stuff here
global $wpdb;
$result = $wpdb->get_results( /* SQL code goes here */ );
// Do something with $result
}
Make sure you register the function with both "wp_ajax" & "wp_ajax_norpiv" otherwise it will only work for logged in users.
Cheers
First. This is an ajax post. Using jquery post its a bit different http://api.jquery.com/jquery.post/
Your question is about posting in jquery, not ajax. So lets modify your code a little:
<script>
$('#thanks').modal('show').on('shown.bs.modal', function () {
var points = $("#points").val();
$("#send_btn").click(function () {
var dataString = 'points=' + points;
alert(dataString);//Remove this
return false;//Remove this
var url = "/bin/sendredeempoints.php";
var data = $('form.contact').serialize(),
$.post( url, { data: data })
.done(function() {
$("#thanks").html(msg)
$("#form-content").modal('hide');
}).fail({
alert("failure");
});
});//Click Function ends
}); //Modal event Ends
</script>
Posting with ajax is a pain in the ass. Since there is Jquery .post() its very easy. Modify if it's not correct. Let me know if it helped.
I see you use alert(). Use console.log() instead. No annoying popups. you can see the data in developer tools console.
EDIT2
The error you get, means your url isn't correct. You are trying to post to a file instead to an url.
I suppose you have an index file or a file that includes other files.
Enter some php code to the file that includes this script.
The php script checks in the url for data and if its true.
<?php
if(isset($_POST['data']) AND $_GET['data'] == 'true'){
//Go to your php file. or include it.
//EXAMPLE
include "/bin/sendredeempoints.php";
//On the sendredeempoints you can do whatever you want with the post.
}
?>
Change your var url to this:
var url = "YOURWEBSITE.com?data=true"; // or the easy one
var url = window.location.href + "?data=true";

Updating selection menu after fresh input into database (JSON)

I'm working on a new website, and i want to learn more about JSON
The website is using jQuery and PHP
I have a jQuery window that gets opend to add a new menu item or submenu item. In this window is also standing a select menu with the added menu and submenu items.
If i have added a new item than it will be added by an ajax request into the database, ofcourse i want to try to avoid window refreshing to see the new added items in the select menu.
The next code is triggering my window and sends the form to a PHP script.
`
var SITE_URL = "http://martin.eenwittekerst.nl/";
$$.ready(function() {
$( "#dialog_add_menu" ).dialog({
autoOpen: false,
modal: true,
width: 900,
open: function(){ $(this).parent().css('overflow', 'visible');
$$.utils.forms.resize() }
}).find('button.submit').click(function(){
var $el = $(this).parents('.ui-dialog-content');
if ($el.validate().form()) {
var filename = SITE_URL+"/admin/requests/menu.php";
$.ajax
({
type: "POST",
url: filename,
data: "do=add&"+$('form#menu').serialize()+"",
success: function(msg)
{
document.getElementById("return_message").innerHTML = msg;
}
});
var filename2 = SITE_URL+"/admin/reloads/menuItems.php";
$.ajax({
type: "GET",
url: filename2,
async: false,
beforeSend: function(x) {
if(x && x.overrideMimeType) {
x.overrideMimeType("application/j-son;charset=UTF-8");
}
},
dataType: "json",
success: function(data){
//do your stuff with the JSON data
alert(data);
}
});
$el.find('form')[0].reset();
$el.dialog('close');
}
}).end().find('button.cancel').click(function(){
var $el = $(this).parents('.ui-dialog-content');
$el.find('form')[0].reset();
$el.dialog('close');;
});
$( ".open-add-menu-dialog" ).click(function() {
$( "#dialog_add_menu" ).dialog( "open" );
return false;
});
});
`
This is included a part where i'm testing with JSON, i will put that piece of code here again where i'm trying to do the JSON thing
`
var filename2 = SITE_URL+"/admin/reloads/menuItems.php";
$.ajax({
type: "GET",
url: filename2,
async: false,
beforeSend: function(x) {
if(x && x.overrideMimeType) {
x.overrideMimeType("application/j-son;charset=UTF-8");
}
},
dataType: "json",
success: function(data){
//do your stuff with the JSON data
alert(data);
}
});
`
At the end i have an alert that's not giving anny respons, not even an empty alert
Sorry for beeing a noob in this, but this is my first time i'm doing this. I have tested a lot what's standing on the internet without success.
The code in my PHP code is verry simple and only for testing ofcourse
`
include(BASE_DOC."config.php");
include(BASE_DOC."classes/cls.db.php");
// Open the database connection
$cOpenDB = new database_connection;
echo $cOpenDB->db_open(DB_HOST, DB_USER, DB_PASS, DB_TABLE);
$rows= array();
$sql = mysql_query("SELECT * FROM menu_items") or die(mysql_error());
while($data = mysql_fetch_array($sql))
{
$rows[] = $data['id'].",".$data['menu_item_name'];
}
echo json_encode($rows);
?>
`
Now i dont understand how to get the JSON array from my PHP script and how to rebuild the HTML of my select menu
Here i have the code of my HTML of the windowedbox to add a new sub- menu item
`
<!-- Add New Menu Item -->
<div style="display: none;" id="dialog_add_menu" title="Voeg een nieuw menu item toe">
<fieldset id="menu">
<form action="" class="full validate" id="menu">
<div class="row">
<label for="d2_menu_item">
<strong>Menu item naam</strong>
</label>
<div>
<input class="required" type="text" name="menu_name" id="menu_name" />
</div>
</div>
<div class="row">
<label for="d2_menu_item_alt">
<strong>Menu item alt</strong>
</label>
<div>
<input class="required" type="text" name="menu_alt" id="menu_alt" />
</div>
</div>
<div class="row">
<label for="d2_menu_item_sub">
<strong>Wordt dit een submenu item?</strong>
</label>
<div>
<select name="sub_option" id="sub_option">
<option value="n">Nee</option>
<option value="y">Ja</option>
</select>
</div>
</div>
<div class="row" id="showMenuItems">
<label for="d2_select_menu_item">
<strong>Selecteer een Menu item om een submenu item aan te koppelen</strong>
</label>
<div>
<div id="sub_menu_item_of">
<select name="sub_of" id="sub_of">
<option>Kies een menu item om een sub menu item aan te koppelen</option>
<?PHP
$cMenuItems = new menu();
echo $cMenuItems->menuItemsSelect("'menu_item_name','menu_item_alt'", "menu_items");
?>
</select>
</div>
</div>
</div>
</form>
<div class="actions">
<div class="left">
<button class="grey cancel">Annuleren</button>
</div>
<div class="right">
<button class="submit">Voeg menu item toe</button>
</div>
</div>
</fieldset>
</div>
<!-- End if #dialog_add_menu -->
`
For the first time is this a real pain in the ass to do, but if someone can help me with this than i'm forever greatfull to you all!
If you have anny questions or need more information let me know!
Sorry for sometimes my poor english
Kind regards
Martin Meijer
When debugging ajax, you have to make sure
- the ajax request did sent (check you firebug network console)
- the php did return a reponse : log before the return "json_encode($rows);"
- the ajax did got a correct reponse : add a error block in your ajax call :
$.ajax({
...
error: function(response) {
alert(JSON.stringify(response));
}
});
Also check you php.log file.

Categories