This is how I pass the array into the function
$rate=$data["rate"];//this is an array like rate[10,20,30,60,70]
$car->rate = $rate;
$car->rentalRate();
In the function , it accepts the array and insert into the table
public function rentalRate()
{
$rate = implode("','",$this->rate);
$sql = "INSERT INTO rental(day_1,day_3,day_7,day_15,day_30)VALUES('$rate')";
$stmt =connection::$pdo->prepare($sql);
$stmt->execute();
unset($rate);
}
Problem is,second time onwards it repeats the records. I mean for the first time when I insert only one row is inserted. The second time I insert, the same new record inserted twice. Third time I insert, thrice inserted..same goes for the number of times I insert. If I refresh than I don't have this issue.
WHat could be tracking the number of time I insert the data, could it be the array? or ajax?
This is how I submit the form via ajax
$("#submit").on("click",function()
{
$("#add_car_form").submit(function(){
var data = {
"action": "test"
};
data = $(this).serialize() + "&" + $.param(data);
$.ajax({
type: "POST",
dataType: "json",
url: "add_car_submit.php", //Relative or absolute path to response.php file
data: data,
success: function(data) {
$(".the-return").html("<br />JSON: " + data["json"] );
}
});
return false;
});
});
hard to say without seeing your full code but here is waht you can do:
Fist, use the dev tools on your browser and see how many requests you are submitting on every click. If they grow with every click it's your JS fault. If not then try to var_dump your POST data at the point of entry in your php scritpt. If the data is not repeated, there is a problem with your php part. (My bet would be with JS, as on AJAX request you create a new instance of php process so it can not track your submissions).
Related
$connect_web = simplexml_load_file('http://www.currency.com/currencies/today.xml');
$usd_buying = $connect_web->Currency[0]->BanknoteBuying;
$usd_selling = $connect_web->Currency[0]->BanknoteSelling;
currency.php
i get the currency from outsource by xml.
and use this on my main page,
<?php
require_once('currency.php');
global $usd_buying ;
global $usd_selling ;
?>
On my main page there is a search box which is triggered key up with every key pressed.
I get data from database and use the currency for every time key pressed.
So every time key pressed , page get the xml data from out source .
I want to get xml data once in a 5 min. not every time key triggered.
Is there any solution for this , like session?or anything else.
function view_record()
{
$("#search").keyup(function()
{
var searchword = $(this).val();
$.ajax(
{
url: 'viewdata.php',
method: 'post',
data:{searchword:searchword},
dataType: 'JSON',
success: function(data)
{
if(data.status=='success')
{ $('#table').html(data.html);
}
You can use javascript setInterval function. ( Detail of this function : https://www.w3schools.com/jsref/met_win_setinterval.asp )
Sample js for your code ;
function getCurrency(){ //ajax request your currency.php and get data //print data in target div via js }
setInterval(getCurrency,300000); //300000 = 5 min (60*5*1000 microseconds) , every 5 minute working getCurrency function
I am posting data to a PHP page using the $.ajax in Jquery. So far all this is working fine.
Here is how all this looks in my index.html.
function send() {
$( "#send" ).show( "slow" );
var page = Page;
var title = $("#title").text();
var title_2 = $("#title_2").val();
$.ajax({
url: "save.php",
method: "POST",
data: { MyPage : page, My_Title1 : title, My_Title2 : title_2 },
dataType: 'json',
success: function(data) {
alert(data);
var result = jQuery.parseJSON(data);
alert(result.last_id);
},
error: function(output) {
alert("not working whole process");
}
});
This to sum up what I am doing, is sending some data, Html and contents in div's, to a sql database.
What I would like to do now is that once this data is posted to the save.php file, I get a response from the php sending me the ID of the page I have saved all this in. So I am using mysqli_insert_id($con); to acheive this.
Set it it looks like this.
$last_id = mysqli_insert_id($con);
When I execute all this, the Post works fine and I end up with what I want.
{"last id":265} at the end of my post.
$data['last id'] = $last_id;
echo json_encode($data);
How do I get this value back to my index.html so that I can place it inside a input. The success is not working out.
//Reply to Steves answer
# Steve. Thank you for answering. Your answer is exactly what is happening. I am sending a whole bunch of html to my save.php file so it can save it to a sql table.
Something looking like this.
Write to MySQL OK!<br>INSERT INTO Project(ID_User,Name_Project,Page_Project,Date_Project) VALUES ( 110, '\"Project name here\"', '<div class=\"file_save_container\"> <------------- HERE THERE IS A WHOLE BUNCH OF HTML ------------> </div>\n\n\n', '2015-03-19 13:10:23');<br>
This is all saving properly to my sql table. What I would like to achieve here is that when the ajax is sent to my save.php I get a response sending me the id of the newly created Project so that I can then place the response "the id" inside a . Right now mysqli_insert_id is placing this at the end of my post.
<br>{"this_id":"311"}
This is what I would like to get back as a response to my index.html file and not have it at the end of my post.
Try to set header('Content-Type: application/json'); in save.php
Write $data['last_id'] instead of $data['last id'] to match your JS.
Background Info
I'm fiddling around with some PHP and AJAX at the moment, to try and get the code working for an auto refreshing div (every 10 seconds), that contains comments.
Here is javascript code I am using to refresh the div..
<script type="text/javascript">// <![CDATA[
$(document).ready(function() {
$.ajaxSetup({ cache: false });
setInterval(function() {
$('#content_main').load('/feed_main.php');
}, 5000);
});
// ]]></script>
The code that will populate the div called "content_main", which is in feed_main.php, essentially accesses the database and echo's out the latest comments ...
Question
Is it possible, to only load the div "content_main" if the data inside of it, hasn't changed since the last time it was loaded?
My logic
Because I'm relatively new to javascript and AJAX I don't quite know how to do this, but my logic is:
For the first time it is run..
load data from feed_main.php file
Create a unique value (perhaps a hash value? ) to identify say 3 unique comments
Every other time it is run...
load the data from feed_main.php file
create a NEW unique value
check this value with the previous one
if they're the same, don't refresh the div, just leave things as they are, but if they're different then refresh..
The reason why I want to do this is because the comments usually have pictures attached, and it is quite annoying to see the image reload every time.
Any help with this would be greatly appreciated.
I've faced similar problem not too long ago, i assume that you using mysql or something for your comments storage serverside ?
I solved my problem by first adding timestamp integer column to my mysql table, then when i added a new row, i'd just simply use time() to save the current time.
mysql row insert example:
$query = "INSERT INTO comments (name, text, timestamp) VALUES ('". $name ."', '". $text ."',". time() .");";
step two would be to json_encode the data you sending from serverside:
$output = array();
if ($html && $html !== '') { // do we have any script output ?
$output['payload'] = $html; // your current script output would go in this variable
}
$output['time'] = time(); // so we know when did we last check for payload update
$json = json_encode($output, ((int)JSON_NUMERIC_CHECK)); // jsonify the array
echo $json; // send it to the client
So, now instead of pure html, your serverside script returns something like this:
{
"payload":"<div class=\"name\">Derpin<\/div><div class=\"msg\">Foo Bar!<\/div>",
"time":1354167493
}
You can grab the data in javascript simply enough:
<script type="text/javascript"> // <![CDATA[
var lastcheck;
var content_main = $('#content_main');
pollTimer = setInterval(function() {
updateJson();
}, 10000);
function updateJson() {
var request = '/feed_main.php?timestamp='+ (lastcheck ? lastcheck : 0);
$.ajax({
url: request,
dataType: 'json',
async: false,
cache: false,
success: function(result) {
if (result.payload) { // new data
lastcheck = result.time; // update stored timestamp
content_main.html(result.payload + content_main.html()); // update html element
} else { // no new data, update only timestamp
lastcheck = result.time;
}
}
});
}
// ]]> </script>
that pretty much takes care of communication between server and client, now you just query your database something like this:
$timestamp = 0;
$where = '';
if (isset($_GET['timestamp'])) {
$timestamp = your_arg_sanitizer($_GET['timestamp']);
}
if ($timestamp) {
$where = ' WHERE timestamp >= '.$timestamp;
}
$query = 'SELECT * FROM comments'. $where .' ORDER BY timestamp DESC;';
The timestamps get passed back and forth, client always sending the timestamp returned by the server in previous query.
Your server only sends comments that were submitted since you checked last time, and you can prepend them to the end of the html like i did. (warning: i have not added any kind of sanity control to that, your comments could get extremely long)
Since you poll for new data every 10 seconds you might want to consider sending pure data across the ajax call to save substantial chunk bandwidth (json string with just timestamp in it, is only around 20 bytes).
You can then use javascript to generate the html, it also has the advantage of offloading lot of the work from your server to the client :). You will also get much finer control over how many comments you want to display at once.
I've made some fairly large assumptions, you will have to modify the code to suit your needs. If you use my code, and your cat|computer|house happens to explode, you get to keep all the pieces :)
How about this:
<script type="text/javascript">
// <![CDATA[
$(function () {
function reload (elem, interval) {
var $elem = $(elem);
// grab the original html
var $original = $elem.html();
$.ajax({
cache : false,
url : '/feed_main.php',
type : 'get',
success : function (data) {
// compare the result to the original
if ($original == data) {
// just start the timer if the data is the same
setTimeout(function () {
reload(elem, interval)
}, interval);
return;
}
// or update the html with new data
$elem.html(data);
// and start the timer
setTimeout(function () {
reload(elem, interval)
}, interval);
}
});
}
// call it the first time
reload('#content_main', 10000);
});
// ]]>
</script>
This is just an idea to get you going it doesn't deal with errors or timeouts.
Best And Easy Code
setInterval(function()
{
$.ajax({
type:"post",
url:"uourpage.php",
datatype:"html",
success:function(data)
{
$("#div").html(data);
}
});
}, 5000);//time in milliseconds
I have a page with some checkboxes and a submit button. I use AJAX to post the checkbox values to a PHP script, calc.php, run some calculations with the data and assign the result to a PHP session variable. I have another PHP script, json.php, that takes that session data and encodes it as JSON for the jquery to display in the div. My problem is I allow the user to set the amount of data sets they are going to submit, subnumber, and my display loop gets out of sync when the user changes the number of sets.
For example, if they start with 3 data sets, they submit them one by one by pressing #button. After the last set, if (count == max) runs and. Now they can do another calculation and change the number of data sets if they wish. If they change it to say 2, output goes to four instead of reseting to 1 and emptying #log.
$("#button").click(function() {
$.ajax({
type: "POST",
url: "calc.php",
data: $("form#checkboxes").serialize(),
success: function(data) {
if(document.getElementById('calc').checked) {
var max = checkboxes.subnumber.value;
var stop = Number(max) + 1;
count++;
output++;
$.getJSON('json.php', function(data) {
$.each(data, function(key, val) {
$('#log').append(output);
$('#log').append(val.result);
$('#log').append("</br>");
})
})
if (count == max){
count = 0;
$("#results").load('results.php')
}
if(output == stop) {
$("#log").empty();
output = 1;
}
}
}
})
}
I know it's something simple, but I have been trying to fix it for two hours now and can't figure out the problem. Everything else works perfectly, it's just the output counter that isn't done correctly.
You're running asynchronous calls into your JSON. If users are doing things so quickly that the calls are coming back out of order, the issue lies in there.
You've got two options:
Run all of your JSON synchronously (use async:false in your JSON calls)
Utilize a counter and only process events that are coming back on the current index.
Psuedo Code for #2:
var pCounter = 0;
function doSomeAjax()
{
pCounter++;
$.ajax('url',{
data:{count:pCounter}
success:function(data)
{
// your json should return the current counter index
if (data.counter != pCounter) return;
// execute normally.
}
});
}
I've got several div id's, each containing a different client. I want to be able to click the delete button and using ajax and jquery delete the specific div from the database. I'm getting success in AJAX but it's not deleting anything from the DB. And then obviously, upon deletion, I would like the container to reload dynamically. help!!!
function DeleteClient(){
clientID = $('.clientblock').attr('id')
alert(clientID);
var yes = confirm("Whoa there chief! Do you really want to DELETE this client?");
if (yes == 1) {
dataToLoad = 'clientID=' + clientID + '&deleteclient=yes',
$.ajax({
type: 'post',
url: '/clients/controller.php',
datatype: 'html',
data: dataToLoad,
success: function(html) {
alert('Client' + clientID + ' should have been deleted from the database.');
$('#clientscontainer').html(html);
},
error: function() {
alert('error');
}});};
};
controller.php info //
Variables necessary are:
$deleteClient
$clientID
on the delete click, when being passed through post (via firebug)
clientID = 0
deleteClient = yes
edit: so obviously, it's not getting the correct client ID to delete it to the DB as it is passing through post but I am getting an ajax success call and where i have the client ID variable displaying there, it is picking the correct client ID.
alert(clientID) is pulling in 0 as well.
Any ideas?
dataToLoad = 'clientID=' + clientID + '&deleteclient=yes',
Your controller is getting clientID value of 0.
Track down your clientID javascript variable and see if it is fetching the correct clientID.