0

Here is the javascript code that has a "no" in the datastring and i want to pass that datastring to data.php using getJson So that in the end i can get json as a response. My data.php code is working but javascript code is not working so please help me.

Javascript code

dataString = 'no='+ no; 

$.getJSON("data.php", dataString,function(response){

        console.log(response);
  });

php code

$no=$_POST['no'];

$headers = array(
'Content-Type: application/json',
);

$url = 'https://www.outpan.com/api/get-product.php?barcode='.$no.'&apikey=318c91a99b132a29dda536d63e7fb8b4';


$ch = curl_init();


curl_setopt($ch, CURLOPT_URL, $url);

curl_setopt($ch, CURLOPT_POST, false);

curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);


curl_setopt($ch, CURLOPT_RETURNTRANSFER, true );


curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);




 $result = curl_exec($ch);



curl_close($ch);

//$result_arr = json_decode($result, true);

echo result;

3 Answers 3

1

One possibility is response is not valid JSON (I am not sure, since you seemed to have tried printing the json_decoded version).
Try printing out the error by using error which is called when no valid JSON is received -

$.getJSON("data.php", dataString,function(response){
    console.log(response)
}).error(function(jqXHR, textStatus, errorThrown){ 
    console.log(textStatus+" - "+errorThrown); 
}); 

If an error is logged, then checkout the curl response in php and make sure it is valid json.

EDIT
This edit is assuming that he php response is invalid JSON as observed from the comments.
Looking at your php code, you have used this -

$headers = array(
'Content-Type: application/json',
);

Try this instead -

header('Content-Type: application/json');

EDIT 2
Looking at your php code again, there seems to be an error while printing -

echo result;

It should be -

echo $result;
Sign up to request clarification or add additional context in comments.

6 Comments

This is the error "parsererror - SyntaxError: Unexpected token a"
@AbdurRehmanFarooqi Yep, thats it. The PHP response is invalid json.
now i have commented the json part and just echo a statement and it is not returned as response.
@AbdurRehmanFarooqi before you print anything, just copy paste the contents here and check if it is valid JSON.
Its not working if is send you source code can you make the changes?
|
0

use $_GET In your php code, you are using $_POST now

1 Comment

i have checked it. Its not working. i think there is a problem with getjson
0

You should $_GET in your php code or change code like this :

$.getJSON("data.php", { no: no },function(response){

    console.log(response);
  });

In php use,

$no=$_REQUEST['no'];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.