Search code examples
phpajaxajaxform

Try to using ajax form instead of form action (solve)


I would like to improve user experience at my website. So I try to change the form action ajax, and I has been try some tutorial but I still getting stuck.

I am using a php forum program/source code call !Discuz and it was from China. Below is my coding now.

In html.

<form method="post" id="jnfarm_pop" action="plugin.php?id=cc&do=shop">
<input type="hidden" name="shopsubmit" value="yes">
<!--first item-->
<input type="checkbox" name="jsid[1]" value="1">
<input type="number" style="width:3em;" name="qty[1]">
<!--second item-->
<input type="checkbox" name="jsid[2]" value="1">
<input type="number" style="width:3em;" name="qty[2]">
...continue 50 item
<button type="submit" class="layui-btn layui-btn-fluid" name="submitbutn">submit</button>
</form>

in PHP, file name plugin.php

<?php
if($_GET['id'] == 'cc'){
  if(submitcheck('shopsubmit')){ //core function in !Discuz 
    for($x=1;$x<=50;$x++){
      if($_GET['jsid'][$x] == '1'){
        $qty[$x] = intval($_GET['qty'][$x]);
        //process....
      }
    }
    showmessage('message here','redirectlink');//this is !Discuz program function and it is fine.
  }
}
?>

The above script is working fine while using form action, and redirect to my output page. If I would like to change to ajax, how do I adjust the below source code?

<script type="text/javascript">
        function login() {
            $.ajax({
                type: "POST",
                dataType: "json",//? is it can use json? since my form data can get as array
                url: "plugin.php?id=cc&do=shop" ,//url
                data: $('#jnfarm_pop').serialize(),
                success: function (result) {
                    console.log(result);
                    if (result.resultCode == 200) {
                        alert("SUCCESS");
                    }
                    ;
                },
                error : function() {
                    alert("ERROR");
                }
            });
        }
</script>
<form method="post" id="jnfarm_pop" action="plugin.php?id=cc&do=shop">
<input type="hidden" name="shopsubmit" value="yes">
<!--first item-->
<input type="checkbox" name="jsid[1]" value="1">
<input type="number" style="width:3em;" name="qty[1]">
<!--second item-->
<input type="checkbox" name="jsid[2]" value="1">
<input type="number" style="width:3em;" name="qty[2]">
...continue 50 item
<button type="submit" class="layui-btn layui-btn-fluid" name="submitbutn" onclick="login()">submit</button>
</form>

And is it have to adjust the plugin.php source code?

Updated, below is work for me, thanks fayis003. html change the <script></script>

$.get('plugin.php?id=cc&do=shop', $('#jnfarm_pop').serialize(), result => {
   //alert('success');
   console.log(result); // check the result in console and if you can see it as a JS object you don't need to parse
   result = JSON.parse(result); // Parse is required if you return the result as plain text otherwise you can omit this step in case you are returning the result as content type json
   alert(result.final);//alert message here
   location.href = result.link;// if you need to get redirected

}).fail(result => {
   alert('fail');
});

PHP

<?php
if($_GET['id'] == 'cc'){
  if(submitcheck('shopsubmit')){ //core function in !Discuz 
    for($x=1;$x<=50;$x++){
      if($_GET['jsid'][$x] == '1'){
        $qty[$x] = intval($_GET['qty'][$x]);
        //process....
      }
    }
    $final = 'message here';
    echo json_encode(['final' => $final]);
  }
}
?>

Solution

  • You can not initiate a direct browser redirect using server-side code on ajax request like you do with synchronous requests. instead, you have to return a URL to which you want to get redirected to and then do something like location.href = result.link in the result callback.

    for ajax request, the simplest option is using as follows

    $.get('plugin.php?id=cc&do=shop', $('#jnfarm_pop').serialize(), result => {
       //alert('success');
       console.log(result); // check the result in console and if you can see it as a JS object you don't need to parse
       result = JSON.parse(result); // Parse is required if you return the result as plain text otherwise you can omit this step in case you are returning the result as content type json
       let final = result.final;
       location.href = result.link;// if you need to get redirected
    
    }).fail(result => {
       alert('fail');
    });
    

    now in the server-side code instead of creating a redirect from PHP return something like

    return json_encode(['link' => 'somlink']);
    

    of just return success message as usual.