i have this class on my php server:
class Voto implements JsonSerializable {
public $voto;
public $info;
public $codiceFiscaleStudente;
public $data;
public $idProva;
function __construct($voto,$idProva,$codiceFiscaleStudente,$data) {
$this->codiceFiscaleStudente=$codiceFiscaleStudente;
$this->voto=$voto;
$this->idProva=$idProva;
$this->data=$data;
$this->info=null;
}
public function jsonSerialize() {
return get_object_vars($this);
}
}
the problem is that the script doesn't send to the client the jsonObject.I've tried to find the error: the script works fine because i tried to send back not the jsonObject but a single properties of my class Voto.
this is my other server syntax
try{
$query="LOCK TABLES sostieneprova read;";
$success=mysqli_query($conn,$query);
if($success){
$voto=getVoto($conn,$_POST['idProva'],$_POST['studente_codiceFiscale']);
if(gettype($voto)==="object"){
$voto->info="Esiste giĆ un voto dello studente in data ".$voto->data;
/*if in my Ajax-request i set datatype="html" and i send back echo($voto->info) it works fine.Instead if in my AJAX CALL in javascript i have set datatype "json" javascript doesn't receveid a jsonObject but an empty string.i think that the problem is with the function below json_encode*/
echo(json_encode($voto));
}
else{
throw new Exception ("Non esiste alcun voto dello studente nella prova: ".$_POST['idProva']);
//$query="UNLOCK TABLES;";
//mysqli_query($conn,$query);
}
}
else{
echo("Impossibile bloccare le tabelle per caricare il voto");
}
}
catch(Exception $e){
$query="UNLOCK TABLES;";
mysqli_query($conn,$query);
echo($e->getMessage());
}
JAVASCRIPT:
var ajax=$.ajax({
url:"responseregistrodocente.php",
data: queryString,
type:"POST",
datatype:"json",
cache:false,
ifModified:false});
ajax.done(
function(dettagliVoto){
alert(dettagliVoto.codiceFiscale);
});
ajax.fail(function(jqxhr){
alert(jqxhr.responseText);
});
Thanks for help.
if this could help: in my html page i have a the jquery document.ready and inside that i have:
$(".submitProve").on("click","button[name='visualizzaVoto']",caricaVotoHandler);
then in an exsternal file i have the function with the ajax request
function caricaVotoHandler(evento){
evento.stopPropagation();
//here there is other program code to build the queryString and the querystring //send the data correctly to the server.I've verified
var ajax=$.ajax({
url:"responseregistrodocente.php",
data: queryString,
type:"POST",
datatype:"json",
cache:false,
ifModified:false});
ajax.done(
function(dettagliVoto){
alert(dettagliVoto);
});
ajax.fail(function(jqxhr){
alert(jqxhr.responseText);
});
//}
}
If the script outputs properly if you only change echo json_encode($voto); to echo $voto->codiceFiscaleStudente; then your problem lies in your implementation of the JsonSerializable interface. try not using it:
If your class Voto only contains public members, all of which you are going to include in the JSON serialization, there's no need to implement JsonSerializable. Calling json_encode() on your object $voto will return the proper JSON string.
Also, in your first JS snippet, your alert call alert(dettagliVoto.codiceFiscale); looks like it should be using dettagliVoto.codiceFiscaleStudente instead, to match that property of your Voto class.
Related
Hi I am new to Laravel having a situation like: I have a HTML form and loading some HTML like "partial.blade.php" using AJAX in Same form, that is working perfectly with static HTML but,
I want to send a JS Array of object with AJAX Request to Dynamically loading HTML Content like: Drop down in same form
Could any Guide me how Can i Pass JS Array to that piece of HTML so i can Render that Array in "partial.blade.php"
here is my code
this is main form HTML & Array i want to pass with this AJAX Request
var dataArray = $('#data1').val();
code included at last in HTML Form Page
$.ajax({
url: "add-property/residential",
type: 'GET',
dataType: 'html',
data: { dataArr: dataArray },
contentType: false,
processData: false,
success: function(response) {
console.log(response);
$('#dynamicForm').html(response);
//alert(response);
},
error: function(response) {
console.log(response);
alert('Error....!');
}
});
here is my Route
Route::any('admin/add-property/residential',function() { return view('admin.residential'); });
all i want to receive that JS array in this piece of HTML that is dynamically loading
When you want to return the contents of a view() to an AJAX request, you can store the view as a variable and return in a JSON response:
public function apiResponse(){
$html = view("admin.residential")->render();
return response()->json(["html" => $html]);
}
In your AJAX request, you can access this as response.html:
success: function(response) {
$("#dynamicForm").html(response.html);
}
To pass a variable from AJAX to the view, you can use the request object. At the top of your routes/api (or routes/web.php, whichever you're using) add use Illuminate\Http\Request;, then in your Route inject that into the function:
<?php
use Illuminate\Http\Request;
...
Route::any('admin/add-property/residential',function(Request $request){
...
});
Not that $request is available, you can access the data being sent in the AJAX request via $request->input("dataArr");, and pass that to the view partial using ->with();:
Route::any('admin/add-property/residential',function(Request $request){
$dataArr = $request->input("dataArr");
$html = view("admin.residential")->with(["dataArr" => $dataArr])->render();
return response()->json(["html" => $html]);
});
According to this
Instead of return view('admin.residential');
You need to do this: return (string) View::make('admin.residential');
Edit
If you want to receive data from the ajax, and then load the view, you could do something like this:
Import the Request.
use Illuminate\Support\Facades\Response;
Make your rote point to a specific method on a controller.
Route::any('admin/add-property/residential',"YourController#returnView");
Make your function to handle the data
public function returnView(Request $request){
$data = $request->all(); // Here you will have all the data you send via AJ
//Make sure the $data has all the necessary parameter to load the view
$view = View::make('my_view', $data);//Here you will pass the data to the view
return response()->json(["html" => $$view->render()]); // Using #TimLewis return
}
I pass a value to my C# part with ajax and I get a response back. But I can't save the value or use it in my C# code. More information below:
Ajax Call: (gallery.aspx)
$.ajax({
url: Url, //assigned previously
data: 'call=ajax&method=GetList&typeIds=' + typeIds.replace(",",""),
type: 'POST',
dataType: 'json',
success: function (resp) {
console.log("From AJAX: " + resp) // this works and shows the result
},
error: function (xhr, status) {
console.log("Sorry, there was a problem!");
}
});
Code Behind (CodeFile):(gallery.aspx.cs)
Update: Full C# code snippet
public partial class gallery : System.Web.UI.Page
{
public List<string> images = new List<string>();
public List<string> imagesList = new List<string>();
public List<string> filteredImagesList = new List<string>();
public List<string> testList = new List<string>();
protected string imagesName;
protected string filterType;
protected void Page_Load(object sender, EventArgs e)
{
if (Request["call"].ParseString() == "ajax")
{
Response.Write(Request["typeIds"].ParseString().TrimEnd(','), true, ResponseType.Json);
filterType = Request["typeIds"].ParseString().TrimEnd(',');
}
else
{
filterType = "Not Assigned!";
}
}
}
Output on the page: Not Assigned!
Meaning <h1><%=filterType%></h1> in aspx file returns the else statement from aspx.cs file
But I get the response back in my javascript while console.log("From AJAX: " + resp) shows the result.
BUT I can't use filtertype's value in my c# codefile.
I can't understand how come the Response.Write(Request["type"].ParseString().TrimEnd(','), true, ResponseType.Json); gives back the Request["type"] to js part but don't save it for my codefile. Should it be anything like Response.Read or Response.Save or something?
Does someone know what is going on in here?
You can store the ajax response in a hidden field and then access that hidden field value in server side code.
<asp:HiddenField ID="HiddenField1" runat="server" />
$.ajax({
url: Url, //assigned previously
data: 'call=ajax&method=GetList&type=' + typeIds.replace(",",""),
type: 'POST',
dataType: 'json',
success: function (resp) {
console.log("From AJAX: " + resp) // this works and shows the result
$('#<%=HiddenField1.CliendId%>').val(resp);
},
error: function (xhr, status) {
console.log("Sorry, there was a problem!");
}
});
You can then access in server side code like this:
HiddenField1.Value
OK. It will never be assigned in the way how you did it. Simply because when the page is loading and all controls are rendering no ajax calls are taking into account Page Life Cycles. Because of that on page load filterType is not assigned.
Although you have a couple of options
Use Ajax with update panel and PageRequestManager class
Change the value through JQuery or Vanilla JS by using <%=filterType.ClientID%>
If you need only front-end representation you can use either option. If you need it for further back-end I'm afraid option 1 only choice for you.
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.
I am trying to access the output from php code to jquery ajax. But I donot know why It is returning me whole page html including the result. can anybody please tell me about it. In firefox console Its show me response of page html including php result. But In jquery code console.log does not hit.
Here is jquery code
function getprofile()
{
$.ajax({
url: 'Userpage/get_profile',
//data: {'title': title}, change this to send js object
type: "post",
dataType: 'json',
data: {'userid': 1},
success: function(data) {
console.log(data);
}
});
}
My php code
<?php
if (!defined('BASEPATH'))
exit('No direct script access allowed');
class Userpage extends CI_Controller
{
function __construct()
{
parent::__construct();
$this->load->helper('url');
$this->load->helper('form');
$this->load->library("session");
$this->load->model("Userpage_model");
$this->load->view('Userpage_view');
}
public function index()
{
}
public function get_profile()
{
$data = array();
$post_id = $this->input->post('userid');
$data['comments'] = $this->Userpage_model->get_profile($post_id);
echo json_encode($data['comments']);
exit;
}
}
?>
Please review the code and tell me where I am going wrong
Thanks
Use exit
public function get_profile()
{
$data = array();
$post_id = $this->input->post('userid');
$data['comments'] = $this->Userpage_model->get_profile($post_id);
echo json_encode($data['comments']);
exit; // use exit here
}
EDIT
PHP uses a special function called header() for setting properties of the page during rendering.
you need to return from your function, using exit is fine but it's not a good practice
public function get_profile()
{
$data = array();
$post_id = $this->input->post('userid');
$data['comments'] = $this->Userpage_model->get_profile($post_id);
return json_encode($data['comments']);
}
You are using CI. From this ajax call:
$.ajax({
url: 'Userpage/get_profile',
success: function(data) {
console.log(data);
}
});
you expect an ajax call is being made to get_profile action inside Userpage controller, that probably will return:
{
"comments": [
{ ... },
{ ... },
{ ... },
...
]
}
which will be logged in browser console.
But you get unexpected result, right?
I think, your ajax call results in error. To prove this, modify your ajax call:
$.ajax({
url: 'Userpage/get_profile',
success: function(data) {
console.log(data);
},
error: function(jqXHR, textStatus, errorThrown) {
// add this function to logs error
console.log(textStatus + ': ' + errorThrown);
}
});
Now, if the ajax call results in error, you can see the error in browser console. I am pretty sure you will get error: Not Found in browser console.
You are using CI, the URL will be something like:
http://<something>/index.php/site/index
In this page, if you make ajax call with url Userpage/get_profile, what the browser really does is make ajax call to:
http://<something>/index.php/site/index/Userpage/get_profile
instead of what you expect:
http://<something>/index.php/Userpage/get_profile
To solve this, you must change the value of url in your ajax call, to point the correct URL above.
By using CI, the absoulte URL above can be generated with the help of site_url() function:
site_url('Userpage/get_profile')
I usually print this URL somewhere in HTML, and retrieve it from javascript during ajax call.
I am new to Spring with AJAX.
My requirement is to check whether email is registered or not, when user clicks on check availability. I am successfully making calls to the controller class but the response is displayed in the browser instead of in same jsp and not entering the success block. I am unable to find the problem.
Below is sample code:
#Controller
public class CheckAvailbiltyEmailController {
#RequestMapping(value="/check",method = RequestMethod.GET)
public ModelAndView viewAjaxEmail(Map model){
return new ModelAndView("CheckEmailAvaliblity");
}
#RequestMapping(value="/check", method=RequestMethod.POST)
public #ResponseBody String ajaxEmailCheck(#RequestParam("email") String email){
System.out.println("Email is:"+email);
return "Please carry on registration";
}
}
My Ajax code:
$.ajax({
type:"POST",
url:"/check"
success:function(data){
alert("Inside Success");
$('#resp email').html(data);
}
error: function(e){
}
});
You need to specify the data you want to send to the server,
The controller will accept "email" as the RequestParam.
Do it like the following snippet :
$.ajax({
type:"POST",
url:"/check",
data: {"email":"email#to.check.com"},
success:function(responseData){
alert("Inside Success");
$('#resp email').html(responseData);
},
error: function(e){
}
});