Ajax variable ignores line breaks - php

I´ve got a problem when I try to send the value of a textarea through Ajax in Joomla.
The variable looks correct right before the ajax request. But when returned from helper.php, the success response var ignores all the line breaks.
My jQuery / Ajax:
var curBody = jQuery(this).closest("div").children("div").children('textarea').val();
//var curBody = curBodyVal;//.replace("/\r\n/","<br>");
console.log(curBody);
jQuery.ajax({
url: "index.php?option=com_ajax&module=usernotes&method=edit&format=json&Id="+edit_id+"&body="+curBody,
success: function( response ) {
console.log(response);
}
});
In my helper.php file at the function for the ajax call:
public static function editAjax()
{
$input = JFactory::getApplication()->input;
//$bodyToUpdate = $input->get("body", 'default_value', 'raw');
$bodyToUpdate = $_GET['body'];
return($bodyToUpdate);
}

Whenever you are trying to send values, which are not simple strings, send it ina a POST method instead of GET,
GET is used for simple strings, only used for characters within ASCII character range.
POST is used for any other complicated strings, you can send binary data as well, for example you can send files and images using POST method, but you cannot send using GET method
Change your ajax to this:
$.ajax({
method: "POST",
url: "index.php",
data: { option: "com_ajax", module: "usernotes" , method: "edit", format: "json" , Id: edit_id, body: curBody },
success: function( response ) {
console.log(response);
}
});

Related

Jquery/Ajax not getting input value from widget

Have a ajax request sending data to a WordPress action which works fine however I can receive the nonce value perfectly but the email input isn't being sent. I know I'm targeting the right value. It does not want to get the value of the email input. If I hardcode a value into the input it will see it. I need to get the user entered value and send that to the ajax script. The code is also run on document load and is after the form values have been rendered.
Input field looks like this:
<input type="email" name="cjd_email" id="cjd_email" class="cjd-email-input"/>
The jquery selector looks like:
var cjd_email = $('#cjd_email').val();
The ajax call is:
$.ajax({
url: cjdAjax.ajaxurl,
type: 'POST',
data: {
action: 'cjd_subscribe',
nonce: cjd_nonce,
email: cjd_email
},
cache: false,
success: function(data) {
var status = $(data).find('response_data').text();
var message = $(data).find('supplemental message').text();
if(status == 'success') {
console.log(message);
}
else {
console.log(message);
}
}
});
Thanks :)
I am assuming you are having a class on form i.e. cjdajax. Then use serialize method to send data instead of any other.
$.ajax({
url: cjdAjax.ajaxurl,
type: 'POST',
data: $('.cjdAjax').serialize(),
cache: false,
success: function(data) {
//your code
}
});
Depending on the browser you use, type=email might not be supported by jQuery / JavaScript and thus the valid() method could return rather strange values. As an alternative, one can use type=text with input validation.
Also, you should Review the success function : You attempt to apply the find()-method on text rather than a DOM element. The code could be corrected if the server returned a JSON-encoded string, so in JavaScript you could convert the string back into an object.
In PHP one could write print(json_encode($yourArray, true)); (notice how the true flag is required for associative keys), while
...
success: function(data){
var yourObject = JSON.parse(data);
if (yourObject.responseData === "success")
console.log(yourObject.message);
},...
could replace the respective current JavaScript passage.

jQuery send a query strings value as POST instead of GET

