Zend redirects to json response - json

I'm making a POST request, using ajax, to a Zend Controller.
$.ajax({
type: 'POST',
data: data,
dataType: "json",
error: function(e){
console.log(e);
}
success: function(msg){
if(msg.success){
//doesn't reach here. I'm getting redirected
console.log('success');
}
}
});
In zend, I have the following line:
$this->jsonResponse(array('success' => true, 'embed' => 'some text here'));
My problem is that I'm getting redirected to the json response page (that's the actual page) which contains the response. The response is correct, but I don't want to be redirected. I don't know what's happening and why is this happening.

In controller write these codes
$this->_helper->layout()->disableLayout(); //to disable layout
$this->view->jsonResponse = json_encode(array(
'success' => true,
'embed' => 'some text here'
)); // encode array
And in view write this line
echo $this->jsonResponse;

Related

Ajax requesting an API for data on a project

So I am busy with a private coding project right now, but can't seem to get my code to work properly.
I want to in essence, get data from my API and display it on to my HTML page, the data type is set to "jsonp" because of CORS errors( this was the only way I could debug it ), anyone have an idea of how I can get this to return usable data for my project?
function fetch(){
"use strict";var url = "https://api.pandascore.co/lol/champions?token=*my_unique_token*";
$.ajax({
url: url,
type: "GET",
crossDomain: true,
dataType: 'jsonp',
contentType: "application/json; charset=utf-8",
beforeSend: function(xhr){
xhr.setRequestHeader('Access-Control-Allow-Origin','*');
},
success: function(data){
console.log(data);
},
done: function(data){
console.log(data);
},
error: function(error){
console.log(error);
}
});
}
Edit:
This is a parsing problem, I cant get the code to log the success, I can see a response but its for my error log, but it doesn't show the success log, so the data is unusable.
Why not try the vanilla fetch method?
const url = 'https://api.pandascore.co/lol/champions?token=my_unique_token';
fetch(url)
.then(response => response.json())
.then(data => console.log(data))
This code should handle parsing JSON data you receive from pandascore. Fetch is not available in IE11, but there should be some polyfills lying around on the web.

Json Error In Laravel Ajax

