I have this ajax request,
$.ajax({
url : '<?php echo current_url(); ?>',
data : "txtKeywords="+$("#txtKeywords").val()+"&search=Search For Item",
type : 'POST',
dataType : 'JSON',
success : function(html)
{
console.log(html);
}
});
return false;
I get the following in my console,
[{"productId":"5","productTitle":"Small Brasserie Dining Table","productPath":"small-brasserie-dining-table\/","productRangeId":"6","productSecondaryRangeId":"0","productTypeId":"2","productRefNo":"0080","productShortDesc":"","productBestSeller":"0","productFeatured":"0","productIsSet":"0","productPrice":"275","productSavingType":"none","productSavingPrice":"0","productSavingMessage":"","productDimWidth":"90","productDimHeight":"74","productDimDepth":"90","productTechnical":"Powder coated aluminium frame with welded joints.","productTemplateId":"5","productMetadataTitle":"","productMetadataKeywords":"","productMetadataDescription":"","productBandingColour":"grey","productActualPrice":"275","rangeTitle":"Dining","parentRangeTitle":"Aegean","fullRangePath":"aegean\/dining\/","fullProductPath":"aegean\/dining\/small-brasserie-dining-table\/","hasImage":"0"}]
But when I do something like,
alert(html.productTitle)
all I get is undefined?
What am I doing wrong?j
Is it because your html variable is an array? Wouldn't you have to do...
alert(html[0].productTitle);
Try html[0].productTitle, I have run into this problem a few times.
Try using Jquery's JSON ajax function instead of the $.ajax it will parse the JSON for you.
http://api.jquery.com/jQuery.getJSON/
try doing something like this:
alert(html.d); // this will show the result of your ajax call
i don't know what the reason is to use the property 'd' but if you can take a look at your result, use a debug tool to see what data is getting back your ajax call.
if you want convert your JSON string to and object, you can do with the following code:
var respuesta = jQuery.parseJSON(html.d);
Related
My PHP is outputting data like this:
$data['full_feed'] = $sxml;
$data['other_stuff']= $new;
echo json_encode($data);
So, in my jQuery, I'm doing this.
$.ajax({
url: 'untitled.php',
type: 'GET',
success: function(data) {
console.log(data['full_feed']);
});
This comes back undefined. So does console.log(data.full_feed). I'm getting back from PHP a valid JSON object, but missing how I can "parse" it correctly.
Parse "data" parameter in response with jQuery.parseJSON function. Then use parsed.full_feed value. Like below:
$.ajax({
url: 'untitled.php',
type: 'GET',
success: function(data) {
data = jQuery.parseJSON(data);
console.log(data.full_feed);
});
You can do like #tilz0R said or for your example to work you need to tell the browser you are sending a json response. So need to set content type header like
header('Content-Type: application/json');
echo json_encode($data);
to see what the server is returning do console.log(typeof data). If its a string you need to parse it. if its an object, it is already parsed.
Also you can put dataType:'json' in your ajax call to let jquery know you are excepting a json response.
I make a $.post request to submit data and return invalid data. Here is the $.post request:
$('#submitAll').click(function(){
$.post("php/entries/submitAndReload.php", {array : dataObject.dataArray}, function(data){
alert(data); // alerts: "[[“0”, “0”,””,””, “0”, “0”, “0”, “0”,”No Style”]]"
dataObject.dataArray = data;
$.post("php/entries/stageArea.php", {array : dataObject.dataArray}, function(data){
$('#stageArea').html(data);
});
});
});
dataObject.dataArray is a double array and alert(data) alerts what looks like the proper format for the subsequent $.post request, but the output from the 2nd $.post request looks like I pass in the following array:[[ "[" ]]. The first field gets a "[" and no other fields get data.
I'm not sure what's going on here and how to properly store the returned data into dataObject.dataArray
What's going on here?
Correct this line:
dataObject.dataArray = data;
To this:
dataObject.dataArray = JSON.parse( data );
You need to parse JSON, untill parsing it is just a string.
Add dataType argument to $.post.
When set as 'json' jQuery knows to parse it to object/array from json string
$.post(url, postData, function(data){
// handling code
alert($.type(data)); //"array"
},'json');
If you set proper content Type header at server also it helps
Reference: $.post docs
I'm trying to implement some ajax function in my php website. I basically know how to use jQuery, but for some reason, the returned value is always empty when I alert() it. This is the code I use:
PHP:
if(_POST('ajax'))
{
$ajax_action = _POST('ajax');
if($ajax_action == "gwonline")
{
return 'test';
}
}
JS / jQuery:
$.ajax({
url: './include/ajax.php',
data: {ajax: 'gwonline'},
type: 'post',
success: function(output) {
alert(output);
}
});
I debugged it and it does call the file with an ajax request and returns the value, but not received apparently.. What am I doing wrong here? I sincerely don't know..
The response should be pass by echo function, not return. So you must use echo 'test'; instead of return 'test';
Don't forget using $ sign in front of every variable in php.
Im on project to make an app with codeigniter but i got stuck, when i want to pass same variable outside field via ajax into controller i got error the variable is not defined.
this is a example.
$("#form_status_update").submit(function() {
var date = new Date().toString();`
$.ajax({
type: 'POST',
url: "<?php echo base_url()?>socialcontroller/setdate",
data:date,
success: function(data) {
window.location.href = "<?php echo base_url()?>socialcontroller/ssetdate";
},
error: function(xhr, ajaxOptions, thrownError) {
alert(thrownError); //throw any errors
}
});
});
after passing some var i want to insert into my database.
and my question is how to pass a variable not field into controller via ajax thanks, i already search on google but i didnt geting the right answer :)
`
The line data:date, is wrong. You are passing up a number on the querystring and not a key/value pair.
It needs to be
data: {date : date},
or
data: "date=" + encodeURIComponent(date),
From jQuery Docs:
data
Type: PlainObject or String or Array
Data to be sent to the
server. It is converted to a query string, if not already a string.
It's appended to the url for GET-requests. See processData option to
prevent this automatic processing. Object must be Key/Value pairs. If
value is an Array, jQuery serializes multiple values with same key
based on the value of the traditional setting (described below).
Here is the code that help you with your problem
You can just adapt it with your code and it should work !
<script>
$(document).ready(function(){
$("button").click(function(){
var myDate = new Date();
$.ajax({
// Send with POST mean you must retrieve it in server side with POST
type: 'POST',
// change this to the url of your controller
url:"index.php",
// Set the data that you are submitting
data:({date:myDate}),
success:function(result){
// Change here with what you need to do with your data if you need of course
$("#div1").html(result);
}});
});
});
</script>
<body>
<div id="div1">
<p>Today date here</h2>
</div>
<button> Get Date< /button>
</body>
</html>
and your PHP code can be something like this !
<?php
// This line of code should get your data that you are sending
$data = $_POST['date'];
/// This code was just for checking purpose that it is returning the same value through ajax
$arr = array(
'receive_date'=>$data,
);
echo json_encode($arr);
I think this code can work with must of MVC framework if you are setting your controller URL as url parameter. Check also the Framework documentation about getting the data through POST !
your selector $("form_status_update") doesn't match a class or an id of the DOM.
and it doesn't match an html element either.
so this for sure gives you some (extra) problems.
couldnt you have tried running the date function at the php controller youre calling from the ajax function.
i dont see any specific reason as to why you have to send in date as the input parameter from the javascript function.
remove the date var and data field.
and in your php controller.
when you get the controller called.
run a date function in the php code and use the date from there.
I'm having a problem reading JSON; my PHP server encodes an object created with the stdClass, then sends this object on my Ajax asynchronous script. I tried to alert the object and the
representation is like this:
alert(prova) //Gives {"idProva":"3","name":"test"}
Now if the variable name is prova, how can I read the value 3?
I tried using prova.idProva, but it doesn't work.
try parsing json into a object
var json = '{"idProva":"3","name":"test"}',
obj = JSON.parse(json);
alert(obj.idProva);
i hope this will help
In ajax all add dataType:'json'
$.ajax({url: '',
dataType: 'json',
type: 'GET',
success: function (prova) {
alert(prova.idProva);
}
);
This may help you,
var data = {"idProva":"3","name":"test"}
console.log(data['idProva']);