In the middle of a PayPal Checkout Express (client-side) javascript, I need to use AJAX to call the output of a PHP page, but I'm a bit stuck.
The PHP page:
$data = array('retid' => $username);
header('Content-Type: application/json');
echo json_encode($data);
Now inside the other javascript page I simply want to capture the PHP variable $username, via AJAX, as a javascript variable.
<?php
$IDToPassPlus = ($id.'&retid=');
?>
<script>
//It's the inclusion of this part, which tries to get the "retid" js variable, that stops the script from rendering the Paypal button:
$.ajax({
type: 'POST',
url: 'test-call.php',
dataType: 'json',
success: function(response) {
var retid = response.data.retid;
},
});
paypal.Button.render({
env: 'sandbox',
client: {
sandbox: 'xxxxx',
production: 'xxxxx'
},
commit: true,
style: {
layout: 'vertical',
size: 'responsive',
shape: 'rect',
color: 'gold'
},
payment: function(data, actions) {
return actions.payment.create({
payment: {
transactions: [
{
amount: { total: '0.99', currency: 'GBP' }
}
],
redirect_urls: {
'cancel_url': 'pay-return-cancel.php?id=<?php echo $IDToPassPlus; ?>'+retid
}
}
});
},
onAuthorize: function(data, actions, error) {
return actions.payment.execute().then(function() {
window.alert('Payment Complete!');
window.location.replace('test-return.php?id=<?php echo $IDToPassPlus; ?>'+retid);
if (error === 'INSTRUMENT_DECLINED') {
actions.restart();
}
});
},
onCancel: function(data, actions) {
return actions.redirect();
},
onError: function(err) {
window.location.replace('pay-return-error.php?id=<?php echo $id; ?>'+retid);
}
}, '#paypal-button');
</script>
Without the contributor's AJAX suggestion, the button works perfectly. But I'm trying to pass a variable from a PHP page by way of AJAX, to add it onto the redirects.
it's possible to use on in-page javascript as
<script>
var js_var = "<?php echo $php_var;?>";
//now you have php var value in javascript to use on .php page
If it's not what you are seeking, then please elaborate your question.
ok so as far I understood you want to retrieve the PHP response via ajax and you don't know how to make ajax call. Here is an example you may use on your js file:
$.ajax({
type: 'POST',
url: 'YOUR PHP SCRIPT URL',
dataType: 'json',//this will make it understand what datatype to expect in response
success: function(response) {
var retid = response.data.retid; //here you get on successfull response
},
});
First, read this entire page; it will really help you throughout your career as a developer, it has helped me tremendously: https://stackoverflow.com/help/mcve
Then, lets use the knowledge gained from that page to make an MCVE. Put this on a new page:
$.ajax({
type: 'POST',
url: 'test-call.php',
dataType: 'json',
success: function(response) {
var retid = response.data.retid;
console.log(retid);
},
});
This should print the value of retid to your console. Take a look at your console. Notice any errors, or does the value of retid print as expected?
So why have we taken time to create a new page and put this on it? We are narrowing down our issue, we're trying to find the exact cause of the problem by creating an MCVE. If we don't know what is causing the problem, and if we can't create a very basic example to illustrate the problem, we will have a hard time solving the problem and/or asking for help.
(Note 1, make your code "pretty" when you post it here. Indent it as it should be indented; this makes it easier for others to read. You are asking people to take time out of their day to help you, for free; make it as easy as possible for them to read and understand your code)
(Note 2, here is an example of where I had some very, very complicated MySQL interactions that I had a question about. Rather than post all of the complicated code, I followed the MCVE concept: DRY - how to extract repeated code to...a stored function maybe? and made some fake, very very simplified examples of my problem. Since I did that, I was able to get quick, concise answers from experts, notice the answer I accepted was from one of the top-scored users on all of Stackoverflow)
Related
I'm working on a song site, where you can rate songs, singers etc, and you also have the option to add them to your favourites.
After a while I've noticed when I add/remove song/singer from my favourites, I pretty much repeate the same ajax request multiple times, only with a different feedback message, so I decided to create a separate function of that request, and in other methods I just call this.
For this I set things such as the route of the button, feedback, message etc in the parameter of the favourite function, as you can see below.
The feedback() function is not really important I believe, I just shared if someone would like to know how it looks like, or if they'd actually find it important anyway.
function feedback($feedback_route,$message_route,$alert_class,$message){
$($feedback_route).removeClass("d-none");
$($feedback_route).addClass($alert_class);
$($feedback_route).addClass("animated fadeIn");
$($message_route).html($message);
setTimeout(() => {
$($feedback_route).addClass("animated fadeOut");
}, 2000);
setTimeout(() => {
$($feedback_route).addClass("d-none");
$($feedback_route).removeClass($alert_class);
$($message_route).html("");
}, 2500);
}
function favourite($ajax_route,$post,$button_route,$event,$feedback_route,
$message_route,$success_message,$error_message){
$.ajax({
url: $ajax_route,
type: "post",
data: {
$post: $($button_route).attr("value"),
event:$event
},
success: (data) => {
feedback($feedback_route,$message_route,"alert-success",$success_message);
setTimeout(() => {
$($button_route).replaceWith(data);
}, 2500);
},
error: () => {
feedback($feedback_route,$message_route,"alert-danger",$error_message);
}
});
}
//-------------------------------ADD SONG TO FAVOURITES-----------------------------
$("#song-info-container #song-container").on("click","#add-to-favourites", () => {
favourite(
"ajax/song-favourite.php",
"songID","#song-info-container #song-container #add-to-favourites",
"add","#song-info-container #song-container .feedback",
"#song-info-container #song-container #message",
"Added!","Failed to add!"
);
$("#song-info-container #song-container .feedback").removeClass("animated fadeOut");
});
Here's how the original ajax request looks like:
$("#song-info-container #song-container").on("click","#add-to-favourites", () => {
$.ajax({
url: "ajax/song-favourite.php",
type: "post",
data: {
songID: $("#song-info-container #song-container #add-to-favourites").attr("value"),
event:"add"
},
success: (data) => {
feedback("#song-info-container #song-container .feedback",
"#song-info-container #song-container #message","alert-success","Added!");
setTimeout(() => {
$("#song-info-container #song-container #add-to-favourites").replaceWith(data);
}, 2500);
},
error: () => {
feedback("#song-info-container #song-container .feedback",
"#song-info-container #song-container #message","alert-danger","Failed to add!");
}
});
$("#song-info-container #song-container .feedback").removeClass("animated fadeOut");
});
And now the actual problem: first I thought it actually works, because the feedback appears with the correct message, but after it disappears(see in the setTimeOut function), the following message appears:
Notice: Undefined index: songID in G:\x\htdocs\AniSong\ajax\song-favourite.php on line 9
So the data which is also set in the parameter of the favourite function is not being passed to the other file.
Does someone know why this happens?
Or can I not do an ajax request like this in the first place?
PS: Sorry if the title doesn't make sense, didn't really know how it should be asked.
This doesn't do what you're expecting:
{
$post: $($button_route).attr("value"),
event: $event
}
This won't replace $post with the string value you're passing to the function. This gives the property the literal name $post. Check the network tab of your browser's debugging tools to see what you're actually sending to the server. There is no songID property.
A quick test to validate:
let $foo = 'test';
console.log({$foo: 'baz'});
If you want to dynamically send this information, you'll need to modify your data structure to do that. Similar to how you have a dynamic "event", you'll now need a dynamic "post". Something like:
{
post: $post,
value: $($button_route).attr("value"),
event: $event
}
Then in your server-side code you'd change your logic to examine the post parameter to see what field you're updating, or whatever such logic you're using server-side.
Alternatively, it just occurs to me that you could potentially create a dynamic property name. Consider something like this:
let $post = 'songID';
let data = {
event: 'add'
};
data[$post] = 'test value';
console.log(data);
It's up to you which you think is more complex vs. which is easier for you to support.
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 am currently migrating an already built web application to MVC, and I'm figuring out that I'm too newbie to do some kind of changes. There are some ajax calls that are freaking me out. I'll try to be as clear as possible, but due to my inexperience I'm not sure if I won't let some important information by the way.
The point is in the old application, things go this way:
In the php code:
if ($action_user == 'show_alerts') {
$list = array();
$query = "SELECT alert_type FROM alert_contact WHERE NOT
deleted AND user_email=" . typeFormat($email);
$result = mysqli_query($db, $query) or die('Error in query "'.$query . '": ' . mysqli_error($db));
while ($db_field = mysqli_fetch_assoc($result)) {
$list[] = $db_field['alert_type'];
}
echo json_encode($list);
In the jquery code:
$.ajax({
type: 'POST',
url: 'userpost.php',
data: $('#userForm').serialize(),
cache: false,
dataType: 'json'
Here comes my problem, and since I don't have an userpost.php file anymore, I have to send it to the index.php and call my users component by a get petition, which I don't like, but I coudn't find another way to do it. And, what is even worse, I don't know at all how ajax is getting the variables that it needs. It must be a pretty basic mistake, but I recognize my skills at this point are't so good. That's what I'm doing in my version:
In the php code:
if ($action_user == 'show_alerts') {
$list = ModelUser::getAlertContact($act_email);
echo json_encode($list);//I predict that ajax don't reach this line, but not sure
}
In the jquery code:
$.ajax({
type: 'POST',
url: 'index.php?option=users',
data: $('#userForm').serialize(),
cache: false,
dataType: 'json',
success: function(data) {
alert ('gotcha');
$.each(alertsarray, function(index, value) {
if ($.inArray(value, data) === -1) {
$("#sub" + value).prop("checked", false);
$('#alert' + value).removeClass("list_alert_sub");
}
else {
$("#sub" + value).prop("checked", true);
$('#alert' + value).addClass("list_alert_sub");
}
});
},
error: function(data) {
alert("¡Error (ajax)!");
}
});
Any help would be appreciated, and if there's some more information I've missed, please let me know. Thanks in advance.
UPDATE:
I've been making some progress but don't seem to find a real solution. Now I know that the url has to be the controller, so I'm using 'components/userpost/controller.php' as it, and it reaches the ajax call, cause the success alert is showing up. The problem is the MVC way, because I send ajax to the controller, but since I don't have a reload in the page, all the includes are failing so they are obviously not being loaded, and I'm getting errors like this:
PHP Warning: include(components/userpost/model.php): failed to open
stream: No such file or directory in
/var/www/html/viewer_mvc/components/userpost/controller.php on line 3,
referer: http://localhost/viewer_mvc/index.php
Really hope you guys can show me where am I failing, and if there's a special way to do these thing in MVC.
For the JQuery call it makes a POST request to index.php?option=users with JSON data. The form with the ID userForm is serialized using the Jquery serialize method.
The .serialize() method creates a text string in standard URL-encoded notation. It can act on a jQuery object that has selected individual form controls
$.ajax({
type: 'POST',
url: 'index.php?option=users',
data: $('#userForm').serialize(),
cache: false,
dataType: 'json'
Now for your PHP sample
if ($action_user == 'show_alerts') {
$list = ModelUser::getAlertContact($act_email);
echo json_encode($list);//I predict that ajax don't reach this line, but not sure
}
This code will be looking for variables that probably don't exist anymore if it is a different file i.e. is there an $action_user variable?
To start reimplementing it you will need to add the logic so that it checks the POST variable if your not using the framework code. So if you have a form element with the name 'name' then that will be available in your PHP script POST variable
$_POST['name']
[How to call a PHP function in MVC using AJAX]
$.ajax({
type: 'POST',
url: 'save-user.php',
data: { fname: "manish", email: "manishkp#com", role:"admin"},
success: function(data) {
console.log(data);
if(data == 'error')
{
$('#Register_error').text('Must Be filled...');
$('#Register_error').show();
}
else {
$('#Register_error').hide();
$('#Register_success').text('Successfully submit');
$('#Register_success').show();
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<?php
$fname = $_POST['fname'];
$email = $_POST['email'];
$role = $_POST['role'];
if(!empty($fname) && !empty($email) && !empty($role))
{
#MYSQL CONNECTION QUERY #
echo"success";
}
else{
echo "error";
}
?>
I'm a newbie at programming with AJAX and beginner at PHP programming. I'm not sure why, but when a user clicks an arrow to "Upvote" a post repeatedly and very fast, the PHP login_check decides that the user is no longer logged in. The program works if I click the arrow at a normal speed, but when I rapid fire it gets weird.
PHP code:
<?php
include "db_connect.php";
include "functions.php";
sec_session_start();
I was wondering if this is a definite case of race conditions and what I could do to prevent it--
AJAX code:
$(document).ready(function() {
$("#upvotearrow").click(function() {
setTimeout(function() { }, 500);
$resdiv=$("#upvotedownvote_resultalert");
$content=$("#upvotedownvote_resultalert_content");
$.ajax({
type: "POST",
url: "../secure/process_upvotedownvote.php",
data: { vote: "upvote", poemid: $("#poemidfield").val() },
dataType:"HTML"
})
.done(function(param) {
if (param=="true_upvote") {
$content.html("Upvote registered!");
$resdiv.css("visibility", "visible");
}
else {
$content.html("Invalid request");
$resdiv.css("visibility", "visible");
}
});
});
$("#downvotearrow").click(function() {
setTimeout(function() { }, 500);
$resdiv=$("#upvotedownvote_resultalert");
$content=$("#upvotedownvote_resultalert_content");
$.ajax({
type: "POST", //POST data
url: "../secure/process_upvotedownvote.php", //Secure upvote/downvote PHP file
data: { vote: "downvote", poemid: $("#poemidfield").val() }, //Get type of vote and poem_id in URL
dataType:"HTML" //Set datatype as HTML to send back params to AJAX function
})
.done(function(param) { //Param- variable returned by PHP file
if (param=="true_downvote") {
$content.html("Downvote registered!");
$resdiv.css("visibility", "visible");
}
else {
$content.html("Invalid request");
$resdiv.css("visibility", "visible");
}
});
});
});
The website with a live demo can be viewed here.
TO LOG IN, JUST USE THIS EMAIL: asdf#gmail.com AND THIS PASSWORD: asdf123
Thanks in advance for any advice!
I don't know about the race condition (which is likely but shouldn't mess with the session unless it is getting regenerated every time). Anyway, if I were you, I would disable the upvote/downvote button right after the first click.
So, I am using jquery to make an ajax call to a php script on my server.
For some reason I cannot figure out, however, there is no querystring sent. Using var_dump() on the $_GET object shows that it is an empty string, and Chrome's network activity developer tool indicates no string is sent.
$.ajax({
"url":"../script/content.php",
"settings": {
"dataType":"html",
"type":"GET",
"data":{
"id":$(this).prop('id')
}
}
}).done( function(msg) {
//$('#debug').html(msg);
$('#dialog').html(msg);
$('#dialog').load(function() {
$('#close').click(function() {
$('#over').fadeOut(fadeTime);
});
if ($('#unique') > 0) {
$('#unique').load(function(){
$('#over').fadeIn(fadeTime);
});
}
else {
$('#over').fadeIn(fadeTime);
}
});
});
I had tried the ajax call without the quotes where they weren't necessary before hand, and the result was the same... I just put those in because I thought it might be the problem... though I think that in such notation the quotes don't make a difference unless one of the field values is supposed to be a string.
Is there anything clear in that code which might cause a querystring not to be sent? I guess there is a problem with my syntax... I just can't see it.
The #dialog load callback seems to never be called, either... but I guess that is another question.
Try this
$.ajax({
//The link we are accessing with params
url:'http://example.com/script/content.php'
+ '?id='
+ $(this).prop('id'),
// The type of request.
type: "get",
//The type of data that is getting returned.
dataType: "html",
error: function(){
//something here
},
success: function( strData ){
//something here
}
});