I am trying to validate list of dynamic text fields.
Validation needs an AJAX call to interact with server.
At the backend I have written just one php file that reads the input request data and performs operation. Below is the example.
abc.js
row_count = 6
for (i = 1; i <=row_count; i++) {
id = "#val"+i.toString() ;
$(id).change(function(){
input_val="random";
$.ajax({
url:"url.php",
type:post,
async:true,
dataType: 'json',
data : {temp:input_val},
success:function(result){},
error: function (request, status, error) {}
});
});
}
url.php
<?php
$random_val = $_POST['temp'];
$cmd = 'systemcommand '.$random_val;
$flag = exec($cmd);
if ($flag == 0){
echo json_encode(array("status"=>'Fail'));
}
else{
echo json_encode(array("status"=>'Success'));
}
?>
It works fine when the row_count = 1 (Just one text field) but fails when the input is more than 1.
When the count is more than 1, the php script is not able to read the request data(The key in JSON data "temp"). it is blank in that case.
Any lead or help should be appreciated.
Thanks
Your javascript bit needs some adjusting, because you do not need to define an ajax for every single element. Use events based on a class. Also, since input behave differently than select, you should setup two different event class handlers.
function validateAjax ( element ) {
var input_val = element.val();// get the value of the element firing this off
$.ajax({
url: "url.php",
type: 'post',
async: true,
dataType: 'json',
data : { temp: input_val },
success: function(result) {
// check your result.status here
},
error: function (request, status, error) { }
});
}
$(".validate_change").on("change",function() { // for selects
validateAjax( $(this) );
});
$(".validate_input").on("input",function() { // for text inputs
validateAjax( $(this) );
});
And for your select or input you add that appropriate class.
<select class="validate_change" name="whatever"><options/></select>
<input class="validate_input" name="blah">
PS
I really worry about this code you have:
$cmd = 'systemcommand '.$random_val;
$flag = exec($cmd);
So, you are just executing anything that is coming in from a webpage POST var??? Please say this website will be under trusted high security access, and only people using it are trusted authenticated users :-)
Related
I have a chatting room with maximum of 2 users, when one user send a message to another, the second user should be notified that new message is received just like Facebook
I have done it with Ajax request like
$(document).ready(
function() {
setInterval(function() {
$.ajax({
url: 'incs/check_new_msg.php' ,
cache: false,
success: function(data)
{
$('#message').html(data);
},
});
}, 1000);
});
<div id="message"></div>
In check_new_msg.php I use the following code:
$new_msg = mysql_query("select * from inbox where status = '0' ");
echo mysql_num_rows($new_msg);
The above code work good but the problem is that it check inbox and new message each second , but it seems harmful for processor as it run a MySQL query each second, please help me how to to execute checking query only when a new message is received.
i will give you a concept then you should try to implement it.
create an external text file when inserting something from another computer and at client side check same file each second rather than checking database. if file exists then check database else continue checking text file
So your only concern is it runs the query every second right?
Here's my solution:
$(document).ready(
function() {
function check_message()
{
$.ajax({
url: 'incs/check_new_msg.php' ,
cache: false,
success: function(data)
{
$('#message').html(data);
},
complete: function(data)
{
check_message();
},
});
}
check_message();
});
<div id="message"></div>
What this does is it will call the ajax recursively once the last ajax request is completed.
One of the ways of implementing the feature you discussed is long polling method. In this method you leave the connection open for certain time and if the changes occur within that time, the response is returned back to user. and another connection is opened and so on.
You should google about longpolling as there are lots of tutorials available. Best of luck
I found a good solution for this problem , for this purpose i use a notepad file in same directory where the script exists.
when inserting a new record from any computer you have to create notepad file with insertion.
$insert = mysql_query("insert into inbox .....");
if(insert)
{
if(!file_exists(notepad_file_path))
{
fopen(notepad_file_path);
}
}
Then I call ajax request request
$(document).ready(
function() {
function check_message()
{
$.ajax({
url: 'incs/check_new_msg.php' ,
cache: false,
success: function(data)
{
$('#message').html(data);
},
complete: function(data)
{
check_message();
},
});
}
check_message();
});
<div id="message"></div>
After that in external ajax file check existence of notepad file, if file exists then give access to database, in that way it will not be harmful for processor.
if(file_exists(notepad_file_path))
{
$new_msg = mysql_query("select * from inbox where status = '0' ");
echo mysql_num_rows($new_msg);
if(mysql_num_rows($new_msg) == 0)
{
unlink(notepad_file_path);
}
}
I have a function which saves an array each time the button is clicked to localStorage.The button will be clicked multiple times and I need to put this Array list into PHP somehow which is on another page from this file.
Thanks
a.js
(this function listens onLoad of the page)
function doFirst(){
var button = document.getElementById("button");
button.addEventListener("click", save, false);
var buttons = document.getElementById("clear");
buttons.addEventListener("click", clear, false);
var buttonss = document.getElementById("submittodb");
buttonss.addEventListener("click", toPHP, false);
$.ajax({
method: 'post',
dataType: 'json',
url: 'edit.php',
data: { items: oldItems }, //NOTE THIS LINE, it's QUITE important
success: function() {//some code to handle successful upload, if needed
}
});
}
function save(){
var oldItems = JSON.parse(localStorage.getItem('itemsArray')) || [];
var newItem = {
'num': document.getElementById("num").value,
'methv': document.getElementById("methv").value,
'q1': document.getElementById("q1").value,
'q2':document.getElementById("q2").value,
'q3':document.getElementById("q3").value,
'q4':document.getElementById("q4").value,
'comm':document.getElementById("comm").value,
};
oldItems.push(newItem);
localStorage.setItem('itemsArray', JSON.stringify(oldItems));}
edit.php
$parsed_array = json_decode($_POST['items']);
and i get the error: Notice: Undefined index: items in /home/project/edit.php on line 9
In order to pass this array to PHP you need to:
JSon-encode it
Make an AJAX or POST request to PHP
Parse the passed array into PHP array
If you're using jQuery (if you're not you should start - it is really handy tool) steps (1) and (2) is as simple as
$.ajax({
method: 'post',
dataType: 'json',
url: 'the URL of PHP page that will handle the request',
data: { items: oldItems }, //NOTE THIS LINE, it's QUITE important
success: function() {//some code to handle successful upload, if needed
}
});
In PHP you can parse the passed array with just
$parsed_array = json_decode($_POST['items']);
There is a direct connection between { items: oldItems } and $_POST['items']. The name of variable you give to the parameter in javascript call will be the name of key in $_POST array where it ends up. So if you just use data: oldItems in javascript you'll have all your entities scattered around the $_POST array.
More on $.ajax, and json_decode for reference.
You can create an AJAX function (use jQuery) and send the JSON data to the server and then manage it using a PHP function/method.
Basically, you need to send the data from the client (browser) back to the server where the database hosted.
Call JSON.stringify(oldItems); to create the json string
Do a Do a POST request using AJAX.
Probably the simplest way is using jQuery:
$.post('http://server.com/url.php', { items: JSON.stringify(oldItems) }, function(response) {
// it worked.
});
I need to load only new data into my div with ajax. At the moment I'm currently loading all data, because if I delete a record in the database it also removes it from my chat div.
Here is my js code:
var chat = {}
chat.fetchMessages = function () {
$.ajax({
url: '/ajax/client.php',
type: 'post',
data: { method: 'fetch', thread: thread},
success: function(data) {
$('.chat_window').html(data);
}
});
}
chat.throwMessage = function (message) {
if ($.trim(message).length != 0) {
$.ajax({
url: '/ajax/client.php',
type: 'post',
data: { method: 'throw', message: message, thread: thread},
success: function(data) {
chat.fetchMessages();
chat.entry.val('');
}
});
}
}
chat.entry = $('.entry');
chat.entry.bind('keydown', function(e) {
if(e.keyCode == 13) {
if($(this).val() == ''){
} else {
chat.throwMessage($(this).val());
e.preventDefault();
}
}
});
chat.interval = setInterval(chat.fetchMessages, 8000);
chat.fetchMessages();
I have had a look around and some say that if you pass a timestamp to the server and load new content that way, but I can't seem to get my head around that. If you need php let me know.
Right, so the timestamp thing makes the most sense. You'll need to do a few things:
On the back end, you need to make client.php accept a timestamp parameter in the querystring. When returning data, instead of just returning all of it, make it return everything since the time stamp, if given. Otherwise return everything.
The very first time you load the chat client, the first thing you should do is make an Ajax call to a new PHP file that returns the current server timestamp. Store the value of that in a Javascript variable as a Number.
During chat.fetchMessages(), increment the value of the timestamp variable by however long it's been since the last fetch (looks like 8000 milliseconds), and feed that to client.php, like url: '/ajax/client.php?timestamp=' + latestFetchTimestamp,
Instead of replacing all HTML content, append instead.
NOTE:
I gave up on trying to do the processing in one go, and just let it return after every x number of sends.
Two paths,
/sms?action=send
/sms?action=status
Let's say that the send path starts sending 10,000 sms messages via REST api calls.
I make a call to that page via ajax.
Then every few seconds, I make a call to /sms?action=status to see how the progress is going, and to update a progress bar.
The status path returns false if no messages are being sent.
What ends up happening is that the ajax call to the SEND path gets the ajax success: function called almost instantly, even though I know the script is taking 1+ minute to complete execution.
My progress bar never gets shown because the status ajax call (which is in a set interval with a few second delay) never seems to actually get called until the send call completes.
I'm trying to put the relevant code in here, but it may not be as clear as it should be without all the context.
<script type="text/javascript">
var smsInterval = 0;
var smsSending = false;
$(document).ready(function() {
var charCount = 0;
var smsText = "";
var smsTotal = <?php echo $options["smsTotal"]; ?>;
<?php if($options["sending"]): ?>
smsStatus();
smsSending = true;
smsInterval = setInterval("smsStatus()", 5000);
<?php endif; ?>
$("span#smsadmin_charcount").html(charCount.toString());
//send button
$("div#smssend").click(function() {
if(smsSending == true) {
return false;
}
smsStatus();
var dataString = $("#smsadmin_form").serialize();
smsSending = true;
$("div#smssend").html("Sending...");
$.ajax({
type: "POST",
url: "<?php echo $base_url; ?>/admin/sms",
data : dataString,
success: function(data) {
},
error: function(request, error) {
$("div.notice.sms").html("ERROR "+error+ "REQUEST "+request);
}
});
});
});
function smsStatus() {
var dataString = "smsaction=status&ajax=true";
$.ajax({
type: "POST",
url: "<?php echo $base_url; ?>/admin/sms",
data : dataString,
success: function(data) {
//data being false here indicates the process finished
if(data == false) {
clearInterval(smsInterval);
var basewidth = $("div.sms_progress_bg").width();
$("div.sms_progress_bar").width(parseInt(basewidth));
$("div.sms_progress_notice").html(parseInt(100) + "% Complete");
smsSending = false;
$("div#smssend").html("Send To <?php echo $options["smsTotal"]; ?> Recipients");
} else {
var pcomplete = parseFloat(data);
$("div.sms_progress_bg").show();
var basewidth = $("div.sms_progress_bg").width();
$("div.sms_progress_bar").width(parseInt(basewidth * pcomplete));
$("div.sms_progress_notice").html(parseInt(pcomplete * 100) + "% Complete");
}
},
error: function(request, error) {
$("div.notice.sms").html("ERROR "+error+ "REQUEST "+request);
}
});
}
I might be missing the point, but inside the $("div#smssend").click you got this line:
smsStatus();
shouldn't it be:
smsInterval = setInterval("smsStatus()", 5000);
and INSIDE the success: function(data) for /admin/sms ?
If the send part is sending out 10k messages, and the status returns true if currently sending a message, and false if in between sending, then you have a design issue.
For example, what is status supposed to be showing?
If status is to show how many of a certain block have been sent, then what you can do is to submit the message to be sent (or addresses), and get back some id for that block.
Then, when you ask for a status, pass the id, and your server can determine how many of that group has been sent, and return back the number that were successful, and unsuccessful, and how many are still pending. If you want to get fancy, you can also give an indication how much longer it may be before finishing, based on how many other requests are also pending.
But, how you approach this really depends on what you expect when you ask for the status.
I have a form that uses ajax to submit data to a mysql database, then sends the form on to PayPal.
However, after submitting, if I click the back button on my browser, change some fields, and then submit the form again, the mysql data isn't updated, nor is a new entry created.
Here's my Jquery:
$j(".submit").click(function() {
var hasError = false;
var order_id = $j('input[name="custom"]').val();
var order_amount = $j('input[name="amount"]').val();
var service_type = $j('input[name="item_name"]').val();
var order_to = $j('input[name="to"]').val();
var order_from = $j('input[name="from"]').val();
var order_message = $j('textarea#message').val();
if(hasError == false) {
var dataString = 'order_id='+ order_id + '&order_amount=' + order_amount + '&service_type=' + service_type + '&order_to=' + order_to + '&order_from=' + order_from + '&order_message=' + order_message;
$j.ajax({ type: "GET", cache: false, url: "/gc_process.php", data: dataString, success: function() { } });
} else {
return false;
}
});
Here's what my PHP script looks like:
<?php
// Make a MySQL Connection
include('dbconnect.php');
// Get data
$order_id = $_GET['order_id'];
$amount = $_GET['order_amount'];
$type = $_GET['service_type'];
$to = $_GET['order_to'];
$from = $_GET['order_from'];
$message = $_GET['order_message'];
// Insert a row of information into the table
mysql_query("REPLACE INTO gift_certificates (order_id, order_type, amount, order_to, order_from, order_message) VALUES('$order_id', '$type', '$amount', '$to', '$from', '$message')");
mysql_close();
?>
Any ideas?
You really should be using POST instead of GET, but regardless, I would check the following:
That jQuery is executing the ajax call after you click back and change the information, you should probably put either a console.log or an alert calls to see if javascript is failing
Add some echos in the PHP and some exits and go line by line and see how far it gets. Since you have it as a get, you can just load up another tab in your browser and change the information you need to.
if $j in your jQuery is the form you should be able to just do $j.serialize(), it's a handy function to get all the form data in one string
Mate,
Have you enclosed your jquery in
$j(function(){
});
To make sure it is only executed when the dom is ready?
Also, I'm assuming that you've manually gone and renamed jquery from "$" to "$j" to prevent namespace conflicts. If that isn't the case it should be $(function and not $j(function
Anyway apart from that, here are some tips for your code:
Step 1: rename all the "name" fields to be the name you want them to be in your "dataString" object. For example change input[name=from] to have the name "order_from"
Step 2:
Use this code.
$j(function(){
$j(".submit").click(function() {
var hasError = false;
if(hasError == false) {
var dataString = $j('form').serialize();
$j.ajax({ type: "GET", cache: false, url: "/gc_process.php?uu="+Math.random(), data: dataString, success: function() { } });
} else {
return false;
}
});
});
You'll notice i slapped a random variable "uu=random" on the url, this is generally a built in function to jquery, but to make sure it isn't caching the response you can force it using this method.
good luck. If that doesn't work, try the script without renaming jquery on a fresh page. See if that works, you might have some collisions between that and other scripts on the page
Turns out the problem is due to the fact that I am using iframes. I was able to fix the problem by making the page without iframes. Thanks for your help all!