Call a PHP function after AJAX - javascript

When a user submits the form on my page I use AJAX to submit the information without refreshing the page. After the user submits the information I want to run a PHP function that I have already written that displays the information. Is this possible or do I need to run another ajax function to update after
$(function () {
$('add').on('submit', function (e) {
$.ajax({
type: 'post',
url: 'submit.php',
data: $('this').serialize(),
success: function () {
alert('form was submitted');
}
});
e.preventDefault();
updateWords(); //PHP FUNCTION
});
});

You will need to run another AJAX call on success of the first one.
JavaScript cannot interact with PHP directly and therefore you can't call a PHP function from the success/complete function of the AJAX call.

in response of this.
I have multiple forms on the page and probably 5 different ajax calls
in which no more then 2 are called at the same time, if json is better
do you have a link to some reading material or additional stack
example similar to this so i can teach myself – user934902
first of all
jquery was made for old browsers to support basic functions that ie6 does not support
the use of jquery is good if you want to have full support on almost all browser
but there are also many bad sides:
it's 81kb code wich is insane (without plugins)
it's very slow compared to native functions.
it's used by ppl who don't know how to write simple javascript.
and much more if we start to talk about the plugins.
now we are in a era where most of the ppl use their mobile devices and modern browsers
which support standard javascript 1.7.Android,ios,safari,internet explorer 10,chrome,opera & firefox support javascript 1.7
http://caniuse.com/
the code below is supported by those browsers.
this is a ajax function written by me it handles post & get
you can read more about that function here
https://stackoverflow.com/a/18309057/2450730
function ajax(a,b,e,d,f,g,c){
c=new XMLHttpRequest;
!f||(c.upload.onprogress=f);
!g||(c.onprogress=g);
c.onload=b;
c.open(e||'get',a);
c.send(d||null)
}
// Params:
// Url,callback,method,formdata or {key:val},uploadFunc,downloadFunc,placeholder
a simple get request would be
ajax('example.php',responseFunction);
and a complex post function would be
ajax('example.php',responseFunction,'post',new FormData(form),uploadFunc,dlFunc);
you need that.
so if you have your form
<form id="myForm">
<input name="name"> Name
<input name="surname"> Surname
<input name="mail"> Email
<input name="file" type="file" multiple> File/Files
</form>
you just have to write a function like that
var form=document.getElementsById('myForm');
form.onsubmit=function(e){
e.preventDefault();
ajax('submit.php',SUCCESS,'post',new FormData(this));
}
and here we come to your question :
create the submit.php file for your needs
<?php
// do whatever you need with the posted info
// copy files to a specific folder
// insert/update/delete the database
// check for errors
// lets say no errors
$err=array();
// load extra info from database to an array called $extrainfo
// load some functions... (you can do what you want here)
// like executing the function you have already written and add that info to
// the $extrainfo.
$extrainfo=array('updated correctly','files copied');
$data=array('post'=>$_POST,'files'=>$_FILES,'info'=>$extrainfo,'errors'=>$err);
echo json_encode($data);
?>
this returns a json encoded array to use later in javascript.
now we need to elaborate this json. in the SUCCESS function
function SUCCESS(){
var data=JSON.parse(this.response);
if(data.errors.length>0){
// you have some errors
}else{
// no errors
// display your response in a proper way.
console.log(data);
}
}
inside this function you just have to display based on the response data.
data contains everything you need.
here is the whole code.
copy and past into a txt file and save it as submit.php.
i have tested only in chrome for now.
<?php
if($_POST){
$err=array();
$extrainfo=array('updated correctly','files copied');
$data=array('post'=>$_POST,'files'=>$_FILES,'info'=>$extrainfo,'errors'=>$err);
echo json_encode($data);
}else{
?><!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>upload</title>
<script>
var form,result;
function ajax(a,b,e,d,f,g,c){
c=new XMLHttpRequest;
!f||(c.upload.onprogress=f);
!g||(c.onprogress=g);
c.onload=b;
c.open(e||'get',a);
c.send(d||null)
}
function SUCCESS(){
console.log(JSON.parse(this.response));
var data=JSON.parse(this.response);
if(data.errors.length>0){
result.textContent='you have some errors:'+data.errors[0];
}else{
result.textContent=JSON.stringify(data, null, '\t');
}
}
window.onload=function(){
form=document.getElementById('myForm');
result=document.getElementById('response');
form.onsubmit=function(e){
e.preventDefault();
ajax('submit.php',SUCCESS,'post',new FormData(this));
}
}
</script>
</head>
<body>
<form id="myForm">
<input name="name"> Name
<input name="surname"> Surname
<input name="mail"> Email
<input name="file[]" type="file" multiple> File/Files
<input type="submit" value="send">
</form>
<pre id="response"></pre>
</body>
</html>
<?php
}
?>

