最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Passing JSON object to PHP script - Stack Overflow

programmeradmin2浏览0评论

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.

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.

Share Improve this question edited Feb 22, 2019 at 13:28 halfer 20.4k19 gold badges109 silver badges202 bronze badges asked Apr 12, 2016 at 13:38 John BeasleyJohn Beasley 3,09511 gold badges53 silver badges103 bronze badges 8
  • 3 You might want to log msg instead of 'fail'. – Gerald Schneider Commented Apr 12, 2016 at 13:39
  • 1 I.e.: console.log('fail:', msg); – MarcoS Commented Apr 12, 2016 at 13:40
  • 1 And there is no reason to use json_decode() in your PHP, the $_POST variable will not contain json. – Gerald Schneider Commented Apr 12, 2016 at 13:41
  • 1 I posted an answer, the error might be that you are echoing html but ajax is expecting json (dataType: 'json') – imvain2 Commented Apr 12, 2016 at 13:42
  • 1 @HoodCoderMan You're getting error may be because of this line. echo $json["service"]["name"]. You don't have any name key in the given example array string. – Alok Patel Commented Apr 12, 2016 at 13:45
 |  Show 3 more ments

4 Answers 4

Reset to default 2

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

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.

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.

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);
发布评论

评论列表(0)

  1. 暂无评论