I have a situation;
I'm calling PHP page through AJAX which require to execute a script on other server which has the email server rights. To be more specific on PHP page after Entering data in Database I have to access the Email server with certain parameters in Query String.
On index.php page i have submit button which enters the data in database through AJAX call and then have to send an email to the user for information.
but for email i need to execute PHP script on other server which have Email server access.
CLIENT SIDE
$.ajax({
url:'vpms/server/updating.php',
type:'POST',
data:formvalues,
success: function(data) {
closelightbox('black_overlay','vendorfeedback',ref-1,'CLOSE');
}
});
IN updating.php
enter code here
if($_POST['Type']=='SUBMITRATING')
{
$sql->Query("INSERT INTO vpms_procurement(`prno`,`vn`,`category`,`paymentterms`,`c1`,`delivery`,`c2`,`communication`,`c3`,`dated`,emaildate ) VALUES('$_POST[PRNO]','$_POST[$vendor]','$_POST[$category]','$_POST[$payment]','$_POST[$payment_txt]','$_POST[$delivery]','$_POST[$delivery_txt]','$_POST[$response]','$_POST[$response_txt]',NOW(),'$_POST[$date]')");
}
$enc=Autoloader::encrypt(serialize($array));
// Sending request to other server for email
header("Location: 10.89.6.2/managerConfirmation.php?token=$enc"); // This is not possible through ajax call
//OR
exec("10.89.6.2/managerConfirmation.php?token=$enc")
}
Options which I may think of.
Using exec("PHP script?q=value");
Or on success of Ajax call make another call through JSONP to access remoteserver.
But I don't know how practical these options are, because I'm also using encrypted data in query string.
your code is vulnerable to sql injection you need to escape all get and post
send use ajax call on successful return of first ajax call
Use 2nd Ajax call on 1st successful ajax response.
$.ajax({
url:'vpms/server/updating.php',
type:'POST',
data:formvalues,
success: function(return_data) {
//Make 2nd ajax call here and run the remote script
enc = return_data ;
$.ajax({
url:'10.89.6.2/managerConfirmation.php?token='+enc,
type:'POST',
data:anything,
success: function(data) {
closelightbox('black_overlay','vendorfeedback',ref-1,'CLOSE');
}
});
}
});
Eventually i had to go with option of another ajax call , but i wanted to share a strange case.
It might help someone.
I used Ajax call which had no Callback and each request also had the failure message
"XMLHttpRequest cannot load 'Remote server address' Origin http://mystuff.local is not allowed by Access-Control-Allow-Origin"
but strangely each request also Succeeded with the delivery of email..
Related
I am working in Banking project .I want to write php code to update table upon successful Transaction using ajax . suppose i am sending request from fundtransfer.php to external API and the External API is also responding correctly .Now upon successful API respond i want to update my database table field name status from pending to completed .
<script>
$(document).ready(function()
{
$.ajax(
{
url:"http://someexternalwebsite.com/API",
type:"post",
data:"variable="+value,
success:function(result)
{
if(result==100)
{
$("#message").html(successful transaction);
//Now i want to update my database tabale status saying Successful Transation
//where to write these all php mysql code to update my database table
// without loading and redirecting page
}
else
{
$("#message").html(some thing gone wrong);
}
}
});
});
</script>
without loading and redirecting page
The same thing you're doing now... Making an AJAX request. (Assuming your initial AJAX request isn't rejected by the Same Origin Policy...) Upon successfully returning from the first AJAX request, you'd make a second one to your code. Something like this:
$.ajax({
url: 'someAPI',
success: function (response) {
$.ajax({
url: 'someDBPage',
success : function (dbResponse) {
// notify the user of success
}
});
}
});
The PHP code at someDBPage would interact with your database just like any other PHP code. And you'd send it data just like any other AJAX POST request, similar to how you're sending data to the API URL now.
You could try:
$.get("http://someexternalwebsite.com/API/?variable="+value) for the http GET method.
or:
Use JavaScript:
function post(data, url){
$.post(url , data
, function (response) {
func(response);
});
}
Then use post(....) inside jquery
I hope it helps you, Good luck :)
i am sending ajax request from html page using jquery to send the bulk emails and fetch the data from the server.
here is the code to send request for bulk mail
var sendReq = $.ajax({
type: 'post',
data: "leftID="+JSON.stringify(leftID)+"&rightID="+JSON.stringify(rightID)+"&mode="+mode,
dataType: 'json',
url:"bulk.php"
});
sendReq.done(function( data ) {
$("#bms-ack").html(data.status);
$("#bms-ack").fadeIn('slow');
$("#bms-ack").fadeOut(6000);
console.log(data);
console.log("success");
});
sendReq.fail(function(jqXHR, data){
$("#bms-ack").html(data.status);
$("#bms-ack").fadeIn('slow');
$("#bms-ack").fadeOut(6000);
console.log("fail");
});
now the issue is when i send a request to php page it will send mails and respond with success message.
as the php is returning the response back to the client so will this ajax request going to get blocked ? because when i send another request from jqtable to fetch new data it takes time until the previous request of ajax to send bulk mail hans't finished. and eventually my jqtable keeps loading.
how do i get rid of blocking request , should i remove returning success message from php and if i do so then how the user will know that the request has been submitted ?
If I understand you correctly your issue is that you can't fire another javascript call while the first one is running? That's because Javascript is single-threaded in most browser implementations.
Some light reading:Is JavaScript guaranteed to be single-threaded?
As far as I know, if you send an AJAX petition, is exactly the same as requiring a new page in a non-asynchronous way: As long as the page is not sent to the browser, you keep waiting for the result, and any other request is just a refresh.
So, if you want to achieve a "non-blocking" AJAX way, send the AJAX petition to "differents" URLs. I mean:
url:"bulk.php" => Change to url: "bulk.php?v=3"
the query string is just a foo, and it's only to change the URL you're calling.
When you'll make your AJAX petitions, just add a query string for every petition you're doing (with a ?v=X is more than enough, where X could be even one of the data you're retrieving, the id of the row, whatever...), and it'll work like a charm, as the browser think is a different petition and don't prevent you (block you) to retrieve the values the PHP file is generating (although you know the values are different because you're sending different data, :D)
Update
Uhm... It should allow you keep working. Just for checking, could you try the next piece of code and tell me what happens?
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
for(var $i=0; $i<5; $i++) {
$.ajax({
type: 'post',
url:"ajax.php?v="+$i,
success: function(data) {
console.log(data)
}
});
console.log('Browser: ' + $i);
}
});
</script>
</head>
<body>
AJAX TEST
</body>
</html>
AJAX File: (ajax.php)
<?php
sleep(5);
echo 'WAAAAAAAA';
To me, it sends 5 AJAX calls to the server at the same time (not blocking behaviour) almost immediately. I think that this is exactly what you want to achieve, could you test your browser and tell me if you're receiving the same? And by the way, could you post an image of the browser behaviour with the AJAX posts?
I have found many threads regarding this issue, but unfortunately I couldn't get it running. Problem is I don't know much about JQuery.
I am trying to make an Ajax call using JQuery in order to fetch multiple records from a mysql database. I have the following function :
function updateWebpage ()
{
$.ajax({
url: './sale/api.php', //the script to call to get data
data: "", //you can insert url argumnets here to pass to api.php
//for example "id=5&parent=6"
dataType: 'json', //data format
success: function(rows) //on recieve of reply
{
for (var i in rows)
{
var row = rows[i];
var username = row[0];
var stateId = row[1];
$('#output').append("<b>id: </b>"+username+"<b> stateId: </b>"+stateId)
.append("<hr />");
}
}
});
};
My api.php is executing a mysql query with something like this:
$array = retrieveUsersInfo('%'); //fetch result
echo json_encode($array);
My main issue, is how to debug an issue like this? Since ajax is calling asynchronously another file, I cannot view any errors. From my firefox debugger, I can see that the $.ajax function is entered, but success is not.
Thanks in advance.
a couple things to try.
hit the api url directly in a browser (not through ajax) and make sure it returns the valid response.
add an error: function(err){} to your jquery ajax call. this method will get called if there is something other than a 200 response back from the server.
I use Chrome's developer tools more than firefox/firebug. It has a Network tab in it that shows me all the communication between the client and the server. You should see a call out to your api in that tab.
just off hand, i think you need to make sure the mime-type is set to text/json in your php file.
I am creating a web application and have the following problem.
In my application the user is working within a single page, they draw on a canvas. There is a single button called "Save". This takes the users ID and whatever they have created in the canvas and sends it to a database. This all works fine. The save function resemebles this:
$.ajax({
url: "/database/write.php",
type: "POST",
data: {
docName: name,
docData: document_Data,
docMode: "new"
},
success: function(html) {
alert("Successfully Saved NEW document");
set_Mode();
},
});
The above AJAX request does send the three values to the PHP script which then successfully creates a new document in the database, what i need to do now is change the application mode from saving a new document to editing the previously saved document. This means that when a user saves again, they will write to the same row, overwriting the previous version of the document.
When i send the data to the write.php it does write the data to the DB and the queries the database for that inserted document and retrieves its unique document ID. with that ID the application can the select that document and overwrite it. To retrieve the document ID from the query, i use the following code in write.php
write.php
$_SESSION['DOCUMENT_ID'] = $DOCUMENT_ID;
This $DOCUMENT_ID is the document ID retrieved from the SELECT query. The script then finishes and transfers control back to the main application page.
Back on the application page i try to retreive the value but it doesnt seem to work. I can retrieve $_SESSION values that were set when the user first accesses the application (id) but now values set by the write.php (DOCUMENT_ID) page. For example, below shows the function called after the AJAX request has been successful:
function set_Mode()
{
var PHPvar_01 = <?php echo($_SESSION['id']); ?>;
alert(PHPvar_01); //WORKS FINE
var PHPvar_02 = <?php echo($_SESSION['DOCUMENT_ID']); ?>;
alert(PHPvar_02); //DOES NOT WORK.
};
How should i go about sending data retrieved from the PHP query script to the application, because $_SESSION does not seem to work here.
Thanks for any feedback.
at the end of write.php :
echo json_encode(array('id'=>$_SESSION['id'], 'DOCUMENT_ID'=>$_SESSION['DOCUMENT_ID']));
in your ajax call :
success: function(data) {
data = eval('('+data+')');
alert("Successfully Saved NEW document");
set_Mode(data.id, data.DOCUMENT_ID);
},
this should do the tricks !
In your write.php, you should echo the $DOCUMENT_ID at the end of the page, and then your success function will receive that in the html argument. Then you should call set_Mode with the html variable that was passed into the success function.
You can't call set_Mode until after the page is loaded, and after you know the document ID. You are writing the document ID into the set_Mode function before you know it, in the initial page load.
Well, your PHP code gets executed only once upon the initial loading of the page. The server detects a request to your site, loads the PHP document internally, parses it and delivers it to the client.
Therefore, when the AJAX call returns, the entire PHP script is not executed again, because the user didn't request the whole page but only sent a single request to your write.php.
Your write.php script must return the $DOCUMENT_ID in some way, e.g. echo it directly, then the success handler in the jQuery AJAX call can access it via the handler's parameter (see jQuery documentation).
You can't access variables on the server when the page is already loaded in the users browsers, other than with ajax.
You need to send something back, and in PHP all you have to do is echo something, and capture it in the success function of your Ajax call.
at the end of /database/write.php, do
echo $_SESSION['DOCUMENT_ID'];
and in JS
$.ajax({
url: "/database/write.php",
type: "POST",
data: {
docName: name,
docData: document_Data,
docMode: "new"
},
success: function(data) {
alert("Successfully Saved NEW document");
set_Mode();
if (data == 'something') {
//do something with the returned DOCUMENT_ID stored in the data variable
}
},
});
I have made a simple chat application which uses long-polling approach using jquery,
function sendchat(){
// this code sends the message
$.ajax({
url: "send.php",
async: true,
data: { /* send inputbox1.value */ },
success: function(data) { }
});
}
function listen_for_message(){
// this code listens for message
$.ajax({
url: "listen.php",
async: true,
timeout:5000,
success: function(data) { // the message recievend so display that message and make new request for listening new messages
$('#display').html(data);
listen_for_message();
}
});
}
THIS SHOULD HAPPEN : after page loaded the infinite request for listen.php occurs and when user sends message, the code sends message to database via send.php.
PROBLEM is, using firebug i've found that send.php request which is performed after listen.php request, is remains pending. means the request for send message is remains pending.
The issue was because of session locking;
both send.php and listen.php files use session variables,
so session is locked in listen.php file and the other file (here send.php file) can't be served after the session frees from serving another file ( here listen.php).
How do I implement basic "Long Polling"?
the link above is a similar question that may help you.
it does not have to be on a database, it can be saved on a tmp file, but your problem is that you are choking the browser by performing too many requests, any one browser handles two requests at a time, which means you should really allow the browser to finish the first requests first then do the second one... and so on...
you do not need to do send.php and listen.php, because you can do it simply on one page both of them.
function check(){
$.ajax({
url : 'process.php',
data : {msg:'blabla'/* add data here to post e.g inputbox1.value or serialised data */}
type : 'post',
success: function (r){
if(r.message){
$('#result').append(r.message);
check();//can use a setTimeout here if you wish
}
}
});
}
process.php
<?php
$msg = $_POST['msg'];//is blabla in this case.
$arg['message'] = $msg;//or grab from db or file
//obviously you will have to put it on a database or on a file ... your choice
//so you can differentiate who sent what to whom.
echo json_encode($arg);
?>
obviously this are only guide lines, but you will exhaust your bandwidth with this method, however it will be alot better because you have only one small file that returns either 0 to 1 byte of information, or more if there is a message posted.
I have not tested this so don't rely on it to work straight away you need a bit of changes to make it work but just helps you understand how you should do it.
however if you are looking for long pulling ajax there are loads of scripts out there already made and fine tuned and have been test, bug fixed and many minds help built it, my advice is don't re-invent the wheel