send multiple requests using ajax in php - php

I am trying to send Push Notifications to android devices using a php script. This works fine if i send it to one device each time, but i have more than 1000 devices and want to send it to all of them at one go. I tried using a loop but it's not working.
<script type="text/javascript">
$(document).ready(function(){
});
function sendToAll(totalUsers){
for(var i=0;i<totalUsers;i++)
{
sendPushNotification(i);
}
}
function sendPushNotification(id){
var data = $('form#1').serialize();
$('form#1').unbind('submit');
$.ajax({
url: "send_message.php",
type: 'GET',
data: data,
beforeSend: function() {
},
success: function(data, textStatus, xhr) {
$('.txt_message').val("");
$('.txt_excerpt').val("");
},
error: function(xhr, textStatus, errorThrown) {
}
});
return false;
}
</script>
This is my HTML form. $no_of_users variable contains the total rows fetched in the select query i.e. the total number of users in the table.
<form id="1" name="" method="post" onsubmit="return sendToAll('<?php echo $no_of_users; ?>')">
<label>Send Message to All the Users</label>
<div class="clear"></div>
<div class="send_container">
<textarea rows="3" name="excerpt" cols="10" class="txt_excerpt" placeholder="Type excerpt here"></textarea>
<textarea rows="3" name="message" cols="25" class="txt_message" placeholder="Type message here"></textarea>
<input type="submit" class="send_btn" value="Send" onclick=""/>

You should use asyncronous requisitions to make all at "same time", use this instruction on your ajax call:
async: true,

You want to push some message to approx. 1000 devices from server. And you want to initiate this with the form and script you presented in the question. But you must also think about the way how server will communicate with devices. There must be some way for you server to reach clients.
One way - instruct you clients to poll server for new messages every N seconds for example. This generates unnecessary traffic and loads the server.
Second way - to use websocket on clients and have server-side support for this. It can be not so trivial as it can appear to be
And one more way - is to use long polling.
Anyways - devices must be instructed in some way how can they receive push messages from server.

Related

Refresh instantly with Ajax

I am trying to understand ajax and want to figure out how I can refresh a div that displays a rowcount from a mysql database live as the data is entered into that database.
I have a simple form on the same page and as the data is submitted from the form to the database how can I make the div update 'live' as well?
The code I've posted here posts a name from a form which is inserted into a mysql database. Then the number of rows in the database is counted and returned as a json object. It all works fine but only refreshes the rowcount when I reload the page and I want it to refresh instantly.
Many thanks.
The form
<form class="form-inline" action="" id="myform" form="" method="post">
<!-- Text input-->
<div class="form-group">
<label class="col-md-4 control-label" for="name"></label>
<div class="col-md-8">
<input id="name" name="name" type="text" placeholder="name" class="form-control input-lg" required>
</div>
</div>
<!-- Button -->
<div class="form-group">
<label class="col-md-4 control-label" for="submit1"></label>
<div class="col-md-4">
<button id="submitButtonId" name="submit1" class="btn btn-primary btn-xl">Submit</button>
</div>
</div>
</form>
<!---------Display rowcount from database--------->
The jquery
<script>
$(document).ready(function(){
$("#submitButtonId").on("click",function(e){
e.preventDefault();
var formdata = $(this.form).serialize();
$.post('data.php', formdata,
function(data){
//Reset Form
$('#myform')[0].reset();
});
return false;
});
});
</script>
<script>
$(document).ready(function() {
$.ajax({
url: 'data.php',
dataType: "json",
success: function (data) {
$("#count").append(data.count);
}
});
return false;
});
</script>
data.php
<?php
//include db configuration file
include_once("db_conx.php");
$name= mysqli_real_escape_string($db_conx,$_POST['name']);
//Update Database
$stmt = $db_conx->prepare('INSERT INTO my_table set name?');
$stmt->bind_param('s',$name);
$stmt->execute();
//Count Rows
$sql="SELECT name FROM utility";
$query = mysqli_query($db_conx, $sql);
// Return the number of rows in result set
$rowcount=mysqli_num_rows($query);
// sending JSON output
$my_data=array(count=>"$rowcount");
echo json_encode($my_data,true);
?>
If you want the server to push events to the client, you can use Websockets. There are services like Pusher that can help, it has a free plan (100 connections, 200K messages per day) and a good documentation to integrate with PHP and some popular frameworks.
If you don't want to use websockets, you can use a more traditionnal polling : every X seconds, you make a GET request to the server asking for the count, if it changes you update it, if not you do nothing and wait for the next call. This can be setup easily with setTimeout() in Javascript.
With PHP + ajax you should query to the database every X time with a timeout (setTimeOut()).
You could use websockets or take a look to firebase.
Also I suggest you to change .append(data.count); to .html(data.count); in order to 'clean' the div, if not, you may have multiple 'data.count' on it.
Here a post with a lot of answers for this: What are Long-Polling, Websockets, Server-Sent Events (SSE) and Comet?

Adding a "Mail Sending..." notification during AJAX request

