I need to read data from my web page with jquery + ajax
This is my function:
public function getvalueshahr()
{
if($_POST['ostan']!=0){
$db= JFactory::getDbo();
$query=$db->getQuery(TRUE);
$query->select('id,title')->from('#__categories')->
where($db->quoteName('parent_id').'='.$db->quote($_POST['ostan']));
$db->setQuery($query);
$res=$db->loadObjectList();
echo $db->getErrorMsg();
echo json_encode($res);}
}
I can read data with c# like this:
But my ajax method is not working. Here is the method:
$.ajax({
type: "POST",
url: "www.mysite.net/index.php?task=shahrestan.getvalueshahr",
data: "{ostan=77}",
dataType: "json",
success: function (result)
{
var d = $.parseJSON(result);
$.each(d, function (i, field)
{
$("#output").append("id: " + field.id + " title: " +
field.title+"br/>");
});
},
error: function (e)
{
alert("error:" + e.responseText);
}
});
The method returns nothing.
You're sending a string instead of an object in your ajax-request. Try changing :
data: "{ostan=77}"
to
data: { ostan: 77 }
And you should set the content type before echoing the results in PHP:
header('Content-Type: application/json');
echo json_encode($res);
Now you don't need $.parseJSON in the JS-code. You will get a json-object straight away.
First of all you send a wrong data to the server. You have to rewrite part of your code like this:
data: {ostan: 77},
or
data: "ostan=77",
The second problem is you get a result as a json object on the success method, but you try to parse it again to the json object. So remove this line from your code:
var d = $.parseJSON(result);
Finally your ajax function should looks like this:
$.ajax({
type: "POST",
url: "www.mysite.net/index.php?task=shahrestan.getvalueshahr",
data: {ostan: 77},
dataType: "json",
success: function (result)
{
$.each(result, function (i, field)
{
$("#output").append("id: " + field.id + " title: " +
field.title+"br/>");
});
},
error: function (e)
{
alert("error:" + e.responseText);
}
});
If you are loading data from you mysql-database you eventually have to convert these data because it is not stored as utf-8 converted. This piece of code convert given object to UTF-8: mb_convert_encoding(database-entry,'UTF-8');
Related
I am posting an Ajax call to a PHP function but all the data passed is "UNDEFINED". When I debugged the JQuery, the value seems work. The undefined is at server side. PHP side.
$('.js-checkout-shipping-submit').on('click', function(e) {
$.ajax({
// Change the URL to the right one
url: 'index.php?route=checkout/checkout/updateShippingAddress',
type: 'post',
dataType: 'json',
data: 'firstName:' + $(' .js-checkout-firstName').val() +
',lastName:' + $('.js-checkout-lastName').val() +
',address:' + $('.js-checkout-address').val() +
',zipcode:' + $('.js-checkout-zipcode').val() ,
success: function(data) {
if(data['status'] === "pass"){
console.log("success");
}
if(data['status'] === "fail") {
console.log("fail");
}
},
error: function(data) {
}
});
e.preventDefault();
});
public function updateShippingAddress(){
$firstName=$this->request->post['firstName'];
$lastName=$this->request->post['lastName'];
$address=$this->request->post['address'];
$zipCode=$this->request->post['zipcode'];
}
You are posting the JSON object as string, please try this
data: { // making the data to become object
firstName : $('.js-checkout-firstName').val(),
lastName : $('.js-checkout-lastName').val(),
address : $('.js-checkout-address').val(),
zipcode : $('.js-checkout-zipcode').val()
},
success: function(data) {
...
If you are getting undefined as value of post params, maybe there is jQuery selector problem.
Try to log $('.js-checkout-firstName').val() and see what you get and make shre an Input is present with class .js-checkout-firstName
You have to pass your request parameter in json format for ajax.
so your data parameter value is be like,
data: {'firstName' : $('.js-checkout-firstName').val(),'lastName' : $('.js-checkout-lastName').val(),'address' : $('.js-checkout-address').val(),'zipcode' : $('.js-checkout-zipcode').val()},
success: function(data) {
I have a JSON code that send a form to on PHP file and I want to use data in PHP
the code is:
// add button .click
$('a.add').click(function(){
$('#loader').show();
var url = "/yadavari/test.php?";
var json_text = JSON.stringify($("form[name='add']").serialize(), null, 2);
var datas = JSON.parse(json_text);
ajx = $.ajax({
url: url,
type: 'post',
data: datas,
dataType: 'json',
success: function(r) {
$('#loader').hide();
if(r.r != 0){
alert("ok");
jsmsalert($('#alert_add'),'success',r.m);
apendtable(r.r);
$("tr").removeClass("odd");
$("tr.viewrow:odd").addClass("odd");
$("tr.editrow:odd").addClass("odd");
$('td[colspan="7"]').remove();
}
else{
jsmsalert($('#alert_add'),'error',r.m,0);
}
},
error: function(request, status, err) {
$('#loader').hide();
jsmsalert($('#alert_add'),'error','error msg');
alert( "ERROR: " + err + " - " );
}
Now I want to fetch data from this JSON code in my PHP page.
I searched but every body just said that $string='{"name":"John Adams"}'; and so.
But I dont know that how can I have this $string in my PHP.
You should have something like:
<?php
echo $_POST["INPUTNAME"];
?>
Care about this, it suffers from security injection.
You need to call the php json_decode function on the returned string. This will convert it into an associative array:
$json2array = json_decode($json_text);
echo $json2array['name']; // "John Adams"
I am trying to use jQuery sortable and then save the changes to the database, however before I even get to updating the database I have something strange going on that I can't fathom. If I log the serialised data to the console, I get all items in the 'list' but if I echo out the json encoded array from the php script I only get one item - confused.com.
The jquery at the moment is:
$('#sortable-list').sortable({
//handle : '.handle',
update : function () {
var order = $(this).sortable('serialize');
var table = $(this).parent().attr('id');
console.log(order);
$.ajax ({
type: "POST",
url: templateDir + "/inc/changeSortOrder.php",
data: "order=" + order + "&sort=1&sort_table=" + table,
dataType: "json",
cache: false,
success: function(data)
{
console.log(data);
}
});
}
});
The PHP at the moment is:
if (isset($_POST['sort']) && $_POST['sort'] == 1) {
if ($_POST['sort_table'] == 'nationalities') {
$output = array();
$list = parse_str($_POST['order'], $output);
echo json_encode($output);
}
}
The console log gives me:
nationality[]=17&nationality[]=1&nationality[]=47&nationality[]=23&nationality[]=3&nationality[]=4&nationality[]=5&nationality[]=6&nationality[]=7&nationality[]=8&nationality[]=12&nationality[]=10&nationality[]=11&nationality[]=13&nationality[]=14&nationality[]=15&nationality[]=16&nationality[]=18&nationality[]=19&nationality[]=20&nationality[]=21&nationality[]=22&nationality[]=24&nationality[]=25&nationality[]=26&nationality[]=27 etc
And the echo json gives me:
Object {nationality: Array[1]}
nationality: Array[1]
0: "17"
length: 1
So for some reason the full array isn't being passed through to the PHP file and I can't work out why.
Your problem is that you are trying to assign a serialized array, to a single query string parameter, which will yield an incorrect query string. Try passing the serialized list as returned by the plugin serialize method like so:
$.ajax ({
type: "POST",
url: templateDir + "/inc/changeSortOrder.php",
data: order + "&sort=1&sort_table=" + table,
dataType: "json",
cache: false,
success: function(data)
{
console.log(data);
}
});
And then access the passed list in php with:
$list = $_POST['nationality'];
Hi i'm trying to get this with jquery ajax but don't know if i'm doing it correctly...
Really tried everything and basically had to look at jquery.ajax for dummies but still not getting it to work...
function addMix(mix) {
alert(mix);//Here I get my array of int's
var myArr = JSON.stringify(mix);
$.ajax({
type:"POST",
dataType: "json",
url: "add.php",
data: myArr,
success: function(data) {
alert("Success: " + data);
console.log(data);
},
error: function(x,y,z){
alert("Error: " + x + ", " + y + ", " + z);
console.log(x, y, z);
},
complete: function(data){
alert("Complete: " + data);
console.log(data);
}
});
}
the php:
<?php
header('Content-Type: application/json');
include "con.php";
$mix = json_decode($_POST);
foreach($mix as $index => $val){
$temp = array();
foreach($temp[$index] as $key => $value){
array_push($temp, $value);
}
}
$sql = "INSERT INTO mg_test(value)
VALUES('$temp')";
mysql_query($sql);
echo json_encode($temp);
mysql_close($con);
?>
Only thing im getting in return is,
alert(mix) = 2,1,3,2
Success: null
Complete: [object Object]
And I get nothing in the DB...
Could anyone point me in the right direction? What am I doing wrong?
Why do you do JSON.stringify(mix) in the $.ajax call?
You can just put the object / array or what it is there!
Here's a fixed JS:
function addMix(mix) {
$.ajax({
type:"POST",
dataType: "json",
url: "add.php",
data: { mix: mix }, // <--- this
success: function(data) {
alert("Success: " + data);
console.log(data);
...
});
}
And in PHP, you must use
$mix = json_decode($_POST['mix']);
instead of:
$mix = json_decode($_POST);
Also, I am pretty sure this query won't work:
$sql = "INSERT INTO mg_test(value) VALUES('$temp')";
$temp is an array - you will have to build the query of it, not just put it there and hope it will magically work. It won't.
Based on $.ajax documentation:
The data option can contain either a query string of the form
key1=value1&key2=value2, or an object of the form {key1: 'value1',
key2: 'value2'}.
Just skip the stringify and pass the object as it it in the data field.
You are sending data to ajax call wrongly. Donot use JSON.stringify(), instead send request parameters like this.
type:"POST",
dataType: "json",
url: "add.php",
data: { "requestData": mix },
success:function(data){
console.log(data);
}
In PHP file. get this as
$mix = json_decode($_POST['requestData']);
dont alert an object alert("Complete: " + data); it (as you see) returns [Object Object]. so what says the console.log(data);?
If you want to see your objects while using
console.log(data);
It would be much better readable in Google chrome console.
Im trying to retrieve some data from JSON object which holds location information such as streetname, postcode etc. But nothing is being retrieved when i try and put it in my div. Can anybody see where im going wrong with this?
This is my ajax code to request and retrieve the data
var criterion = document.getElementById("address").value;
$.ajax({
url: 'process.php',
type: 'GET',
data: 'address='+ criterion,
success: function(data)
{
$('#txtHint').html(data);
$.each(data, function(i,value)
{
var str = "Postcode: ";
str += value.postcode;
$('#txtHint').html(str);
});
//alert("Postcode: " + data.postcode);
},
error: function(e)
{
//called when there is an error
console.log(e.message);
alert("error");
}
});
When this is run in the broswer is just says "Postcode: undefined".
This is the php code to select the data from the database.
$sql="SELECT * FROM carparktest WHERE postcode LIKE '".$search."%'";
$result = mysql_query($sql);
while($r = mysql_fetch_assoc($result)) $rows[] = $r;
echo json_encode($rows), "\n"; //Puts each row onto a new line in the json data
You are missing the data type:
$.ajax({
dataType: 'json'
})
You can use also the $.getJSON
EDIT: example of JSON
$.getJSON('process.php', { address: criterion } function(data) {
//do what you need with the data
alert(data);
}).error(function() { alert("error"); });
Just look at what your code is doing.
First, put the data directly into the #txtHint box.
Then, for each data element, create the string "Postcode: "+value.postcode (without even checking if value.postcode exists - it probably doesn't) and overwrite the html in #txtHint with it.
End result: the script is doing exactly what you told it to do.
Remove that loop thing, and see what you get.
Does your JSON data represent multiple rows containing the same object structure? Please alert the data object in your success function and post it so we can help you debug it.
Use the
dataType: 'json'
param in your ajax call
or use $.getJSON() Which will automatically convert JSON data into a JS object.
You can also convert the JSON response into JS object yourself using $.parseJSON() inside success callback like this
data = $.parseJSON(data);
This works for me on your site:
function showCarPark(){
var criterion = $('#address').val();
// Assuming this does something, it's yours ;)
codeAddress(criterion);
$.ajax({
url: 'process.php',
type: 'GET',
dataType: 'json',
data: {
address: criterion
},
success: function(data)
{
$("#txtHint").html("");
$.each(data, function(k,v)
{
$("#txtHint").append("Postcode: " + v.postcode + "<br/>");
});
},
error: function(e)
{
alert(e.message);
}
});
}