Run a php function using jQuery - javascript

I've got this php function located in the base /home/index.php
function addEmail() {
$email = htmlentities($_POST['email']);
if (wp_create_user($email, '7777777', $email)) echo 'OK';
die();
}
I've also got this jQuery function located in /home/js/assets.js. The function checks to see if the email is valid and if so, should run the php function above.
$('#submit_btn').click(function () {
var entered = $('#ms_id-2 > input#input_fld').val();
if (isValidEmailAddress(entered) == false) {
alert('Sorry, the email you entered is invalid. Please try again.');
//console.log('No Validation!');
} else {
alert('Thank you. Your email address has been added to the list.');
}
});
So basically, if the email is valid, I need the code to execute that function in index.php. What's the quickest way to do this?

Create a PHP resource which invokes the desired logic. Something as simple as this might do the trick depending on what you want it to do:
<?php
require('index.php');
addEmail();
?>
Then make an AJAX request to that resource:
$.post('theNewPage.php', { 'email' : entered }, function (response) {
// handle the response in some way
});
The point is that JavaScript and PHP can't execute each other's code. One is client-side, one is server-side. They run at different times in different environments. And they communicate by way of HTTP requests in this case.
So if you have code server-side that you want to execute, then you create a page which executes it and you make an HTTP request (in this case an AJAX request) to that page to execute it. The response in the callback function in the JavaScript code will contain the result of that page (which in this case appears to be an echo of 'OK'). You'd examine that response and perform whatever action you intend to perform on the page.

Related

Why does Stripe's handleCardPayment not run in my Javascript function?

I am trying to use Stripes handleCardPayment to process a charge following a payment intent. I can't get the handleCardPayment function to run inside another Javascript function.
I have tried to debug my code step by step. The Javascript function runs and will print out an alert to the window.
The Javascript variables I set at the top of the function also get set.
The handleCardPayment() function however does not seem to run?
I have attempted a try/catch to see if I can catch the error coming from the request but nothing is logged.
I am a little stumped as to where the issue is with this? although I suspect it might be something basic that I am missing on calling the stripe function correctly.
function completePayment() {
// Assign client secret from PHP session variable
var clientSecret = "<?php echo $_SESSION['c_secret'] ?>";
try {
stripe.handleCardPayment(
clientSecret, cardElement, {
source_data: {
owner: {email: "<?php echo $_SESSION['m_usr_email'] ?>"}
}
}
).then(function(result) {
if (result.error) {
alert("Error in payment");
} else {
alert("Success in payment");
}
});
}
catch(error) {
console.log(error.message);
}
}
My payment intent is created on a separate PHP page. This works correctly and a payment intent is created in stripe with an associated client secret.
How the app currently functions:
User presses 'Subscribe' button.
Ajax request runs and POSTS to a separate PHP file
PHP file creates the payment intent and saves the client secret in a PHP SESSION variable
Ajax 'Complete function()' then calls 'completePayment();'
Javascript function 'completePayment();' is located just before the closing tag at the bottom of the page.
Debugging 'completePayment()' shows that the function does execute following the Ajax 'Complete function()' call.
stripe.HandleCardPayment fails to do anything.
cardElement is a global Javascript variable set when the card element is created (this is created on initial page load).
I have debugged both PHP SESSION variables and confirm that they have both been set with the correct information prior to using them in the handleCardPayment function.
Any suggestions on what I am doing wrong here?
I had same problem. It looks like the function it does not execute becouse the console logs does not appear but after searching I saw that I missing $intent->client_secret, before that, the js console not show me anything and I had to call only the function stripe.handleCardPayment without any code extra then the cosole show me $intent->client_secret It was undefined.
I don't speak english very well I hope that It will serve somebody

Calling a JS function via PHP

this is my JS:
function showErrorMsg() {
modal.style.display = "block";
}
I want to call that function via php:
if(empty($from) || empty($first_name) || empty($last_name) || empty($_POST['message'])) {
// CALL showErrorMsg();
}
The PHP line is called whenever I click a button in a mail-form, and it checks if any of the fields are empty.
I tried this:
if(empty($from) || empty($first_name) || empty($last_name) || empty($_POST['message'])) {
echo "<script type='text/javascript'>showErrorMsg();</script>"
} else {
mail($to,$subject,$message,$headers);
mail($from,$subject2,$message2,$headers2); // sends a copy of the message to the sender
echo "Mail Sent. Thank you " . $first_name . ", we will contact you shortly.";
}
But that gave me an HTTP 500 error..
The JS is in its own file called modal.js.
NOTE: The JS is basically just a example. There's alot more confusing stuff in it, so a JS function is needed. Just wanted to clarify this before someone came and gave me tips on how PHP can change style properties. ;)
As #hassan linked above in his comment,
What is the difference between client-side and server-side programming?
The problem here is a misunderstanding between a script that is executed server-side vs client-side. Javascript (except NodeJS) is a client-side language. This means it doesn't get executed by the server, and cannot run server code. It is executed by the browser. In other words, all of your Javascript runs immediately AFTER your PHP script(s) complete.
This means that you need to output the Javascript in a way that uses a click listener to invoke an AJAX request to your PHP (server) by sending an HTTP request to one of your other PHP files.