I'm Use Laravel 5.2 And Ajax For Crud
Insert to Database is Correct But When Laravel Response The Browser Show Below Error In Console
SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
Laravel Code:
return response()->json('ok');
Jquery Code:
$.ajax({
type: type,
url: my_url,
data: formData,
dataType: 'json',
success: function (data) {
....
error: function(data){// Error...
var errors = $.parseJSON(data.responseText); console.log(errors);
$.each(errors, function(index, value) { $.gritter.add({
title: 'Error',
text: value
});
});
}
RedyState=4
Staus = 200
Can you paste your all controller code related to this error? Make sure you're not echoing anything before returning json response.
For example,
Route::get('/', function () {
echo "hi";
return response()->json('ok');
});
It would cause parse error.
With the Json response, what if you try something like.
return response()->json(['status'=>'ok']);
You javascript code should be
$.ajax({
type: type,
url: my_url,
data: formData,
dataType: 'json',
success:function (xhr){
var data = xhr.data;
},
error: function (error){
}
});
And why are you using var errors = $.parseJSON(data.responseText); ? Your response will be always json, no?

Is it possible to combine a GET and POST in Javascript?

I have javascript code that should login (ie send some information to the server) and then receive a reply JSON message. I know this is doable by first doing a post, and then in the asynchronous response, when it completes, do a get. This would require two callback functions and two messages.
I was just wondering whether there is any way to do a get and send JSON as part of the query, so that there is just a single request/response rather than two.
Here is a sample post I wrote:
function post(url, payload, callback) {
payload = JSON.stringify(payload);
var http = new XMLHttpRequest();
http.open("POST", location.pathname + url, true);
http.setRequestHeader("Content-type", "application/json");
http.onreadystatechange = function () {
if (http.readyState === 4 && http.status !== 200) {
callback(false, http.response);
} else if (http.readyState === 4 && http.status === 200) {
callback(true, http.response);
}
return;
};
http.send(payload);
}
If I want to get back JSON, what do I do?
Is it as simple as changing POST to GET and looking at:
http.responseText upon the return?
If you are doing any login functionality you should always use the HTTP POST method.
You could use AJAX (W3schools documentation about AJAX ) to handle sending your login form over POST and then handle the response in the same code block. bellow is an example.
$('#login-form').submit(function(e) {
e.preventDefault(); // Prevents the page from refreshing
// serializes the form data with id login-form
var formData = $(this).serialize();
$.ajax({
type: 'POST',
data: formData,
contentType: 'application/x-www-form-urlencoded',
dataType: 'json',
url: $(this).attr('action'),
//if your server sends a status OK message handle the response
//data will be the JSON response from the server
success: function(result,status,xhr) {
var jsonRes = JSON.parse(result); // parse the JSON object
console.log(jsonRes);
},
//if there was an error with your request the server will send
// an error response code and it is handled here
error: function(xhr,status,error) {
console.log(error);
}
});

Reading data from res.end()

I'm sending a simple data back from the server to the client.
app.post('/user', function (req, res) {
var userName = "John";
res.end(JSON.stringify({"error":"", "user": userName}));
});
$.ajax({
type: "POST",
...
contentType : 'application/json',
dataType: "json"
})
.done(function(data) {
// send join message
var resData = JSON.parse(data);
alert("hello"); // this doesn't show up
});
});
});
But in the browser console, I get this error - "Uncaught SyntaxError: Unexpected token o".
If I do JSON.stringify and JSON.parse on the content, it works fine.
alert(JSON.parse (JSON.stringify({"error":"", "user": userName})).user);
And also, .done works fine without a data payload from the server i.e. the alert("hello") works.
So, I'm guessing something fishy is happening while sending data within res.end(). Please help.
While at it, it would be nice if you can also tell me how to do the same using res.json() and which one is preferable.
The problem here is that you set dataType: 'json' in your jQuery request. This causes the response from the server to be automatically parsed as JSON, so it will return the object rather than the raw server response.

Keep getting a 404 when using Ajax in drupal

Hello i've got this problem with an ajax call in my (newbie) Drupal site. I'm trying to save some data from a form field, by posting it with jQuery to a function in my Drupal module. Here is my code:
// in drupal
function mymodule_menu() {
$items = array();
$items['mymodule/set/data'] = array(
'page callback' => 'mymodule_set_data',
'type' => MENU_SUGGESTED_ITEM,
'access arguments' => array('access content'),
);
return $items;
}
function mymodule_set_data($var) {
drupal_json_output(array('status' => 'OK', 'data' => "return_something"));
}
// in my js file
jQuery("#form_element").on('blur',function(){
jQuery.ajax({
type: 'POST',
url: "mymodule/set/data",
dataType: 'json',
data:{
fu: 'bar'
},
success: function(data) {
console.log(data);
},
error: function(jqXHR, textStatus, errorThrown){
console.log(errorThrown);
}
});
});
Everything goes well, the jQuery get's triggerd, the ajax call is being catched on the server, and i do get the {"status":"OK","data":"return_something"} back from the server. Except for the fact that the status of the call is a 404... :(
I found an solution to my problem.
Ik was moving my app to an other host and there for i needed to change the url the ajax action was calling. I decided to make it dynamic with the following code:
drupal_add_js(array('url' => $_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']), 'setting');
I changed my ajax call url into:
"http://"+Drupal.settings.url + "/set/data
This resulted in my JS calling the following URL:
http://host/drupal/?q=mymodule/set/data
instead of the old one:
http://host/drupal/mymodule/set/data
Which was something Drupal did like :)
Still i don't understand why my drupal accepted http://host/drupal/mymodule/set/data, handled my data but returned a 404.