John Beasley
John Beasley

Reputation: 3075

Passing JSON object to PHP script

I am trying to pass a JSON object that looks similar to this:

 {"service": "AAS1", "sizeTypes":[{"id":"20HU", "value":"1.0"},{"id":"40FB","2.5"}]}

Just a note: In the sizeTypes, there are a total of about 58 items in the array.

When the user clicks the submit button, I need to be able to send the object to a PHP script to run an UPDATE query. Here is the javascript that should be sending the JSON to the PHP script:

 $('#addNewSubmit').click(function()
 {
   var payload = {
     name: $('#addservice').val();
     sizeTypes: []
   };

   $('input.size_types[type=text]').each(function(){
     payload.sizeTypes.push({
       id: $(this).attr('id'),
       value: $(this).val()
      });
   });

   $.ajax({
     type: 'POST',
     url: 'api/editService.php',
     data: {service: payload},
     dataType: 'json',
     success: function(msh){
       console.log('success');
     },
     error: function(msg){
       console.log('fail');
     }
   });
 });

Using the above click function, I am trying to send the object over to php script below, which is in api/editService.php:

 <?php
 if(isset($_POST['service']))
 {
   $json = json_decode($_POST['service'], true);

   echo $json["service"]["name"] . "<br />";

   foreach ($json["service"]["sizeTypes"] as $key => $value){
     echo $value["value"] . "<br />";
   }
 }
 else
 {
   echo "Nooooooob";
 }
 ?>

I do not have the UPDATE query in place yet because I am not even sure if I am passing the JSON correctly. In the javascript click function, you see the SUCCESS and ERROR functions. All I am producing is the ERROR function in Chrome's console.

I am not sure where the error lies, in the JavaScript or the PHP.

Why can I only produce the error function in the AJAX post?

Edit

I removed the dataType in the ajax call, and added JSON.stringify to data:

 $.ajax({
   type: 'POST',
   url: 'api/editService.php',
   data: {servce: JSON.stringify(payload)},
   success: function(msg){
     console.log('success');
   },
   error: function(msg){
     console.log('fail'), msg);
   }
 });

In the PHP script, I tried this:

 if(isset($_POST['service'))
 {
   $json = json_decode($_POST['service'], true);

   foreach ($json["service"]["sizeTypes"] as $key => $value){
     $insert = mysqli_query($dbc, "INSERT INTO table (COLUMN, COLUMN, COLUMN) VALUES (".$json["service"] . ", " . "$value["id"] . ", " . $value["value"]")");
   }
 }
 else
 {
   echo "noooooob";
 }

With this update, I am able to get the success message to fire, but that's pretty much it. I cannot get the query to run.

Upvotes: 2

Views: 7736

Answers (4)

mferly
mferly

Reputation: 1656

Example how to handle a JSON response from editService.php. Typically, the editService.php script will be the worker and will handle whatever it is you need done. It will (typically) send a simple response back to the success method (consider updating your $.ajax to use the latest methods, eg. $.done, etc). From there you handle the responses appropriately.

$.ajax({
    method: 'POST',
    url: '/api/editService.php',
    data: { service: payload },
    dataType: 'json'
})
 .done(function(msh) {
    if (msh.success) {
        console.log('success');
    }
    else {
        console.log('failed');
    }
})
 .fail(function(msg) {
    console.log('fail');
});

Example /editService.php and how to work with JSON via $.ajax

<?php
$response = [];
if ( isset($_POST['service']) ) {
    // do your stuff; DO NOT output (echo) anything here, this is simply logic
    // ... do some more stuff

    // if everything has satisfied, send response back
    $response['success'] = true;

    // else, if this logic fails, send that response back
    $response['success'] = false;
}
else {
    // initial condition failed
    $response['success'] = false;
}
echo json_encode($response);

Upvotes: 0

jeroen
jeroen

Reputation: 91734

As you are sending an object in your service key, you probably have a multi-dimensional array in $_POST['service'].

If you want to send a string, you should convert the object to json:

data: {service: JSON.stringify(payload)},

Now you can decode it like you are doing in php.

Also note that you can only send json back from php if you set the dataType to json. Anything other than valid json will have you end up in the error handler.

Upvotes: 1

imvain2
imvain2

Reputation: 15847

without seeing the error, I suspect the error is because ajax is expecting json (dataType: 'json',) but you are echoing html in your php

Upvotes: 2

Adam Pietrasiak
Adam Pietrasiak

Reputation: 13184

Try to change

 error: function(msg){
   console.log('fail');
 }

to

 error: function(msg){
   console.log(msg);
 }

There might be some php error or syntax issue and you should be able to see it there.

Also try to debug your php script step by step by adding something like

echo "still works";die;

on the beginning of php script and moving it down till it'll cause error, then you'll know where the error is.

Also if you're expecting JSON (and you are - dataType: 'json' in js , don't echo any HTML in your php.

Upvotes: 1

Related Questions