If the function is dependant on the AJAX call to submit.php finishing, then create a new AJAX call. If not, then just append the function to submit.php and call it at the end of the file.

You should use the ajax function that performs the update information to update the page itself at the same time.
Just return usable HTML as the return from the ajax, and use that as the HTML content of the page.
Example: test.php
<script>
function updateName() {
var url = './test.php?inpName=' + $('#inpName').val();
$.get( url, function( data ) {
$( "#frmDivUpdate" ).html( data );
alert( "Call was performed." );
});
}
</script>
<div id="frmDivUpdate">
<form>
Enter your name : <input name="inpName" id="inpName">
<br>
<input type="button" onClick="updateName();" value="Update">
</form>
</div>
<?php
if (isset($_GET))
{
$inpName = $_GET["inpName"];
echo "You updated your val to $inpName";
}
?>

PHP is serverside , javascript is clientside.
you can't call php from client if the page is already loaded.
so the easy way is ajax
in the submit.php add:
echo json_encode($_POST);
or the
PHP function that I have already written
... the information what you need.
and in the success function
success: function () {
// i don't use jquery but the response contains the json string
console.log('the words you wanna update:',JSON.parse(response));
// updateWords(JSON.parse(response));
}
EDIT
you also don't need more than one ajax function
you say you already wrote a script to display the next information to the client.
add that script to the submit.php
and the succes function will give you what you need as response.
i added echo json_encode($_POST); because most of the time as answer/update info you need is that one you just posted.

Related

PHP Undefined POST variables and unable to execute INSERT function [duplicate]

I know there a fair few entries on SO and the web on this however I just can't get to work - any help would be appreciated.
So i have an array in Javascript which I'm trying to pass on to PHP.
I've got a little JS function to first POST it, so:
function sendToPHP() {
$.post("index.php", { "variable": toSearchArray });
}
Then down the page, I have the PHP:
<?php
$myval = $_POST['variable'];
print_r ($myval);
?>
*The prints just there for me to check.
Any ideas - fyi I'm using MAMP so its localhost:8888/index.php. Could this be causing issues in that the URL is not correct?
Thanks.
You have a misunderstanding about how ajax works. Although jquery makes it easy, it is still not automatic. You should just find a tutorial about ajax with jquery, but if you want to just send an array to php and see the output on screen, something like this would work:
index.php
<html>
<head>
<title>Test</title>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
//attach to the button a click event
$('#btn').click(function(){
//get the value from the textbox
var txt=$('#txt').val();
//if txt is blank, alert an error
if(txt == ''){
alert("Enter some text");
} else {
//send txt to the server
//notice the function at the end. this gets called after the data has been sent
$.post('catcher.php', {'text':txt}, function(data){
//now data is an object, so put the message in the div
$('#response').text(data.message);
}, 'json');
}
});
});
</script>
</head>
<body>
<input type="text" id="txt">
<input type="button" id="btn">
<pre id="response" style="overflow:auto;width:800px;height:600px;margin:0 auto;border:1px solid black;"> </pre>
</body>
</html>
catcher.php:
<?php
//if something was posted
if(!empty($_POST)){
//start an output var
$output = array();
//do any processing here.
$output['message'] = "Success!";
//send the output back to the client
echo json_encode($output);
}
It is better to use 2 files, one for the user to load that initiates the ajax call and one page to handle the ajax call. Sending an array works the same, just replace getting the textbox value with sending an array.
Instead of declaring variable toSearchArray as array. consider it an javascript object.
var toSearchArray = {}.
This is what happens when you open your page (index.php)
A GET request is issued to index.php and the content is returned. There are no values in the $_POST array so your print_r() line does nothing.
Javascript is executed that sends a POST request to index.php via AJAX. Note that this is an entirely new request, separate to the original GET. The $_POST array will be populated on this request however the response is discarded.
Hopefully this will illustrate what you can do.
ajax.php
<?php
header("content-type: application/json");
exit(json_encode($_POST));
index.php
<script>
const toSearchArray = ['some', 'array', 'with', 'values'];
$.post('ajax.php', {
variable: toSearchArray
}).done(data => {
console.log(data) // here you will see the result of the ajax.php script
})
</script>
Well I don't think thats the right way to do it when it comes to arrays, see you need to use JSON encode in javascript then JSON decode in php
Refer to this question Pass Javascript Array -> PHP

