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 :)
Related
I've read all the articles but cant seem to get my ajax response into a PHP variable. Please can you advice. I want to assign rowid to a PHP variable.
$(document).on('click', '#updateid', function() {
var vallab = $('#idval').val();
var rowid;
$.ajax({
url:'a.php',
type: 'POST',
async: false,
data: {labid: vallab},
success: function(data){
// console.log(data);
rowid = data;
}
});
console.log(rowid);
return rowid;
});
my a.php code is below
<?php
# Fetch the variable if it's set.
$lab_id = (isset($_POST["labid"])) ? $_POST["labid"] : null;
echo $lab_id;
?>
I am getting the response back with the id, and want to use it on that page
I want to pass rowid into a PHP function so I need to get the value of rowid.
Please can you advice?
I cant seem to get my ajax response into a PHP variable
Well, the AJAX response came FROM a PHP file, right? So why don't you do whatever you need to do with the response right in that PHP file?
$.ajax({
url:'THIS IS YOUR PHP FILE',
type: 'POST',
data: {THIS IS THE DATA YOU SEND TO PHP},
success: function(data){
console.log(data); //THIS IS THE RESPONSE YOU GET BACK
}
});
You can't use it. Javascript is a scripting language which run in browser when the dom is loaded and elements are visible.
PHP is a serverside language and run on server before the page is loaded.
You need to understand the lifecycle of your application. Your php code executes once, it runs the full script from top to bottom when the page loads. At the point the script starts if can only access the post that came with the request (e.g if you clicked submit on a form then the 'action' of the form receives the post). Any number of things can happen in your script, but once it's finished the php is gone, and so is the post (in basic terms). So you no longer have any access to the php which created this page.
Ajax allows you to update a section of your page - it sends a request to your sever and runs some php code - you must understand that this is a new and separate request, so the new post submission only exists in the lifecycle of this new execution and is in now way linked to the page that has already finished loading. Now you could ask Ajax to call your original script, but that wouldn't affect your page at all because the page does not reload. What you would get is a strange looking response which you (probably) couldn't do anything useful with.
Ajax allows small specific changes to the page, so when you get your response (which I assume you get in a format you want since you don't ask about it and you have a console.log) you then need to do something with jQuery/javascript. Instead of returning rowid write a javascript function like :
function printRowId(rowid) {
$('#your html div id here').text('Row id is ' + rowid);
}
and then call it in your response:
$.ajax({
url:'a.php',
type: 'POST',
async: false,
data: {labid: vallab},
success: function(data){
// console.log(data);
rowid = data;
}
});
printRowId(rowid);
return rowid;
You can use Ajax to update your data, update your database and then reflect the changes on the current page, but you cannot use it to pass directly to the php that has already finished executing
I got the following ajax where I want to send data from a < form > to a PHP page, where the data will be stored in a DataBase and then I will return a password generated in the PHP to the AJAX, but seems that I can't succeed
$.ajax({
type:'POST',
url:'register.php',
data:$('#form_register').serialize(),
});
I'm new to AJAX and every answer I saw was just a PHP page with a few lines of code, it's impossible to use the JSON response in a PHP page with more code?
If you want to return some data from your register.php, you have to output it in this file:
<?php
// register.php
/* Do whatever has to be done here */
echo json_encode(<your data-array here>); // Encode the data you want to return here
In your script where the ajax request is made you have to handle the response from register.php
$.ajax({
type:'POST',
url:'register.php',
data:$('#form_register').serialize()
}).done(function(returnedData) {
// Process the returnedData
});
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..
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 want a code for multiple ajax request. What happens actually is my first ajax request give me the response and in that responce function i m calling another function which having another website url. I want to send data to this new website using multiple ajax request.
Please help me out...
Thanks,
Prafulla
use global variables and manipulate your data in each request.
like:
var a;
$.ajax({
url:url_one;
success: function(data){ a =data; }
});
$.ajax({
url:url_two;
data: a //sends the data from the 1st request
success: function(data){
//do something with the data from the 2nd url
}
});
You can encapsulate your ajax call in function or event handlers as you need.
You can also manuipulate the data returned in variable a before sending it to the 2nd url.
Seems sloppy to me, but sould work.