Controller function call from JS- JSON parse error - only in firefox - javascript

I have a button, which on click should insert the users into table.
Basically im stuck in calling the controller function from my javascript.
HTML button.
<div class="continue_btton">
<input type="submit" name="submit" id="SaveSettings" value="<?php echo $this->translate('Update'); ?>" class="update bdr_rds2" onclick="if($('input[name=target_criteria]:checked').val() == 'optedin_users')
{
return someFun()
} else
{
return validateForm()
}
">
</div>
UPDATED:
Javascript
function someFun(){
var urlInsert = '#Url.Action("myFunAction")';
$.get(urlInsert, function () {
});
}
Also tried below, but the controller func not calling
function myFunAction(){
var formData = $("#Preference").serialize();
$.ajax({
type: 'POST',
url: '/advertiser/campaign/myFun',
data: formData,
dataType: 'html',
success: function (data) {
$('span.targetCount').text($.trim(data));
},
error: function (jqXHR, textStatus, errorThrown) {
var error = $.parseJSON(jqXHR.responseText);
var content = error.content;
console.log(content.message);
if (content.display_exceptions)
console.log(content.exception.xdebug_message);
},
});
}
Controller.php - Doesnt seem to be called
public function myFunAction(){
echo '+++myFUN---';exit;
}
Error:
JSON.parse: unexpected character at line 1 column 1 of the JSON data
Tried dataType as html, json and text. Still same error.

My guess is either your post data or your response object is not considered valid json and that is why Firefox throws an error (maybe Chrome is more forgiving). What you could check is whether the request is send correctly and whether the response from the server actually arrives and whether it is valid json. You should consider returning valid json from your myFunAction method in your controller (instead of just printing a string like you do right now):
public function myFunAction(){
$data = '+++myFUN---';
return new JsonModel([
'data' => $data
]);
}
Check more on how to properly return Json in Zend for example on this blog post here: https://akrabat.com/returning-json-from-a-zf2-controller-action/
Valid json response should have a content-type header set to application/json and have a valid json string in the response body. Zend JsonModel will help you with this.
When you post data you should also set the content-type of the request to application-json, like that the server understands that you are sending a json object with data.
I never use JQuery but I think it is done like this if I am not mistaken:
$.ajax({
type: 'POST',
url: '/advertiser/campaign/myFun',
data: formData,
contentType: "application/json",
});

Related

show values entered in form as a table before getting submitted

