Ajax get shopping cart on page load - php

I want to load the shopping cart whenever the page is loaded but nothing happens. The console log is not telling me anything either. I have a post to cart system that works fine, so I cant figure out why this doesnt work.
I am using Laravel with a shopping cart plugin.
$(document).ready(function() {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: 'get',
url: '{{route("getCart")}}',
error: function(data) {
var errors = data.responseJSON;
console.log(errors);
},
dataType: 'json',
success: function(data) {
$('#cartResult').html(data.cartCount)
},
});
});
public function cartGet()
{
$cartCount = Cart::content() - > count();
$data = array('cartCount' => $cartCount);
echo json_encode($data);
}

Try return json_encode($data); instead of echo.
You can also avoid json_encode and just use return $data;.

Simply return $data, laravel will place the correct header in response.
if you return json_endode($data) a Content-type: text/plain header will be placed,
if you return $data (which is a structure) laravel will json_encode under the hood and place a Content-type: application/json header.
your code should look like this:
public function cartGet()
{
return ['cartCount' => Cart::content()->count()];
}

It might be because in your $.ajax call you've set dataType: 'json'
From the docs:
As of jQuery 1.5, jQuery can convert a dataType from what it received
in the Content-Type header to what you require. For example, if you
want a text response to be treated as XML, use "text xml" for the
dataType. You can also make a JSONP request, have it received as text,
and interpreted by jQuery as XML: "jsonp text xml". Similarly, a
shorthand string such as "jsonp xml" will first attempt to convert
from jsonp to xml, and, failing that, convert from jsonp to text, and
then from text to xml.
When you echo json_encode(), it sends the data straight to the php output stream buffer and Laravel doesn't know that it needs to add a Content-Type: application/json header to its response. Without it, maybe jQuery needs the dataType to be "text json"?
As others have mentioned, you can return $data from your controller. Laravel will automatically cast your array to json, and it will also set the appropriate Content-Type headers. Maybe try that first?

Related

Send PHP's JSON response from an API call as part of AJAX success function