JavaScript to PHP form, based on user input

I have a simple form on my homepage (index.php), that takes one user input.
<form action="/run.php" method="POST" target="_blank"
<input type="text" name="userinput">
<button type="submit">Run!</button>
</form>
That input is then passed to run.php where the content is displayed and inserted into a MySQL database.
However, I need to run JavaScript functions on that user input, and then input the results (from the JavaScript function) into the database (so passing the value from JavaScript to PHP).
I originally had the JavaScript in the run.php, which worked for calculating and displaying the value, but I was unable to pass the value to PHP to insert into the database.
From what I've read, you can't pass JavaScript values to PHP on the same page, as it requires some sort of POST or GET, so I'm attempting to run the JavaScript functions on the homepage index.php and then use a hidden input field to POST the value to the run.php file.
<input id='hidden_input' type='hidden' name='final-calc' value='random(userinput)' />
Where the function is a JavaScript Promise:
function random(userinput) {
....
.then(function(userinput) { // Function needs to use the userinput from the form
// calculations
return X //(X being any random value)
}
}
The two problems I'm running into is that:
I can only get the userinput value after the user enters a value and submits the form, so I don't believe I can pass that userinput value into the JavaScript function and still POST the returned value?
The JavaScript function is an asynchronous Promise, but apparently, this might not have an effect - so it may not be a problem.
The key here is AJAX. You have to retrieve the userinput using plain JS, make any calculations needed and then send the results to your PHP script. I left a fiddle: https://jsfiddle.net/k5xd54eu/1/
<input type="text" id="userinput" name="userinput"/>
<button onclick="inputhandler();">TEST</button>
<script>
function inputhandler() {
var text = document.getElementById('userinput').value;
alert(text);
/*DRAGONS BE HERE*/
/*THEN*/
/*USE AJAX HERE TO PASS THE RESULTS TO PHP SCRIPT*/
}
</script>
I'm not explaining how to implement the AJAX call to send the results, mainly because it's a matter of taste too. For example you can use plain JS or a library such as jQuery (which is my personal preference, since it's very clean and easy). Take a look here:
http://api.jquery.com/jquery.ajax/
and here:
https://www.w3schools.com/jquery/jquery_ajax_intro.asp
for more information.
EDIT: Since I've mentioned AJAX, it would be more correct to include some code. So this is what I generally use for simple POSTs (it's based on the jQuery library so be careful to include it):
var url = 'ajaxhandler.php';
var stuff = '1234abcd';
$.ajax({
type: "POST",
url: url,
data: {stuff: stuff},
success: function (data) {
/*Do things on successful POST*/
}
});

AJAX - my simple ajax request does not work

I'm currently learning how to use Ajax but i already have a problem :
1 HTML :
<body>
<form>
Nom d'utilisateur : <input type="text" id="username" name="username"/>
<input type="submit" id="submit" />
</form>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script src="script.js"></script>
JS :
$(document).ready(function(){
$("form").submit(function(e){
e.preventDefault();
var don=$('#username').val();
$.ajax({
url:'test.php',
type:'post',
data:don,
success: function(html){
alert(html);
}
});
});
});
PHP :
<?php
if(!empty($_POST['username'])){
$response="yep";
}
else{
$response="nope";
}
echo $response;
?>
As you can see, it is really simple. But it drives me crazy, i didn't understand why i always have the response "nope".
Can you help me ?
Thank you
PHP requires you to submit key=value constructs to properly build $_POST/$_GET with. No key, no value. You haven't provided a key, just a value.
Try
data: {"username":don}
instead. Or have your PHP script read the raw POST data via php://input.
You are just sending a string. You need to send a JSON object:
var don = {"username" : $('#username').val()};
jQuery will turn this into a string and send it (I'm assuming, otherwise you need to JSON.stringify it), and then you'll need to call json_decode on it server-side before you query it.
If you want to continue using your current serverside code, you need to use a GET request and submit to url: "test.php?username="+encodeURIComponent($('#username').val()) and then check the _GET variable on PHP side.

How to set variable to external content?

So I have this code that uses JQuery to output a live calculation from data entered in a text field. It all works fine as seen below:
$(document).on('keyup', '#w_amount', function(){
// alert('pressed')
var totalcost= 11 * $(this).val()
$(".total_cost").html(totalcost);
})
and it's outputted here:
<span class=\"total_cost\" style=\"display: inline; vertical-align: inherit;\">0</span>
Currently the code takes whatever number is entered into the text field and multiplies it by 11. However what I want it to do is multiply it by the number located at the following url: https://www.eobot.com/api.aspx?coin=DOGE
There is just a number at that url nothing else i.e. 0.00014253
I'd appreciate any help you can give! Received a great response last time.
Thanks!
Because of Cross-origin policy, you can't make an ajax request to it. Instead I would recommend using curl or something on your server and then either input that value into the page at load time, or make an ajax request to your server which would then make the request to that link.
Edit: as suggested by #Sukima: the data parameter renamed to url_figure to avoid declaring unnecessary variable.
Assuming that your jQuery script, HTML files are both hosted on the same server that has the figure (eobot.com) then here is how it could be done.
$(document).on('keyup', '#w_amount', function(){
// alert('pressed')
$.get( "https://www.eobot.com/api.aspx?coin=DOGE", function( url_figure) {
var totalcost= url_figure * $(this).val()
$(".total_cost").html(totalcost);
});
});
Well, I don't like to leave you at an "it's not possible" answer so here you go:
Name your file test.php and use it on a live server or on localhost
<?php
if( isset($_GET["getCoinValue"]) ){
$val = #file_get_contents("https://www.eobot.com/api.aspx?coin=DOGE");
exit ($val ? "$val" : "Could not retrieve data");
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>GET DOGE</title>
<script src="//code.jquery.com/jquery-2.1.1.min.js"></script>
</head>
<body>
W <input id="w_amount" type="text"><br>
* <input class="doge_value" type="text" readonly><br>
= <input class="total_cost" type="text" readonly>
</body>
<script>
$(function(){
var $dogeValue = $(".doge_value");
var $totalCost = $(".total_cost");
$("#w_amount").on('keyup', function(){
var thisValue = parseInt(this.value, 10);
$.ajax({
data : {"getCoinValue":true} ,
success : function( resp ){
$dogeValue.val( resp );
$totalCost.val( thisValue * resp );
},
error : function(x, e){ console.log(x, e); }
});
});
});
</script>
</html>
The trick is to fool AJAX that the result is on our server,
achieved by pulling the content from the external site using PHP and file_get_contents
On "input" AJAX contacts the same .php file using GET (jQ's AJAX defauly type).
PHP gets the content from the external URI to our server, and exits with a String response.
AJAX serves the response back from our server (without COP issues)
The result is than multiplied by the entered value.

JS/jQuery passing array/variable/data to PHP in same page?

Im hoping you can point me in the right direction.
I have a php page, that includes some HTML markup and some JS/jQuery routines to build an array of 'user choices' based on the 'user input' (checkboxes..etc).
my question is, how can I pass off this (multidimensional) array to PHP, that is in the same page? (ultimately I want to save this data/array to my PHP session)
While looking around, I read about using another (external) .php script to do,, which is NOT what Im after, I'm hoping to do this to the SAME PAGE I'm in... WITHOUT A REFRESH.
will $.post() do this for me? without a page refresh (if we suppress the event or whatever)...
and -not- using an external .php script?
I understand PHP runs/executes FIRST... then everything else..
I'm not really trying to get PHP to do anything with the data being sent from JS/AJAX.. outside of save it to the SESSION array..
Ajax seems like it will be needed?
To summarize:
1.) PHP and JS are in/on same page (file)
2.) No page refresh
3.) No external PHP script to do 'anything'.
4.) Trying to get (multidimensional) array to PHP session in same page.
5.) I am trying to 'update' the PHP SESSION array each time a user 'clicks' on a checkbox.
I have read a little on using AJAX to post to the same page with the URL var left empty/blank?
edit:
to show the data, I want to pass...heres a snippet of the code.
its an array of objects.. where 1 of the poperties of each object is another array
example:
var somePicks = [];
somePicks.push({casename:caseName, fullname:fullName, trialdate:trialDate, citystate:cityState, plaintiff:plaintiff, itemsordered:itemsOrdered=[{name:itemOrdered, price:itemPrice}]});
when from all the checkboxes.. I update the 'sub-array' (push or splice..etc)
somePicks[i].itemsordered.push({name:itemOrdered, price:itemPrice});
'this' is the array/data I want to get into my PHP session from JS using whatever I can AJAX most likely.
You can sort of do that, but in essence it won't be any different than using an external PHP file. The PHP code gets executed on the server before ever being sent to the browser. You won't be able to update the PHP SESSION array without reconnecting with the server.
If you really want to use post to call the current page (I don't think you can just leave the url blank, but you can provide the current file name), you can just have the PHP handler code at the top of the page. However, this would be the exact same as just putting that handler code in an external file and calling it.
Either way, the page will not refresh and will look exactly the same to the user.
You can use $.ajax function with $(#formid).serializearray (). And use url as ur form action in $.ajax function.
I hope it will work for you
<form id="formId" action="post.php" methor="post">
<input type="checkbox" name="test1" value="testvalue1">TestValue1
<input type="checkbox" name="test2" value="testvalue2">TestValue2
<input type="button" id="buttonSubmit" value="click here" />
</form>
<script>
$("document").ready(function ()
{
$("#buttonSubmit").click(function () }
{
var serializedata=$("#formId").serializeArray();
$.ajax(
{
type:"post",
url:$("#formId").attr("action"),
data:{"data":serializedata},
success:function()
{
alert("yes");
}
});
});
});
</script>
<?php
if(isset($_POST))
{
session_start();
$_SESSION["data"]=$_POST["data"];
}
?>
I suggest to use the .post method of Jquery, to call a PHP file, sending the array and processing in the PHP called.
Can find the jquery documentation about .post() here: http://api.jquery.com/jquery.post/
Edited:
I used this case some time ago:
document.getElementById("promotion_heart_big").onclick = function(e){
$.post("' . URL_SITE . 'admin/querys/front.make_love.php",
{
id_element: ' . $business["promotion"]["id"] . ',
type: \'promotion\',
value: $("#field_heart").val()
},
function(data) {
if (data.result) {
//some long code....
}
}
},
"json"
);
from some preliminary testing..
this does NOT seem to be working, (will do more test tomorrow)
$.ajax({
type : 'POST',
//url : 'sessionSetter.php',
data: {
userPicks : userPicks,
},
success : function(data){
//console.log(data);
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
});
It was mentioned that posting to external .php script -or- posting the same page would produce the same results..
no page refresh
$_SESSION would update for future pages
Does anyone have an y example for that?

Categories

Resources