First, I do not have much talent in ajax so please consider that while answering. Here I want to get all the values which I inserted into the form in a table before getting submitted but unfortunately am not getting the results I want. So far I have done this. Please have a look.
<script>
var form_data={ agent_name: $('#agent_name').val(),
type: $('input[name="type"]').val(),
number: $('#number').val(),
quantity: $('#quantity').val()
}
$.ajax({
type: 'POST',
url: '<?php echo base_url();?>admin_control/ajax_data',
data: form_data,
dataType:"json", //to parse string into JSON object,
success: function(data){
if(data){
var len = data.length;
alert(len);
var txt = "";
if(len > 0){
for(var i=0;i<len;i++){
if(data[i].agent_name && data[i].type){
txt += $('#table').append('<tr class="item-row"><td><input type="hidden" id="add_type" name="add_type[]" value="super">Super</td><td><input type="hidden" id="add_amount" name="add_amount[]" value="10">745</td><td><input type="hidden" class="add_quantity" id="add_quantity" name="add_quantity[]" value="10">10</td><td name="add_amount" id="add_amount">100</td><td><input type="checkbox" class="add_checkbox" name="layout" id="add_checkbox" value="1" checked></td></tr>');
}
}
if(txt != ""){
$("#table").append(txt).removeClass("hidden");
}
}
}
},
error: function(jqXHR, textStatus, errorThrown){
alert('error: ' + textStatus + ': ' + errorThrown);
}
});
return false;
</script>
Here I want to pass the values of form_data in to the table I had written and how can we pass that and did it compulsory to use the url in ajax while using this am getting an error like error: parsererror: SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data.
Here is my controller
public function ajax_data()
{
$array = array("agent_name" => "admin","number"=>"785","type"=>"super","quantity"=>"10");
$data['json'] = $array;
echo json_encode($data);
}
The Ajax post will call the controller method for post values. The ajax code usually correct but you have not defined url.
url: '',
Firstly define a method (ex: HomeController) then set ajax url parameter like
url: '#Url.Action("Save","Home")' or url: 'Save/Home'
[HttpPost]
public JsonResult Save(string agent_name, string type , int number,int quantity)
{
// return json
}
Note :
The data types you send from the form with the method types must be
the same.
Well, just to give you some hints to work on: The Ajax call could look like this:
$.ajax({
type: 'POST',
url: 'echodata.php',
data: form_data,
dataType:"json",
success: function(data){
$('#table').append('<tr><td>'+data.agent_name+'</td>' // + more columns ...
+'</tr>');}
);
The php script should really be something that processes the incoming information (passed as the $_POST array) into some other data that will ultimately be echoed as JSON string.
This is just a trivial version of echodata.php for testing:
<?php
echo json_encode($_POST);
?>
EDIT:
While you have fixed your URL attribute and have added a "controller" on the server your Ajax success function still expects something it will not get. Your PHP script delivers a JSON string that will be parsed into as a JavaScript object and not an array. The object will not have the length property your success function tries to use. Instead you should be looking for the json property.
So, there is no point for the for loop, instead you can use data.json.agent_name, data.json.number and data.json.type (etc.) properties directly. Your current .append() also only adds a static string to your table. This should of course be changed to use the freshly received values.

AJAX not coming up a success even though its updating the database

My php is updating the table but not refreshing in javascript have tried several different ways of doing this and nothing is working.
PHP
$sql = "UPDATE INTOXDM.ASTP_FORM SET SUPERVISOR_EID = '".$newSuper."' WHERE FORMID = '".$formId."'";
$row = $xdm->fetch($sql);
$return["color"] = $row['APPRENTICE_SIGNATURE'];
$return["json"] = json_encode($return);
echo json_encode($return);
?>
Javascipt
var data = {
"formId": formID,
"newSuper": newSuper
};
data = $.param(data);
$.ajax({
type: "POST",
dataType: "json",
url: "src/GetInfo.php",
data: data,
success: function() {
location.reload();
}
});
I'd start by modifing the code like this:
var data = {
"formId": formID,
"newSuper": newSuper
};
// No need for serialization here,
// the 'data' parameter of jQuery.ajax accepts JS object
// data = $.param(data);
$.ajax({
type: "POST",
dataType: "json",
url: "src/GetInfo.php",
data: data,
// As suggested by Rocket Hazmat, try to add an error callback here
error: function(jQueryXHR, textStatus, errorMessage) {
console.log("Something went wrong " + errorMessage);
},
success: function(jsonResponse) {
// Try to reference the location object from document/window
// wd = document or window as seen here http://stackoverflow.com/questions/2624111/preferred-method-to-reload-page-with-javascript
// Also watch out, usually browsers require a user confirmation before reloading if the page contains POST data
// One of these should be fine
wd.location.assign(wd.location.href) : go to the URL
wd.location.replace(wd.location.href) : go to the URL and replace previous page in history
wd.location.reload(<true/false/blank>) : reload page from server/cache/cache
}
});
Also, this might be a shot in the dark but the parameter dataType gave me problems sometime in the past, so if you are sure about the json returned by your php script, you could use the eval function to jsonify the response
$.ajax({
...
// Remove data type
// dataType: "json",
...
success: function(plainTextResponse) {
// Eval response, NOT SAFE! But working
var jsonResponse = eval('('+ plainTextResponse +')');
...
}
});
Your ajax is expecting json data and your php is sending malformed json string. Send a correct json string and your script will work fine.
Your php json_encode should be like this:
$data = json_encode($return);
echo $data;

how to create correct PHP json response

Hello i have a page can calla an ajax page in json with jquery.
i just set
dataType: "json"
in ajax call and i set header in php
header("Content-type: application/json; charset=utf-8");
but when i try read my response in a client i have this error:
SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data
var o = JSON.parse(jsonString);
For more information
PHP file function:
function _addToWishlist($v,$db){
$ris = array();
$data = array();
$data[0]=20;
$data[1]=25;
$data[2]=30;
$ris['stato']="1";
$ris['mex']="DA IMPLEMENTARE!!!";
$ris['data']=$data;
$ris['action']="";
ob_clean();
echo json_encode($ris);
}
and thi is a php response:
{"status":"success","stato":"1","mex":"DA IMPLEMENTARE!!!","data":[20,25,30],"action":""}
in client i use this javascript:
$.ajax({
url: "common/function/include/dataLoad.php",
type: "POST",
data: datas,
async:false,
//dataType: "text",
dataType: "json",
success: function(ris) {
// Run the code here that needs
// to access the data returned
//$(this).parent
//alert (ris);
risp=ris;
//var a = JSON.parse(ris);
tryParseJSON(ris);
//return ris;
},
error: function() {
alert('Errore di rete');
}
}).done(function(){
if(divwhere!=""){
$(divwhere).html(risp);
}
if(actionAfter!=""){
eval(actionAfter);
}
});
the function for test json is here: stackoverflow
how can i do for create a correct call json? thank you very much
jQuery will automatically parse a JSON response for you - you don't need to do it again. The returned ris object is ready for you to work with as-is. Assuming the request works, there is no problem with the format of your PHP response.
success: function(ris) {
console.log(ris.status); // = 'success'
console.log(ris.mex); // = 'DA IMPLEMENTARE!!!'
},

Ajax Error Potentially Due to Incorrect Data Object Being Passed

Hi I am new to ajax and I am attempting to pass a Json to a Database, but I am not that far yet. Currently I am attempting to be verified that the data I am passing is being done successfully. However, I always drop into the ajax error method. I will upload my code and the way the data looks and then the error.
Thank you for your help!
<script>
function updateTable()
{
alert("Do i try to update table?");
document.getElementById("testLand").innerHTML = "Post Json";
//echo new table values for ID = x
}
function popupClick (){
var popupObj = {};
popupObj["Verified_By"] = $('#popupVBy').val();
popupObj["Date_Verified"] = $('#popupDV').val();
popupObj["Comments"] = $('#popupC').val();
popupObj["Notes"] = $('#popupN').val();
var popupString = JSON.stringify(popupObj);
alert(popupString);
$.ajax({
type: "POST",
dataType: "json",
url: "popupAjax.php",
data: popupObj,
cache: false,
success: function(data)
{
alert("Success");
updateTable();
},
error: function(data)
{
alert("there was an error in the ajax");
alert(JSON.stringify(data));
}
});
}
</script>
JSON Being Passed shown in var popupString:
Error:
popupAjax.php file (warning it's testy)
<?php
echo "Testing tests are testy";
?>
You are specifying the dataType as json. But this is the returned data type, not the type of the data you are sending.
You are returning html / text so you can just remove the dataType line:
type: "POST",
url: "popupAjax.php",
If you do want to return json, you need to build your datastructure on the server-side and send it at the end. In your test-case it would just be:
echo json_encode("Testing tests are testy");
But you could send a nested object or array as well.
As an additional note, you can use .serialize() on your form (if you use a form...) so that jQuery automatically builds an object that you can send in the ajax method. Then you don't have to do that manually.

Passing array with Ajax to PHP script results in empty post

I want to pass an array from a HTML site to a PHP script using AJAX
JS
function selectPictures() {
//selected Pictures is my JS array
var jsonArray = JSON.stringify(selectedPictures);
var request;
request = $.ajax({
url: "selectedPictures.php",
type: "POST",
data: {
data: jsonArray
},
cache: false
success: function () {
alert('OK');
}
});
}
HTML
href="selectedPictures.php" onclick="selectPictures();"
PHP
if (isset($_POST['data'])) {
$data = json_decode(stripslashes($_POST['data']));
foreach($data as $d) {
echo $d;
}
}
Actually I want to send the data to another HTML page and then include the PHP script, but I don't understand why this example does not even work. The $_POST['data'] is not set.
UPDATE
Ok, the Ajax post is actually working, as I see the HTTP request is successful BUT: I cannot access the variable instantly. I need to access the values of the passed array at once to execute another PHP script. When I want to do this, I get an undefined index error. Also at the time when the isset function is executed, it returns false (despite the successful HTTP request).
HTML
click
JS
$(function(){
$('#selectPictures').click(function(){
var jsonArray = JSON.stringify(selectedPictures);
var request = $.ajax({
url: "selectedPictures.php",
type: "POST",
data: {data: jsonArray},
cache: false,
success: function(data){alert(data);}
});
});
});
Use f12 in chrome to see errors, you forgot to add a comma after the "cache: false"

Categories

Resources