One of my php pages was changed to handle POST data (in order to accommodate a few form text fields), instead of GET (which was previously used).
So now, instead of if($_GET) { } it uses if($_POST) { }. They (team) wont allow both methods using ||.
I need to send a querystring to that same page using jQuery, but because of if($_POST) { }, it will not get through.
The querystring is formed from this : <i class="icon-hand remove" data-handle="se25p37x"></i>
I used to send it using jQuery ajax before, but that will not work now. Any idea how I can send it as POST?
$('.remove').live('click', function() {
var self = $(this);
var handle = $(this).data("handle");
if(handle) {
$.ajax({
type:"POST", // this used to be GET, before the change
url:"/user/actions/"+handle,
dataType:'json',
beforeSend:function(html) {
},
Just change type: "GET" to type: "POST" and add data parameter:
...
type: "POST",
data: $('form').serialize(), // OR data: {handle: $(this).data("handle")}
dataType: 'json',
...

Getting Response From Jquery JSON

I'm having trouble getting a response from my php jquery / json / ajax. I keep combining all these different tutorials together but I still can't seem to pull it all together since no one tutorial follow what I'm trying to do.
Right now I'm trying to pass two arrays (since there's no easy way to pass associative arrays) to my jquery ajax function and just alert it out. Here's my code:
PHP
$names = array('john doe', 'jane doe');
$ids = array('123', '223');
$data['names'] = $names;
$data['ids'] = $ids;
echo json_encode($data);
Jquery
function getList(){
$.ajax({
type: "GET",
url: 'test.php',
data: "",
complete: function(data){
var test = jQuery.parseJSON(data);
alert(test.names[0]);
alert("here");
}
},
"json");
}
getList();
In my html file all I'm really calling is my javascript file for debugging purposes. I know i'm returning an object but I'm getting an error with null values in my names section, and i'm not sure why. What am I missing?
My PHP file returns
{"names":["john doe","jane doe"],"ids":["123","223"]}
It seems to be just ending here
Uncaught TypeError: Cannot read property '0' of undefined
so my sub0 is killing me.
You could prob use the $.getJSON facade that jQuery provides, this will setup all the required ajax params for a standard JSON request:
$.getJSON('test.php', function(response) {
alert(response.names[0]); // john doe
});
However i think the route of the issue is that 1) your server may not be returning the correct response codes and/or the correct headers (ie: JSON data) - however the above method at least for the latter should force this conclusion.
See: http://api.jquery.com/jQuery.getJSON
It looks like the problem is that you're using the complete callback instead of the success callback:
function getList(){
$.ajax({
type: "GET",
url: 'test.php',
data: "",
success: function(data) { /* success callback */
var test = jQuery.parseJSON(data);
alert(test.names[0]);
alert("here");
}
},
"json");
}
getList();
From jQuery AJAX Docs:
success(data, textStatus, jqXHR)
A function to be called if the request succeeds. The function gets passed three arguments: The data returned from the server, formatted according to the dataType parameter; a string describing the status; and the jqXHR (in jQuery 1.4.x, XMLHttpRequest) object. As of jQuery 1.5, the success setting can accept an array of functions. Each function will be called in turn. This is an Ajax Event.
complete(jqXHR, textStatus)
A function to be called when the request finishes (after success and error callbacks are executed). The function gets passed two arguments: The jqXHR (in jQuery 1.4.x, XMLHTTPRequest) object and a string categorizing the status of the request ("success", "notmodified", "error", "timeout", "abort", or "parsererror"). As of jQuery 1.5, the complete setting can accept an array of functions. Each function will be called in turn. This is an Ajax Event.
jQuery wants to know what kind of data to expect as a response, otherwise it wont know how to parse it.
So, as has been said before here, you tell jQuery using the dataType = 'json' attribute.
function getList() {
$.ajax({
type: "GET",
url: 'test.php',
data: "",
dataType: "json",
success: function(data) {
console.log(data);
}
});
}
On top of this it is a good idea to have PHP present its content as json rather than html. You use the header for this by setting header('Content-type: application/json'); before any output in your PHP script. So:
$names = array('john doe', 'jane doe');
$ids = array('123', '223');
$data['names'] = $names;
$data['ids'] = $ids;
header('Content-type: application/json');
echo json_encode($data);
You should pass all parameters for ajax() function in single object. So, there should be "dataType" option. Also, if you set data type explicitly, jQuery will parse JSON data for you. Complete callback will receive parsed JavaScript object as parameter.
function getList() {
$.ajax({
type: "GET",
url: 'test.php',
data: "",
dataType: "json",
success: function(test) {
alert(test.names[0]);
alert("here");
}
});
}

jQuery ajax request with json response, how to?

I am sending an ajax request with two post values, the first is "action" which defines what actions my php script has to parse, the other is "id" which is the id of the user it has to parse the script for.
The server returns 6 values inside an array() and is then encoded to JSON with the PHP function: json_encode();
Some of my responses are HTML, but when I encode it to JSON, it escapes "/" so it becomes "\/"
How do I disable that?
Also when I don't know how to display this in jQuery when I get the server response, I just thought that putting it all into a div would just display the numbers and HTML codes I had requested, but it displays the array as it is encoded in PHP.
PHP
$response = array();
$response[] = "<a href=''>link</a>";
$response[] = 1;
echo json_encode($response);
jQuery:
$.ajax({
type: "POST",
dataType: "json",
url: "main.php",
data: "action=loadall&id=" + id,
complete: function(data) {
$('#main').html(data.responseText);
}
});
How do I make this into working JSON?
You need to call the
$.parseJSON();
For example:
...
success: function(data){
var json = $.parseJSON(data); // create an object with the key of the array
alert(json.html); // where html is the key of array that you want, $response['html'] = "<a>something..</a>";
},
error: function(data){
var json = $.parseJSON(data);
alert(json.error);
} ...
see this in
http://api.jquery.com/jQuery.parseJSON/
if you still have the problem of slashes:
search for security.magicquotes.disabling.php
or:
function.stripslashes.php
Note:
This answer here is for those who try to use $.ajax with the dataType property set to json and even that got the wrong response type. Defining the header('Content-type: application/json'); in the server may correct the problem, but if you are returning text/html or any other type, the $.ajax method should convert it to json. I make a test with older versions of jQuery and only after version 1.4.4 the $.ajax force to convert any content-type to the dataType passed. So if you have this problem, try to update your jQuery version.
Firstly, it will help if you set the headers of your PHP to serve JSON:
header('Content-type: application/json');
Secondly, it will help to adjust your ajax call:
$.ajax({
url: "main.php",
type: "POST",
dataType: "json",
data: {"action": "loadall", "id": id},
success: function(data){
console.log(data);
},
error: function(error){
console.log("Error:");
console.log(error);
}
});
If successful, the response you receieve should be picked up as true JSON and an object should be logged to console.
NOTE: If you want to pick up pure html, you might want to consider using another method to JSON, but I personally recommend using JSON and rendering it into html using templates (such as Handlebars js).
Since you are creating a markup as a string you don't have convert it into json. Just send it as it is combining all the array elements using implode method. Try this.
PHP change
$response = array();
$response[] = "<a href=''>link</a>";
$response[] = 1;
echo implode("", $response);//<-----Combine array items into single string
JS (Change the dataType from json to html or just don't set it jQuery will figure it out)
$.ajax({
type: "POST",
dataType: "html",
url: "main.php",
data: "action=loadall&id=" + id,
success: function(response){
$('#main').html(response);
}
});
Connect your javascript clientside controller and php serverside controller using sending and receiving opcodes with binded data. So your php code can send as response functional delta for js recepient/listener
see https://github.com/ArtNazarov/LazyJs
Sorry for my bad English
Try this code. You don't require the parse function because your data type is JSON so it is return JSON object.
$.ajax({
url : base_url+"Login/submit",
type: "POST",
dataType: "json",
data : {
'username': username,
'password': password
},
success: function(data)
{
alert(data.status);
}
});

Jquery, reading JSON variables received from PHP

Sorry if this is basic, but I have been dealing with figuring this out all day and have gotten to where I can do everything I need with Jquery and cakephp (not sure if cakephp matters in this or if its same as any PHP), I want to return a variable from a cakephp function to jquery, I had read about how to do it, like here:
the cakephp:
$test[ 'mytest'] = $test;
echo json_encode($test);
and the jquery:
$.ajax({
type: 'POST',
url: 'http://localhost/site1/utilities/ajax_component_call_handler',
data: {
component_function: component_function,
param_array: param_array
},
dataType: "json",
success: function(data) {
// how do i get back the JSON variables?
}
});
I just can't figure out how to get one or more variables back into usable form within jquery, I just want the variable so I can do whatever else with it, I've been looking at what I can find through searching but its not making it fully clear to me.. thanks for any advice.
The JSON variables are in the data variable. In your case, it'll look like this:
var data = {
myTest: "Whatever you wrote here"
};
... so you can read it from data.myTest.
(Not sure whether it's relevant but you can remove the http://localhost/ part from the URL;
AJAX does not allow cross-domain requests anyway.)
Your variables are in data.
$.ajax({
type: 'POST',
url: 'http://localhost/site1/utilities/ajax_component_call_handler',
data: {
component_function: component_function,
param_array: param_array
},
dataType: "json",
success: function(data) {
// how do i get back the JSON variables?
var values = eval( data ); //if you 100 % trust to your sources.
}
});
Basically data variable contain the json string. To parse it and convert it again to JSON, you have to do following:
$.ajax({
type: 'POST',
url: 'http://localhost/site1/utilities/ajax_component_call_handler',
data: {
component_function: component_function,
param_array: param_array
},
dataType: "json",
success: function(data) {
json = $.parseJSON(data);
alert(json.mytest);
}
I haven't test it but it should work this way.
Note that when you specify dataType "json" or use $.getJSON (instead of $.ajax) jQuery will apply $.parseJSON automatically.
So in the "success" callback you do not need to parse the response using parseJSON again:
success: function(data) {
alert(data.mytest);
}
In case of returning a JSON variable back to view files you can use javascript helper:
in your utilities controller:
function ajax_component_call_handler() {
$this->layout = 'ajax';
if( $this->RequestHandler->isAjax()) {
$foobar = array('Foo' => array('Bar'));
$this->set('data', $foobar);
}
}
and in your view/utilities/ajax_component_call_handler.ctp you can use:
if( isset($data) ) {
$javascript->object($data); //converts PHP var to JSON
}
So, when you reach the stage in your function:
success: function(data) {
console.log(data); //it will be a JSON object.
}
In this case you will variable type handling separated from controllers and view logic (what if you'll need something else then JSON)...

Categories