0

In .js I want to send some multi data in json using ajax. I have problem receiving them in my php

js:

$("#mybtn").on('click'.function(){
    $.ajax({
        type:'POST',
        url: 'handler.php',
        data: JSON.stringify({taskId:2 , infos:"blahblah"}),
        headers:{
              'content-type':'application/json'
        },
        success: function(response){alert "response";},
        error: function(){alert "error";}
    });
});

for example how can i ,if taskid is 1, write infos in debug.txt?

handler.php:

<?php
    $temp = $_POST;  //also i put $_REQUEST not usefull
    file_put_contents('D:\debug.txt',$temp);
    //$temp2 = data   I don't know how to do it!
    if($temp2['taskId']==1){
        file_put_contents('D:\debug.txt',$temp2['infos']);
?>

2 Answers2

0

after a lot of research and consulting one of my friend I get the answer: if we want to send data using ajax in json our js should be like this:

$.ajax({
    type: 'POST',
    url: 'destination.php',
    data: JSON.stringify({
        id: 1,
        name: 'user'
    }),
    headers:{'content-type': 'application/json'},
    success: function(response){
        //assume we have received data from php in json form:
        response = JSON.parse(response);
        dosomething(response);
    },
    error: function(){ alert("Error in Ajaxing"); }
});

now in php:

<? php
$json = file_get_contents('php://input');
$ary = json_decode($json);

$result = dothings($ary);
$result = json_encode($result);    
echo(result);
?>

Hope this helps others!

-1

Json encode your post in PHP :

  $.ajax({
        type:'POST',
        url: 'handler.php',
        data: {taskId:2 , infos:"blahblah"},
        success: function(response){alert "response";},
        error: function(){alert "error";}
    });

And :

$temp = $_POST;
file_put_contents('D:\debug.txt', json_encode($temp));
if($temp['taskId']==1){
    file_put_contents('D:\debug.txt',$temp['infos']);
Vincent Decaux
  • 9,857
  • 6
  • 56
  • 84