I have setup a page that takes the data from a form, serializes into JSON and then uses AJAX to call a PHP file to process the form data and send it to an API via cURL.
How can I get the response from the API to come back as part of the AJAX's success function?
At the start of my project, I was able to accomplish this because I was using the php as an include. But cannot use that method because the file is being executed from the AJAX call not from an include.
I tried to follow this tutorial, but just kept catching errors.
I've also scoured, reviewed and attempted more suggestions from various posts on this site than I can even count. Now, I'm asking for some help.
Here is the pertinent ajax on my index.php file.
$.ajax
({
type: "POST",
dataType : 'json',
async: false,
url: 'save_application.php',
data: { filename: fileName, applicationData: jsonFormString, job: adid },
success: function () { console.log("done");},
failure: function() {console.log('error');}
});
And here is the relevant part of the save_application.php file.
$curl = curl_init();
curl_setopt_array($curl, array(
//stuff here
));
$applicantresponse = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
And lastly, the $applicantresponse that comes back is formatted like this:
{
"applicationId": 123456789,
"links": {
"link1": "https://thisisalinkforLINK1.html", //THIS IS THE VALUE I WANT
"link2": "https://thisisalink.html",
"link3": "https://thisisalink.html"
}
}
Ultimately, I want to set a variable to the value for links->resume (ex: var resumeLink = (something goes here); \\returns https://thisisalinkforLINK1.html) back on my index.php within the success function so I can use that response for some other to-dos.
You need to output $applicantresponse from your save_application.php file so that it's returned to your calling code, and you need to change the success function in your ajax code to then use that data. It'll look something like this:
$applicantresponse = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
echo json_encode($applicantresponse);
and then...
$.ajax
({
...
success: function (data) {
console.log(data.links.link1);
// do something with the data that was returned
},
...
});
One thing that is important is that your php code not output any other text to the client. All other echo, print, debugging calls, all of that stuff, has to be removed, because otherwise you're not sending back valid json encoded data that jQuery knows how to interpret.
It looks like save_application.php uses the data submitted by $.ajax for the curl request, and you need to send part of the curl response back to the client to be used in the success function.
The curl response is already JSON, so the simplest thing to do is just
echo $applicantresponse;
which will send the entire curl response back to the client.
If you only want to send one of the links of it, you'll need to decode it and extract the specific piece you want, then re-encode that piece.
$applicantresponse = json_decode($applicantresponse);
$link = $applicantresponse->links->link1;
echo json_encode($link);

Ajax call with contentType: 'application/json' not working

I have an ajax call, that sends form data to a php function. Since I read a lot that using contentType: 'application/json' is best practice I wanted to give it a try as well. But unfortunately my script doesn't return anything when I use it. If I remove it, the script does what it is supposed to do.
Do you have any idea what the reason might be and why? Thank you!
$('#Form').submit(function(e) {
e.preventDefault();
var content = $(this).serialize() + "&ajax=1";
$.ajax('app/class/controller/contactForm.php', {
type: "POST",
//contentType: 'application/json',
dataType: 'json',
data: content,
success: function(result) {
console.log(result);
}
});
})
and my PHP:
if(isset($_POST['ajax']) && $_POST['ajax'] === '1') {
echo json_encode(validateForm($_POST));
}
When using contentType: 'application/json' you will not be able to rely on $_POST being populated. $_POST is only populated for form-encoded content types.
As such, you need to read your data from PHP raw input like this:
$input = file_get_contents('php://input');
$object = json_decode($input);
Of course if you want to send application/json you should actually send JSON, which you are not doing. You either need to build the object serialization to JSON directly, or you need to do something like this - Convert form data to JavaScript object with jQuery - to serialize the object from the form.
Honestly in your case, since you are dealing with form data, I don't quite think the use case for using application/json is there.
The best practice you refer to is about the server script setting the Content-Type for JSON to "application/json":
Header('Content-Type: application/json; charset=UTF8');
This is because otherwise a default Content-Type will be sent, often a catch-all text/html, and this could lead to an incomprehension with the client.
If you do not specify yourself a Content-Type in the jQuery request, jQuery will determine the most appropriate one. The problem here is that you were sending a POST form, for which the default Content-Type set by jQuery is application/x-www-form-urlencoded, which tells PHP to decode the data as POST fields and populate $_POST. Your script would have then recovered its parameters from $_POST (or maybe $_REQUEST).
By changing it to application/json, $_POST will no longer be populated, the receiving script operation won't receive the parameters where it was expecting to, and the operation breaks.
So you either need to:
not specify the Content-Type yourself (better, IMHO)
set a Content-Type of application/x-www-form-urlencoded; charset=UTF-8
set a Content-Type of application/json; charset=UTF-8 and modify the script to parse the POST stream and decode the JSON data; see this answer.
The third option requires proper handling of php://input.
The PHP script should be setting the Content-Type header.
if(isset($_POST['ajax']) && $_POST['ajax'] === '1') {
header('Content-Type: application/json');
echo json_encode(validateForm($_POST));
}

Json request to another domain

Im trying to make a request from one server to another with json and php.
my html page:
$.ajax({
type: "POST",
url: "https://api.domain.com/gateway/partners/create_account.ajax.php",
dataType: 'jsonp',
crossDomain: true,
data: { "name" : "Test name"},
success: function(data)
{
console.log(data.responseText);
}
});
My php looks like this:
$name = $_GET['name'];
$data = array("Hello", $name);
echo json_encode($data);
I want to receive on my console: Hello Test name
What did I do wrong?
You are:
Telling jQuery to process the response as JSONP
Writing PHP that will output JSON (not JSONP) … presumably with a text/html content-type.
Trying to make a POST request instead of a GET request. JSONP only supports GET.
Trying to treat the data returned by the request as if it were an XHR object.
The minimal example of a JSONP response would be:
<?php
header("Content-Type: application/javascript");
$name = $_GET['name'];
$data = array("Hello", $name);
echo $_GET['callback'];
echo "(";
echo json_encode($data);
echo ");";
Then you need to alter the JS so that type: "POST" becomes type: "GET" and console.log(data.responseText); becomes console.log(data);
Alternatively, you could use another technique to bypass the same origin policy and still use POST.
The jsonp is a old practice and a insecure one because any one can call to your script. To is very default tor retrieving errors when a jsonp call fails.
You can implement CORS headers in your request, and then you can use just a simple XHR call.
Addeding the header:
Access-Control-Allow-Origin: *
Will fix your issue, but is better use the exact domain instead of the wildcard.

PHP's json_encode and jQuery

I'm making an AJAX call to a page /person/steve:
$.ajax({
url: '/person/steve',
method: 'POST',
dataType: 'json',
success: function(response){
console.log(JSON.stringify(response));
}
});
/person/steve consists of this code:
$person = array(
'name' => 'Steve',
'twitter' => '#stevelindstrom'
);
echo json_encode(array('data' => $person));
die;
Now, in my php, when I log the result of that json_encode using the PEAR Log class, I get:
{"data":{"name":"Steve","twitter":"#stevelindstrom"}}
Which is what I would expect, but if I look at the response in the Chrome dev tools, it shows:
[{"data":{"name":"Steve","twitter":"#stevelindstrom"}}]
Any idea why my object is getting stuck into an array? I have other pages that are nearly identical (just different data), and they show up as I would expect them to...
EDIT: I tried using JSON_FORCE_OBJECT and I'm getting the same result.
Try adding to json_encode as second argument JSON_FORCE_OBJECT
And do You return JSON or a string, I mean the Content-type header, is it text/html or (which should be in this case) application/json ?
Or maybe just JSON.stringify method wraps it into an array, try using dragonfly or other tool to see source of the server's raw response.
According to your question, the response is a json string. Which would make the JSON.Stringify call redundant. Remove that and see what happens.

jquery cant transform json response

I'm using jquery with the form plugin to handle the submit, but when the client receive the server response it cant pass it to a json object:
var options = {
success: showResponse,
dataType: 'json',
error: errorhandler
};
$('#UserEditForm').ajaxForm(options);
The server response is generate with the _json_encode_ php function.
When I submit the form, always the errorhandler function is called and I check the response with firebug it comes with some kind of a space after the first "{"
" {"status":1"}"
, that with utf-8 encode and something like:
"{"status":1}"
with iso-8859-1.
Thanks!!
Do you send headers with your server reply?
Otherwise, try:
header('Content-type: application/json');
Also, I've had problems with jQuery not reading some large chunks of data in JSON correctly, and I used the parse method from json.org:
https://github.com/douglascrockford/JSON-js/blob/master/json2.js

Categories