nicecap
nicecap

Reputation: 13

jquery.ajax to PHP fails when I use ECHO in my PHP

this is the 1st time I try to use AJAX - my website needs to call a PHP during runtime when the user leaves a specific form field (VIN). I pass the value of this field to a PHP function for validation and processing. Then PHP should return 3 values for 3 different form fields. This is my problem: I won't get the 3 values back into my javascript.

Each time when I use ECHO json_encode in my php the AJAX call crashes and the console shows "VM7190:1 Uncaught SyntaxError: Unexpected token Y in JSON at position 0(…)".

If I put any other simple ECHO in my PHP the AJAX call would return with an error.

If I remove each ECHO from my PHP the AJAX call returns as success but the returning data is NULL.

It would be so great if I could get a solution for this problem here.

If anybody would like to test the site - this is the url: mycarbio

Thank you very much.

This is my AJAX call:

function decode_my_vin(myvin) {

alert("in decode_my_vin");
dataoneID  = '123';
dataoneKEY = 'xyz';

jQuery.ajax(
    {
    cache: false,
    type: 'POST',
    url: '/wp-content/themes/Impreza-child/vin-decoder.php',
	dataType:'json',
    data: { 
			'value1_VIN':	myvin,
			'value2_ID':	dataoneID,
			'value3_KEY':	dataoneKEY,
			'value4_Year':	' ',
			'value5_Make':	' ',
			'value6_Model':	' '
		  },
//	async: false,
	success: function(response) {
			var obj = jQuery.parseJSON(response);
			alert("success returned: " + obj); 
		    document.getElementById("fld_7290902_1").value = "2015";
	    	document.getElementById("fld_1595243_1").value = "Ford";
    		document.getElementById("fld_7532728_1").value = "Focus";
			return;
		},
	error: function() { alert("error in der jquery"); }
    });
}

And this is my PHP

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

	$resultYear = '2010';
	$resultMake = 'Ford';
	$resultModel = 'Focus';
	
    $vinResult = array("Year: ", $resultYear, "Make: ", $resultMake, "Model: ", $resultModel);

	echo json_encode($vinResult);
?>

Upvotes: 1

Views: 113

Answers (1)

jonalport
jonalport

Reputation: 380

This may not be your only problem, but you should try using an associative array when rendering the JSON:

$vinResult = array(
  'Year' => $resultYear, 
  'Make' => $resultMake,
  'Model' => $resultModel
);

Currently you are combining your property names and values.

Upvotes: 1

Related Questions