1

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
        });
      });
user934902
  • 1,184
  • 3
  • 15
  • 33
  • Then you should do another ajax call to this php function – krackmoe Dec 09 '13 at 15:34
  • Another AJAX call maybe? Also you can add processing of this function in previous AJAX call. If you are not doing something after first AJAX call response which matters. – sulmanpucit Dec 09 '13 at 15:34
  • 2
    Just run the php function from your `submit.php` script and return the data to the `success` function. That way you can do everything in one request. Unless you want the two to run simultaneously of course... – jeroen Dec 09 '13 at 15:42
  • my answer is based on the fact that when you update something in the database you want to get a succes response and the new values.my code does both.no need for multiple ajax calls. json_decode is just to get the response in a javascript readable array. – cocco Dec 09 '13 at 16:22
  • @cocco, as I've said several times. Your code doesn't stop multiple ajax calls being needed. – Ryan Dec 09 '13 at 16:24
  • sure stops it if you include the response function in the submit.php.and he calls updatewords(response) inside the success function. – cocco Dec 09 '13 at 16:26
  • i added you an example using json (but as i don't use jquery i used my own ajax function.) hope you understand what i meant in my first answer. – cocco Dec 09 '13 at 17:39

5 Answers5

3

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.

Ryan
  • 3,552
  • 1
  • 22
  • 39
  • thats what i thought, just was curious to see if this was possible, thanks – user934902 Dec 09 '13 at 15:34
  • you don't need to execute another ajax call if you add the code you have already written inside the submit.php – cocco Dec 09 '13 at 15:52
  • to many ajax calls are worst than adding the php addwords function to the submit response. ajax is 2 ways . – cocco Dec 09 '13 at 15:54
  • Thanks for the downvote, however - you don't know that it's possible for the code to be removed from the file the AJAX call is in, and into submit.php. – Ryan Dec 09 '13 at 15:59
  • if he write the code it's possible with if's and includes. anyway the answer you downvoted answers both. you execute the updateWords inside the success function.and even if he gets the response with the correct information he needs to execute another function to display that information..... – cocco Dec 09 '13 at 16:01
  • You still make no sense to me. Going on the original post, I would of presumed if he could of had the PHP function in submit.php - he would not have this issue. Therefore I provided the solution that would solve his problem without changing the structure of his code. I downvoted one other post, which was yours. Because it originally didn't answer the post and was almost off-topic, not that it should make a difference to my answer and prompt you to downvote mine as a 'revenge' act. – Ryan Dec 09 '13 at 16:05
  • I just restructured the PHP function as a seperate AJAX function and called it after the submit and it works fine. Cocco as for your answer, Im not familiar with json so I dont know if this is a better answer or not – user934902 Dec 09 '13 at 16:07
  • its not a revenge... multiple ajax calls are a bad approach for such a simple thing.At the other side if your programming it's obvious when reading @user934902 function that there are some "errors" inside the function. if you want to execute the updatewords after the ajax call you need to put it inside the success function.and that last function is made to get a response. in his case the php addwords information. so pls.... – cocco Dec 09 '13 at 16:08
  • 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 Dec 09 '13 at 16:09
  • Your answer uses multiple ajax calls, that's what your whole answer was based on. You're a confusing person. @user934902 JSON is an array format used in JavaScript, you can use `json_encode` and `json_decode` in PHP to help convert PHP arrays to or from a JavaScript compatible array. Again, not sure what relevance that had to your question! – Ryan Dec 09 '13 at 16:10
  • @user934902 reading about JSON would add to your knowledge, however I presume you already have the response from your PHP script that you need and therefore it probably wouldn't help you in this case. – Ryan Dec 09 '13 at 16:12
  • json is a string that contains a javascript array .. it's very usefull for stuff you do.having more ajax calls at the same time is not a good idea. – cocco Dec 09 '13 at 16:13
  • @Stanyer even if my answer has multiple ajax calls they are sequentially and not at the same time. – cocco Dec 09 '13 at 16:15
  • @cocco I'm not going to carry this on, but I just want to say I'm not sure you're on the same wavelength... Your answer is doing exactly what mine is, but if anything it's slightly less efficient, as you are calling another function which will then do the AJAX request. Therefore I don't see the disadvantages of mine what so ever. I don't fully believe you know what you are talking about - but I'm just going to leave you to it... – Ryan Dec 09 '13 at 16:21
  • you prolly don't understand my answer. the final one as also the first one. all of the text & code i wrote simplifies and fastens the questioner's code. you downvoted me.again ajax is 2 ways you post something and you get a response. the php script should include the response function . if not the code is written bad. – cocco Dec 09 '13 at 16:24
3

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:

  1. it's 81kb code wich is insane (without plugins)
  2. it's very slow compared to native functions.
  3. it's used by ppl who don't know how to write simple javascript.
  4. 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
}
?>
Community
  • 1
  • 1
cocco
  • 16,442
  • 7
  • 62
  • 77
0

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.

cocco
  • 16,442
  • 7
  • 62
  • 77
  • How is this going to accomplish what the OP wanted to do? – Ryan Dec 09 '13 at 15:40
  • Because this doesn't explain why/how to call a PHP function within a JavaScript function, or more-so why it isn't possible. – Ryan Dec 09 '13 at 15:42
  • That was understood initially, the question was asking whether it was possible to call a PHP function within a JS function. – Ryan Dec 09 '13 at 15:44
  • yeah with ajax you can call another php script . inside javascript there is no php as it's clientside – cocco Dec 09 '13 at 15:45
  • Yes I know - but if you read his question - you didn't answer it. – Ryan Dec 09 '13 at 15:45
  • read it again pls ... the point is you don't need more than one ajax call. – cocco Dec 09 '13 at 15:50
  • If the point is that you don't need more than one ajax call, why does your code indicate that you call a function which performs a second ajax call? – Ryan Dec 09 '13 at 15:55
0

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.

Xarus
  • 6,589
  • 4
  • 15
  • 22
0

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";
  }
  ?>
bmccall1
  • 79
  • 1
  • 1
  • 7