undefined result javascript

I have a simple javascript code, that validate when you write a order number and generates tags with javascript(with bootstrap-tagsinput js):
var order = $('#order_number').val();
if ($.inArray(order, $('#input_order_tags').val()) >= 0) {
$('#input_order_tags').tagsinput('add', order);
return;
}
var params = {
email: email,
order_code: order
}
AjaxServices.validateOrderNumberByEmail(params, function(error, result) {
if (error)
alert(error);
else
$('#input_order_tags').tagsinput('add', result.order);
});
This works fine but, every time trigger the error message when send a order number:
Console chrome debug:
How I can avoid the error of alert?
This is not a javascript issue. Server-side in you application you use order_code in one of the calls which returns the error message you see in the ajax call. Debug the offending call server-side, see which call returns that error and adjust your code so it works properly.
There might be two possibilities
client side issue ( javascript error) if so, its because the field order_number is disabled field.
as mentioned in this link
undefined index on javascript dynamic variables when passing to php form
If so, remove that disabled and use read-only and check if it works, without any error.
Server side issue( ajax call) if so, server side code which performs on call of that ajax call is causing that issue.

How to use send responses back to ajax and process each response separately

On Page1:
An AJAX script is processed loading Page2
On Page2:
A mysqli Database query will run, if the database query is successful, I want to send a success response back to AJAX query and reload the page. If the database query fails, I want to send a fail response back to AJAX query and redirect to fail page.
Is this possible? How would I write this? I'm new to AJAX and have reviewed some AJAX scripts and also read documentation, but I learn best by experimenting with code to find solutions that work for me. I have played with a few ajax scripts but can't get any of them to work correctly and can't find one that does anything near what I need. Seems like it would be a fairly easy ajax script, so I was hoping someone could help me with it.
Here's a possible jQuery solution. Let me know if you want pure JavaScript.
index.html
<input type="text" id="input" />
<button type="button">Submit!</button>
scripts.js
$('button').on('click',function() {
var val = $('#input').val();
sendQuery(val);
});
function sendQuery(x) {
var val = x;
$('body').load('query.php?input=' + val);
}
query.php
$mysqli = new mysqli('localhost','root','password','db');
$val = $_GET['input'];
$query = <<<Q
SELECT
*
FROM
table
WHERE
column = ?
Q;
$stmt = $mysqli->stmt_init();
if($stmt->prepare($query)) {
$stmt->bind_param("i",$val);
$stmt->execute();
while($stmt->fetch()) {
#if the query is successful
echo '<script>
$(function() {
location.reload();
});
</script>';
}
} else {
echo '<script>
$(function() {
window.location.href = "http://www.yoursite.com/errorpage.html";
});
</script>';
}
$mysqli->close();
The only thing I'm uncertain about is why you want to send a response back with AJAX, and then move to a completely new page. To me that kind of seems like that negates the reason you're wanting to use AJAX in the first place. Any thoughts?
What the above does is use jQuery to load XMLHTTPRequest.responseText into the body (the reponseText is the scripts that are echoed by your php doc). In this case, in the case of success from the db, it echoes a script that reloads the page. In the case of a failure, it echoes a script that moves the user to an error page.

How to assig a PHP variable a value inside a JavaScript block?

if ($page_title->exists()) {
//the rest of the code is in php.here i insert a javascript for the confirm box.
echo'<script type= "text/javascript" >
var b=confirm("This page already exists.would you want to edit");
if(b == true)
//here i want to assign a php variable , say for eg. $a to 1 so that i can use that value of $a in an if clause outside this javascript code.
</script>';
}
if($a==1)
..some code..
How do I do it?
The PHP code is executed on the server side and is all done at the point where your javascript is executed on the client side.
To communicate the value from the client to the server you typically either use AJAX (tutorial on how to do it here: http://www.w3schools.com/ajax/ajax_httprequest.asp) or store the value in a form and submit it together with data you are going to send down later anyway.
Good luck
Javascript runs on the client (browser) and PHP on your server. So you have to transport the variable to the server.
Most easy way to do this is to use the URL to send this information, for example: http://example.com/myscript.php?a=1. Then you can grab a using $_REQUEST['a'] and use it.
A more sophisticated (and complex) method is to use AJAX to send the variable to your PHP script, so it can return some data which you can use to modify your page.
What you need depends on your application, so you should provide some more details if you do not know what method is best to you in your situation.
you can send the result back to php using an ajax call, e.g.:
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-ui.min.js"></script>
<script type="text/javascript">
x = confirm('Page exists, would you like to edit it?)
$.post('script.php', {x: x}, function(data) {
if (data == '1') {
alert('ok');
} else {
alert('not ok');
}
});
</script>

Categories

Resources