How to send JSON to PHP?

Asked

Viewed 367 times

2

How to send this object by ajax, and read on php?

inserir a descrição da imagem aqui

//Aqui crio o objeto com os inputs 
var obj = new Object();
var objectsRadio = $('input:checked').map(function(i){
    obj.id_varejo = id_varejo;
    obj.id_pesquisa = idPesquisa;
    obj.id_pergunta = $(this).attr('name');
    obj.id_resposta = $(this).val();  

    return {
          id_varejo   : obj.id_varejo,
          id_pesquisa : obj.id_pesquisa,
          id_pergunta : obj.id_pergunta,
          id_resposta : obj.id_resposta
   };          
}).get();    

//Aqui sera o envio para php
var sql =  $.ajax({
    type: 'get',
    url: 'dadosPS.php?ps=saveResult',
    dataType : 'json',
    data: { 'dados' : objectsRadio },

    //data: jsonString,
    beforeSend: function () {
      //console.log("Before");
    },

    success: function (data, textStatus, jqXHR) {
        // console.log("Success = " + data);
    },

    complete: function () {},

    error: function (jqXHR, textStatus, errorThrown) {
        //console.log("Error"); 
    }
 });

Return update, this is php’s answer

Array
(
[dados] => Array
    (
        [0] => Array
            (
                [id_varejo] => 895
                [id_pesquisa] => 1
                [id_pergunta] => 1
                [id_resposta] => 3
            )

        [1] => Array
            (
                [id_varejo] => 895
                [id_pesquisa] => 1
                [id_pergunta] => 2
                [id_resposta] => 8
            )

        [2] => Array
            (
                [id_varejo] => 895
                [id_pesquisa] => 1
                [id_pergunta] => 3
                [id_resposta] => 11
            )

        [3] => Array
            (
                [id_varejo] => 895
                [id_pesquisa] => 1
                [id_pergunta] => 4
                [id_resposta] => 12
            )

        [4] => Array
            (
                [id_varejo] => 895
                [id_pesquisa] => 1
                [id_pergunta] => 5
                [id_resposta] => 13
            )

        [5] => Array
            (
                [id_varejo] => 895
                [id_pesquisa] => 1
                [id_pergunta] => 6
                [id_resposta] => 14
            )

        [6] => Array
            (
                [id_varejo] => 895
                [id_pesquisa] => 1
                [id_pergunta] => 7
                [id_resposta] => 16
            )

        [7] => Array
            (
                [id_varejo] => 895
                [id_pesquisa] => 1
                [id_pergunta] => 8
                [id_resposta] => 18
            )

        [8] => Array
            (
                [id_varejo] => 895
                [id_pesquisa] => 1
                [id_pergunta] => 9
                [id_resposta] => 23
            )

        [9] => Array
            (
                [id_varejo] => 895
                [id_pesquisa] => 1
                [id_pergunta] => 10
                [id_resposta] => 26
            )

        [10] => Array
            (
                [id_varejo] => 895
                [id_pesquisa] => 1
                [id_pergunta] => 11
                [id_resposta] => 29
            )

        [11] => Array
            (
                [id_varejo] => 895
                [id_pesquisa] => 1
                [id_pergunta] => 12
                [id_resposta] => 30
            )

        [12] => Array
            (
                [id_varejo] => 895
                [id_pesquisa] => 1
                [id_pergunta] => 13
                [id_resposta] => 31
            )

        [13] => Array
            (
                [id_varejo] => 895
                [id_pesquisa] => 1
                [id_pergunta] => 14
                [id_resposta] => 32
            )

        [14] => Array
            (
                [id_varejo] => 895
                [id_pesquisa] => 1
                [id_pergunta] => 15
                [id_resposta] => 33
            )

    )

)

in the precise case insert now in mysql database with this table structure

  1. id (pk,auto increment)
  2. id_search
  3. id_question
  4. id_respostaid_var

this would be the final point for me to finalize this issue.

  • 1

    You know you need to use AJAX, so have you read the documentation on? And what did you try to do after that? Put your code in the question.

  • use $item = json_decode($json, true), then can make a foreach with something like echo $item[0]['id_pergunta']

  • //Here I create the object with the inputs var obj = new Object(); var objectsRadio = $('input:checked'). map(Function(i) { obj.id_question = $(this).attr('name'); obj.id_answer = $(this).val(); Return { id_question : obj.id_question, id_answer : obj.id_answer }; }). get();

  • //Here will be the upload to php var sql = $.ajax({ type: get', url: 'PS.php data? ps=saveResult', dataType : 'json', date: [{ 'data' : objectsRadio }], });

  • Carlos, just below the question there is the [Edit] button. Use it to insert this code. Do not forget to format it correctly.

  • 1

    What about PHP code? By the way, what’s going on? How did you identify that this code doesn’t work? Does any error appear? Which? The HTTP method shouldn’t be POST instead of GET? What data comes in PHP? What comes back in Javascript?

  • Do this and see what returns in your console’s XHR request: $array = json_decode($_POST['dados']); print_r($array); die(); Note: try sending via post. GET will definitely give problem.

  • PHP receives the JS array you send, you just need to use json_decode() to convert into array format.

  • Objs: 'data' does not need to be in string format, can use so: ... data: {dados:objectsRadio}

  • the return of PHP, will be your echo output from json_decode() which is inside the return variable: date of your Success, that is, log: ...success:function(data) { console.log(data) }, do not forget to remove the print_r() and echo the: json_decode($_POST);

  • Use $.ajax({ type: 'post', ...

  • I tried reading the array with foreach but only returns error... what I am doing wrong?

Show 7 more comments

1 answer

2


A simple example, that would be...

var objArr = []

for(let i = 0; i < 20; i++){
  objArr.push(i)
}

console.log(objArr)

$.ajax({
  type: 'POST',
  url: 'SUA URL',
  data: objArr,
  success: function(data){
    console.log(data)
  }
})

  • In case I can use this same logic to read in php with foreach and inside this foreach perform the Insert?

  • @Carloslopes Exactly

  • Are you sure you can set the object ojbArr with let? He will exist in the scope of $.ajax?

  • It was just an example, because I was going to do without jquery, with pure js. but I ended up putting jquery. but the correct thing would be to use var

Browser other questions tagged

You are not signed in. Login or sign up in order to post.