Announcement

Collapse
No announcement yet.

Need help with json AJAX call

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

    Need help with json AJAX call

    Hello forum:
    Hope someone can help me with this:
    I am attempting to create my first json AJAX function.
    I am attempting a json AJAX call to a PHP program but the PHP program is not receiving the data I am attempting to pass.
    Here is the json AJAX function:

    <script>
    function parties() {
    var someJSON = '[{"name":"Jonathan Suh","gender":"male"},{"name":"William Philbin","gender":"male"},{"name":"Allison McKinnery","gender":"female"}]';
    $.ajax ({
    type: "POST",
    url: "redirect.php",
    data: someJSON,
    cache: false,
    success: function(){
    alert("AOK");
    }

    } );
    }
    </script>
    Here is my PHP redirect,php program:
    <?php
    $someArray = json_decode($_POST['someJSON'], false);
    print_r($someArray);
    foreach ($someArray as $key => $value) {
    $name = $value["name"];
    $gender = $value["gender"];
    echo $name . " " . $gender . "<br>";
    }
    exit();
    ?>

    Program redirect,php executes but no data is being received by the $POST in it.
    (the print_r function displays nothing),
    The AJAX success function shows AOK.

    Must be an error in my AJAX call but I can't find it.

    Hope someone can help!
    Larry
    Larry
    Luce Kanun Web Design
    www.facebook.com/wajake41
    www.plus.google.com/116415026668025242914/posts?hl=en



    #2
    Originally posted by wajake41 View Post
    Hello forum:
    Hope someone can help me with this:
    I am attempting to create my first json AJAX function.
    I am attempting a json AJAX call to a PHP program but the PHP program is not receiving the data I am attempting to pass.
    Here is the json AJAX function:

    <script>
    function parties() {
    var someJSON = '[{"name":"Jonathan Suh","gender":"male"},{"name":"William Philbin","gender":"male"},{"name":"Allison McKinnery","gender":"female"}]';
    $.ajax ({
    type: "POST",
    url: "redirect.php",
    data: someJSON,
    cache: false,
    success: function(){
    alert("AOK");
    }

    } );
    }
    </script>
    Here is my PHP redirect,php program:
    <?php
    $someArray = json_decode($_POST['someJSON'], false);
    print_r($someArray);
    foreach ($someArray as $key => $value) {
    $name = $value["name"];
    $gender = $value["gender"];
    echo $name . " " . $gender . "<br>";
    }
    exit();
    ?>

    Program redirect,php executes but no data is being received by the $POST in it.
    (the print_r function displays nothing),
    The AJAX success function shows AOK.

    Must be an error in my AJAX call but I can't find it.

    Hope someone can help!
    Larry
    Pass the data variable as so

    Code:
        data: {
            someJSON: someJSON
        }

    Comment


      #3
      Hello new_user:
      Thanks for your reply.
      I've tried what you have suggested but still am having no success.
      Will work on it later today again.
      I think there is a way in PHP to dump the data received but can't remember how right now. I'd like to see what the redirect program is receiving.
      That would probably help with this.
      Thanks,
      Larry.
      Last edited by wajake41; 07-10-18, 07:51 AM.
      Larry
      Luce Kanun Web Design
      www.facebook.com/wajake41
      www.plus.google.com/116415026668025242914/posts?hl=en


      Comment


        #4
        You should try using some echo statements in your PHP to make sure that your script is indeed executing. I'd start off by commenting everything out and putting an echo 'hello'; at the top just to see if you get a response.

        You might also want to change your success function to something like

        Code:
        function(res) {
            console.log(res);
        }
        and look at what your PHP is outputting. Right now you shouldn't expect to see anything as you're not actually doing anything with the response. Your AJAX call is doing the following

        Execute PHP and returning a print_r and 3 echos as a text string, which is then passed as a variable to your success function as that success function's parameter. That's why the above success function has the res parameter - all your print_r's and echo's would be there, which we can look at in the console.

        Logging the response to the console can especially be helpful because it will also show you any errors that the php file is spitting out. In this case, you would have received a fatal error about incorrectly treating a stdClass Object as an array - when you pass false as the second parameter of json_decode, anything that acts like an object in JavaScript is going to be created as a stdClass Object in PHP rather than an associative array. Which means you can fix this error two ways:

        1) Leave it as it is, which will treat objects as a stdClass Object

        This means you'd need to change your PHP code to

        Code:
        $name = $value->name;
        $gender = $value->gender;
        As stdClass Object properties are accessed via the '->' notation, or

        2) Change your json_decode second parameter to true, which would make your code work as expected.

        Comment


          #5
          Hello new_user:
          Tried for another hour or so to get this to work. With your change I started getting a parse error on character 3 of my json string.
          This same json string works OK with the javascript AJAX call that I wanted to replace.
          Gave up and went back to my proven JS AJAX call.

          Thanks for your assistance anyway!!

          Cheers, Larry

          Almost time for FIFA soccer, gotta go.
          Larry
          Luce Kanun Web Design
          www.facebook.com/wajake41
          www.plus.google.com/116415026668025242914/posts?hl=en


          Comment


            #6
            Code:
            var someJSON = '[{"name":"Jonathan Suh","gender":"male"},{"name":"William Philbin","gender":"male"},{"name":"Allison McKinnery","gender":"female"}]';
            Try removing the single quotes, my guess is you are creating a string literal instead on an object array.


            http://www.alphabetsigns.com/

            Comment


              #7
              Hello Alphabet (AKA Google)
              No solution yet. Tried your change to an object but still getting a parse error.
              Here's the puzzle:
              Using the same exact json string:
              var data = '[{"name":"Jonathan Suh","gender":"male"},{"name":"William Philbin","gender":"male"},{"name":"Allison McKinnery","gender":"female"}]';
              (this is my PHP read of this json string: $data = json_decode($_POST['data'],true);)
              this call fails with a parse error:



              $.ajax( {
              url: "redirect.php",
              type: "POST",
              data: {data:data},
              dataType: "json",
              contentType: "application/json",
              success: function(result) {
              console.log("Response " + JSON.stringify(result));
              },
              error : function(request, textStatus, errorThrown) {
              alert('textStatus ' + textStatus);
              alert('errorThrown ' + errorThrown);
              }
              });

              but this one doesn't

              function party_ajax(data) {
              var xmlhttp;
              if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
              xmlhttp=new XMLHttpRequest();
              } else { // code for IE6, IE5
              xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
              }

              xmlhttp.onreadystatechange=function() {
              if (xmlhttp.readyState==4 ) {
              if(xmlhttp.status==200) {
              party_resp(xmlhttp.responseText);
              } else {
              alert("An error has occurred: " + xmlhttp.responseText);
              }
              }
              }

              xmlhttp.open("POST","redirect.php",false);
              xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
              xmlhttp.setRequestHeader("Cache-Control", "private, no-cache, no-store, must-revalidate");
              xmlhttp.setRequestHeader("X-Requested-With", "XMLHttpRequest");
              xmlhttp.send(data);
              }

              In both cases the same exact json string is used.
              After this much effort I've lost interest in making the json call work.
              Will stick with the JS AJAX call
              Thanks for your suggestions,
              Larryj
              Last edited by wajake41; 07-10-18, 01:23 PM.
              Larry
              Luce Kanun Web Design
              www.facebook.com/wajake41
              www.plus.google.com/116415026668025242914/posts?hl=en


              Comment


                #8
                The first script is jquery the second script is pure JS.

                1. Do you have the jquery library installed before the ajax call?
                2. The header types and encoding are slightly different, try working with that.

                Code:
                $.ajax( {
                url: "redirect.php",
                type: "POST",
                headers: {
                    "Cache-Control", "private, no-cache, no-store, must-revalidate"
                },
                data: JSON.stringify({ someJSON : someJSON }),
                dataType: "json",
                contentType: "application/json; charset=utf-8",
                success: function(result) {
                console.log("Response " + JSON.stringify(result));
                },
                error : function(request, textStatus, errorThrown) {
                alert('textStatus ' + textStatus);
                alert('errorThrown ' + errorThrown);
                }
                });
                http://www.alphabetsigns.com/

                Comment


                  #9
                  Hello Google:
                  Bingo? I do not have the jquery library installed.
                  Where can I get that?
                  Larry
                  Larry
                  Luce Kanun Web Design
                  www.facebook.com/wajake41
                  www.plus.google.com/116415026668025242914/posts?hl=en


                  Comment


                    #10
                    Code:
                    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
                    $.ajax mostly works from its default settings but you may have to configure some header and encodings.

                    Here's a link:

                    http://api.jquery.com/jquery.ajax/
                    http://www.alphabetsigns.com/

                    Comment


                      #11
                      Hello Alphabet:
                      Still getting parse error.
                      Too frustrated with the jquery approach to attempt to solve this.
                      I will stick with my JS AJAX usage which has worked for me consistently with out the issues encountered with trying to make the jquery AJAX work
                      .
                      I do have a remaining question though.
                      Can more than one json string be passed via the jquery AJAX request? The JS AJAX I've been using allows multiple data strings to be used. I wouldn't want the ability to be lost with jquery.
                      ..
                      Larry
                      Luce Kanun Web Design
                      www.facebook.com/wajake41
                      www.plus.google.com/116415026668025242914/posts?hl=en


                      Comment


                        #12
                        Yes, you can pass multiple data strings with jquery ajax.

                        JSON is an acronym for JavaScript Object Notation - so all JSON are objects signified with the curly braces:

                        Code:
                         { 
                        
                        }

                        Within the object you can pass a string signified with quotes:

                        Code:
                        {
                        
                            "name" : "value"
                        
                        }
                        or an array of strings signified with braces:

                        Code:
                        {
                        
                            [
                                "name1" ; "value1",
                                "name2 : "value2"
                            ]
                        
                        }
                        I hope this helps and sorry you couldn't get JQ to work.





                        http://www.alphabetsigns.com/

                        Comment


                          #13
                          I also need help with AJAX call

                          I need to make ajax call with POST method to my MivaScript Compiled app.

                          I have no problem doing it with GET method but can not do the same with POST method, it rise a server error, even before to reach my miva app.

                          I tried calling a php file with the AJAX call with POST method, and no problem.

                          The problem is that I can not call Miva Compiled file with AJAX with POST method.

                          Any help will be very appreciated

                          Thanks
                          Last edited by Rick Wilson; 07-16-18, 12:37 PM.

                          Comment


                            #14
                            Hi Ezequiel,

                            It could be anything but my first thought is are the urls on the same domain?

                            To help debug the problem look at Dev Tools check the Network tab > Filter XHR > Select the AJAX request > View Headers

                            The short answer is to contact the module developer as the app may have been built to provide GET requests and not POST requests.

                            GET and POST requests are handled differently over the network protocol. A GET request is designed to read from a database and GET you the information. A POST request allow a user to create, read, update or delete information from a database (CRUD). For example, a list of what is in you basket is a GET request. Updating the quantities of what is in your basket is a POST request.

                            So if the GET request is working with the miva app why do you need to change it to a POST request?




                            http://www.alphabetsigns.com/

                            Comment


                              #15
                              Thank you Alphabet. The problem was in fact the urls, but your explanation was very helpfull.

                              Best regards

                              Ezequiel
                              Last edited by Rick Wilson; 07-20-18, 10:02 AM.

                              Comment

                              Working...
                              X