In my mail sending script powering my contact form, the mail sending action can take some time, during this time the user doesn't know what happens. So, I wanted to add a "Mail Sending..." notification. The "Mail Sending..." notification appears when the submit button is clicked, but the script processing stalls at this point infinitely, and further mail processing is not done. I shall appreciate clues on how to resolve this. Find below the AJAX script and html form code.
<script>
$(document).ready(function(){
$('#submit').click(function(){
$.post("send.php", $("#contactform").serialize(),function(response) {
$('#success').html('<h4>Mail Sending...</h4>').load(url);
});
return false;
});
});
</script>
And this is the contact form html code:
<form action="" method="post" id="contactform" >
<label for="name">Name:</label><br />
<input type="text" name="name" id="name" /><br />
<label for="email">Email:</label><br />
<input type="text" name="email" id="email" /><br />
<label for="message">Message:</label><br />
<textarea name="message" id="message"></textarea><br />
<input type="button" value="send" id="submit" />
<div id="success" style="color:red;"></div>
</form>
Well,
"during this time the user doesn't know what happens. So, I wanted to add a "Mail Sending..." notification."
How about ajaxStart as this is exactly what it is designed for.
"Show a loading message whenever an Ajax request starts (and none is already active)."
You can simply attach the event handler to any element:
$( document ).ajaxStart(function() {
$( "#loading" ).show();
});
Then in the case when the ajax request is started the loading div will be shown. Once the ajax is done it will be hidden again as it would with:
$( "#loading" ).hide();
You will want to make sure that the div with that id (loading) is hidden by default.
"but the script processing stalls at this point infinitely, and further mail processing is not done."
Per jQUery Post:
If a request with jQuery.post() returns an error code, it will fail silently unless the script has also called the global .ajaxError() method. Alternatively, as of jQuery 1.5, the .error() method of the jqXHR object returned by jQuery.post() is also available for error handling.
If your post is failing it should return an indication as to why.
<script>
$(document).ready(function(){
$('#submit').click(function(){
$.post( "test.php", $( "#testform" ).serialize() )
.done(function( data ) {
$('#success').html('<h4>Mail Sending...</h4>');
// You should not do a .load within another ajax call so placing it here is okay as it will execute AFTER the original one completes, but it will trigger the ajaxStart method again.
})
.fail(function ( data ) {
console.log(data);
});
});
});
</script>
Unfortunately I am on mobile so I can't test the above to make sure it works, but that should get you started.

How to deal with php POST when form is dynamic

