A few issues:
1)
while($result = mysql_fetch_assoc($exe)){
$value = json_encode($result);
}
echo $value;
Unless it so happens that your query only returns one row, this code will give you a problem - every time your while
loop runs, you'll overwrite $value
with a totally new value, so you'll only ever see the last line of data returned by your query.
If you know the query will only ever return one row, then the while
can be replaced with if
:
if($result = mysql_fetch_assoc($exe)){
$value = json_encode($result);
}
echo $value;
But if you might return multiple rows, you need to change it to:
$values = array();
while($result = mysql_fetch_assoc($exe)){
$values[] = $result;
}
echo json_encode($values);
so that you get a single JSON array containing all the results.
2) var x = JSON.parse(response);
- due to dataType: "json"
, response
is already an object. By setting the dataType
option as "json" you told jQuery to automatically parse it for you. So you don't need to parse it yourself, therefore this line is redundant.
Doing alert(response);
probably gets you something meaningless like [object]
shown in the alert, since response
is an object, and you can't just display an object as text. You can either stringify it to display the whole object, or pick a specific property to display and alert that, e.g.
Show the whole object:
alert(JSON.stringify(response));
Show a particular attribute:
alert(response.id);
3) This isn't broken in this case, but I recommend not building your data
string yourself. It means you don't get the benefit of proper URI-encoding of your data, which jQuery can take care of for you. This means that if you send any characters in your data which have special meaning in a querystring (e.g. &
or ?
, for example), your string will break and the server won't understand what you've sent it. You won't notice if you're just sending a simple integer or something, but you should get into the habit of doing this so you encounter problems in future.
Instead, give jQuery an object containing the data, and it'll take care of building the querystring for you and encoding it correctly:
data: { "product_id" : product_id, "type": "add" },
4) This is not directly related to your issue, but it's nonetheless a serious thing which you need to sort out urgently: Why are you using the long-deprecated mysql_
code library? It was discontinued many years ago and removed entirely in PHP7. No new code should be written using this library. It leaves you vulnerable to SQL injection attacks (due to the lack of parameterised query support) and potentially other unpatched vulnerabilities. Switch to using mysqli
or PDO
as soon as possible, and then learn how to write parameterised queries to protect your data from malicious input. See http://bobby-tables.com for a simple explanation of the risks and some sample PHP code to write queries safely.