My client page (form builder) is dynamic, i.e. User can build a form with 2 text areas and 1 text field or any amount needed.
Ive been able to do it and change their IDS too. Now I have to send these data to server side PHP.
Now what if the user enters more fields or less? like 5 text areas 10 text fields. How can Write the server side code?
Client side e.g
<textarea type="text" name="TxtArea1" /></textarea>
<textarea type="text" name="TxtArea2" /></textarea>
<input type="text" name="Txt1" />
Ajax post e.g
$.ajax(
{
url : formURL,
type: "POST",
data : postData,
success:function(data, textStatus, jqXHR)
{
$("#main").load("test.php");
},
error: function(jqXHR, textStatus, errorThrown)
{
$("#main").load("An err occured");
}
Server side e.g
$f1 = $_POST[ 'TxtArea1' ];
$f2 = $_POST[ 'TxtArea2' ];
$f3 = $_POST[ 'Txt1' ];
You can use array notation to have your form elements show up as an array on the server side in the respective $_POST index
<textarea type="text" name="TxtArea[]" /></textarea>
<input type="text" name="Txt[]" />
Then you can loop over $_POST['TxtArea']

How to use server validation & client-side validation with jQuery Tools?

Ok, so I have the following form in a jQuery overlay:
<div class="profile_about_edit_container" id="profile_about_edit_container">
<form id="profile_edit_form" name="profile_edit_form" method="post" action="validation.php">
<label>First Name:</label>
<input type="text" name="firstname" maxlength="50" size="30">
<label>Last Name:</label>
<input type="text" name="lastname" maxlength="50" size="30">
<button type="submit" class="save">Save</button>
<button class="close">Cancel</button>
</form>
</div>
This is displayed using an <a> with class="profile_popups_form" and the following Javascript:
$(document).ready(function() {
$(".profile_popups_form").overlay({
});
});
This shows correctly, and validation.php then echo's an array of error messages like so:
if (count($errors) > 0) {
echo json_encode($errors);
}
But now I'm trying to use jQuery client & server validation on this form.
I tried this:
$(document).ready(function(){
var form = $("#profile_edit_form");
$("#profile_edit_form").submit(function(e) {
e.preventDefault();
var input = $("#profile_edit_form").validator();
$.getJSON(form.attr("action") + "?" + form.serialize(), function(json) {
if (json !== '') {
input.data("validator").invalidate(json);
}
else
$('#profile_edit_form').unbind('submit').submit();
});
});
With the objective of submitting the form and displaying this array of error messages in the normal way jQuery Tools Validation does. But I'm having no luck.
Am I approaching this right? If so, what am I doing wrong? I'm not sure if it's the Javascript causing the issue, or if I'm approaching this right logically. I can find literally no resources explaining how to use JQuery Tools Validation with PHP successfully.
Currently the array is just displayed on the screen as if you echo'd text.
I used the following resource to get the code for returning the array:
http://www.abdullahyahya.com/2012/06/20/javascript-client-side-form-validation-using-server-side-form-validation/
Try doing an ajax request to a php file and get back the response from server. The client side can be done with various ways; from HTML5 tags to plain regex
data = $(this).serializeArray();
//we serialized the data of the form and then we do the ajax request
$.ajax({
url: 'validate.php',
type: 'post',
data: data,
dataType : 'json',
success: function (dat) {
if(dat.error==0){
//dat.error is my returned error from the php file
}else{
//handle the errors
}
}
},
error: function(){
//that's if something is wrong with sent data
alert('failure');
}
});

PHP/jQuery: Fadein/refresh after insert

i have a "wall" on each profile, and i wish to make it smarter, so you don't need to update the page to view your inserted message you just put up.
When you insert a message, it makes a ajax call and inserts to the database, and you receive a message about it has been inserted. But right now you need to refresh the page to see your inserted message. What i want to do is if you insert a new message, it should fadein /refresh the wall with messages that is right under the form.
How can I do this?
I have worked on it alittle and tried to make a new file, inserted all coding to show comments and then i set timeout to refresh each 2 seconds
function ajax_update() {
var wrapperId = '#box';
var profileID = document.getElementById('profileID');
var postFile = 'showcomments.php?id='+ profileID.value;
_v++;
_v2++;
$.post(postFile, { v2: _v2 , v: _v},
function(data){
$(wrapperId).html(data);
});
setTimeout('ajax_update()', 2000);
}
but this isnt good, as it makes too many server calls, so hope you can help me out, since i dont know how i should do this in a cool way
Form with ajax call:
http://phpbin.net/x/838833504
And my current php code that grab from db and list in messages:
http://phpbin.net/x/2145692361
I would suggest a slight methodology change:
submit the new post to the database via AJAX
in the success callback for that AJAX post, create an element with the content that was submitted and append it to the list of posts on the page.
if you want it to look cool just use some of the built in animation effects (fadeIn, show, etc).
This way, you're not polling for changes all the time, and you only have to request things from the server upon page loads.
function DoWallInsert(){
var wrapperId = '#box';
var profileID = document.getElementById('profileID');
$("#insert_response").html("Laddar..");
$.ajax({
type: "POST",
url: "misc/insertWall.php",
data: {
value: 'y',
BuID : $('#BuID').val(),
uID : $('#uID').val(),
message : $('#message').val()
},
success: function(msg){
// in here you will have to add the message to the top of the list of wall posts
// to do this you use prepend whatever html and the message in whatever way you
// are using to display the messages.
$(wrapperId).prepend("<div>" + $('#message').val() + "</div>");
}
});
}
html might look like this before:
<form action="javascript:DoWallInsert()" method="post">
<input name="message" type="text" id="message" value="" size="40">
<input type="hidden" name="BuID" id="BuID" value="123123">
<input type="hidden" name="uID" id="uID" value="53425">
<input name="submit" type="submit" id="submit" value="Skicka">
</form>
<div id="box">
<div id="post-1">Some stuff</div>
<div id="post-2">Some other stuff</div>
</div>
html should look like this after:
<form action="javascript:DoWallInsert()" method="post">
<input name="message" type="text" id="message" value="" size="40">
<input type="hidden" name="BuID" id="BuID" value="123123">
<input type="hidden" name="uID" id="uID" value="53425">
<input name="submit" type="submit" id="submit" value="Skicka">
</form>
<div id="box">
<div>Whatever was typed in the box</div>
<div id="post-1">Some stuff</div>
<div id="post-2">Some other stuff</div>
</div>
If the html you want to append to the list of posts has php in it then my best suggestion is to return the html for the new div in the response from the server on the on the AJAX call to this: misc/insertWall.php
insertWall.php should return "<a href='profil.php?id=".$userinfo[id]."'>".$userinfo["full_name"]."</a>". then you can process it and display it in the success part of DoWallInsert():
success: function(msg){
// in here you are receiving a response, you should display it in the page
// this assumes that you are fully formatting the message before returning it
// and you just want to insert it here.
$(wrapperId).prepend(msg);
}
One way is to return the newly updated wall listing from your .post() handler on the server. Then in the callback, repaint the wall area with that content (forget about using setTimeout()). You could also do the same thing, but working message by message, adding the latest message to the top of the "stack" in your wall content area.
So, repainting the whole wall:
$.post(postFile, { v2: _v2 , v: _v},
function(data){
// make your server return the updated wall content
// return data.whatever
// data.wallcontent
$('#wrapperId').html(data.wallcontent);
});
or message by message:
$.post(postFile, { v2: _v2 , v: _v},
function(data){
// make your server return the new message ready for insert
// return data.whatever
// data.message_you_just_posted_formatted
$('#wrapperId')
.prepend( data.message_you_just_posted_formatted );
});
That's the basic idea.

Categories