I am using ajax with masonry
Ajax code: This ajax is used to get data from
$.ajax({
type: "get",
url: "some.php",
dataType: "text",
success: function(data) {
if (data && data.length > 0) {
$items = $(data);
$grid.append( $items )
.masonry('appended', $items);
$(this).find(".loading").hide();
}
}
Php Part: This is just a small or sufficient part of php file to understand the problem
$b= "sv";
echo "asjdgsajd";
echo "a";
echo $b;
now i am getting everything correctly but i want to use say value of $b for setting a attribute value and also other values as content but how can i particularly get value of $b?
Thankyou
Change the dataType to json.
$.ajax({
type: "get",
url: "some.php",
dataType: "json",
success: function(data) {
//data will hold an object with your response data, no need to parse
console.log('Do whatever you want with ' + data.b + '.');
}
In some.php do the following:
$response =array(
'b' => "sv",
'a' => "asjdgsajd",
'c' => "a"
);
echo json_encode($response);
echo $b;
The items of the associative array will end up as properties of a javascript object, that you can use in your success callback (or done function as success is deprecated).
Try using json and change your php to send the json response that way you can send more content and access them on client side as you need it.
PHP Script :
$outArr=array("b"=>"sv","content1"=>"asjdgsajd","content2"=>"a");
$jsonResponse=json_encode($outArr);
echo $jsonResponse;
In AJAX function you can access your data like this:
$.ajax({
type: "get",
url: "some.php",
dataType: "text",
success: function(data) {
if (data && data.length > 0) {
data=$.parseJSON( data ); //parse response string
b=data.b;//value of b
content1=data.content1;//value of content1
$("#exampleDiv").attr("id",b).html(content1); //set the attribute and content here for an example div
}
}
})
Related
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;
I'm trying to get my results from a SQL query into an array in javascript. I'm trying the following:
PHP:
$query = mysqli_query($connection, "select a, b, c from table");
$result_a = array();
$result_b = array();
$result_c = array();
while($row = mysqli_fetch_array($query)) {
$result_a[] = $row['a'];
$result_b[] = $row['b'];
$result_c[] = $row['c'];
}
echo json_encode(array('a'=>$result_a,'b'=>$result_b, 'c'=>$result_c ));
javascript:
$.ajax({
type: "POST",
url: "http://mywebsite.com/data.php",
data: dataString3,
cache: false,
error: function(){},
success: function(data){
alert (data.a);
alert (data.b);
alert (data.c);
},
});
return false;
The PHP arrays have the data I'm looking for but the alerts in javascript are undefined. Any help would be appreciated.
In PHP you echo data in json format json_encode(array('a'=>$result_a,'b'=>$result_b, 'c'=>$result_c ));
So if you want to use the json as an object directly in the ajax success function, you need tell the ajax call "You are expecting a json object coming bakc!";
So you should modified js code to this:
$.ajax({
type: "POST",
url: "http://mywebsite.com/data.php",
data: dataString3,
cache: false,
dataType : "json", // <------here, auto parse json for you
error: function(){},
success: function(data){
alert (data.a);
alert (data.b);
alert (data.c);
}
});
Or in the success function, manually parse json before use;
$.ajax({
type: "POST",
url: "http://mywebsite.com/data.php",
data: dataString3,
cache: false
error: function(){},
success: function(data){
var obj = jQuery.parseJSON(data); // <---- here, manual parse
alert (obj.a);
alert (obj.b);
alert (obj.c);
}
});
I have php on my server that is handling the AJAX call and returning a JSON object like so:
$dataArray = array('order_id'=>$order_id, 'response'=>'Sucessfully Added');
header('Content-type: application/json');
echo json_encode( $dataArray );
This is my AJAX call:
$('.add').ajaxForm({url: this.href, type:'post',
data: this.serialize,
dataType: 'json',
success: function(responseText){
var p = JSON.parse(responseText);
alert(p.response);
$('.popupContainer').hide();
}
});
In FireBug I can see that it reaches the line that begins with 'var p' just fine. In fact, at this point, FB tells me that the responseText is exactly what I want it to be: {"order_id":"182","response":"Sucessfully Added"}. But at that point it suddenly stops, so I must be missing something here.
There is no need to do manual parsing, since the dataType is set as json the response will be automatically parsed
$('.add').ajaxForm({
url: this.href,
type: 'post',
data: this.serialize,
dataType: 'json',
success: function (p) {
alert(p.response);
$('.popupContainer').hide();
}
});
jQuery Form
dataType
'json': if dataType == 'json' the server response will be evaluted and
passed to the 'success' callback, if specified
success
responseText or responseXML value (depending on the value of the
dataType option).
I have this ajax send two variables to php, it sends the 2nd one trough fine but the first variable is always reported by php as NULL, i console log the javascript variable before sendign it and it does return an array of strings so I have no idea what is going on.
console.log(givenSpots);
jQuery.ajax({
type: "POST",
url: "includes/map/update.php",
data: {'spots': givenSpots, 'thisEvent': givenEvent},
dataType: "json",
cache: false,
async: false,
success: function(result){
response = result;
}
});
The receiving PHP is:
session_start();
if(isset($_SESSION["adminid"])){
$currentUser = $_SESSION["adminid"];
} else if(isset($_SESSION["vartotojasid"])){
$currentUser = $_SESSION["vartotojasid"];
} else $currentUser = false;
if ($currentUser) {
file_put_contents("update.txt", "0 ");
include_once "../../../../../../connection.php";
$event = $_POST["thisEvent"];
if (isset($_POST["spots"])) {
$data = $_POST["spots"];...
you need to encode your array to json before sending it to php, you can use
JSON.stringify(postDataArray)
or using jquery $.post :
$.post(yourURL, {
data : $.toJSON(postDataArray)
}, function(response){
//do something with your response
}
);
than just decode it with php and use it on your server
Hi All I have the following code to pass a JS variable using AJAX as seen below:
function buttonCallback(obj){
var id = $(obj).attr('id');
$.ajax({
type: "POST",
url: "/project/main/passid",
data: { 'id': id },
success: function(msg){
window.alert(msg);
}
});
}
if I put an alert box in I can see the object id is successfully getting grabbed. however if in php I want to simply return the variable - I am getting a null has anyone got any ideas:
heres my PHP function (I am using Codeigniter):
public function passid(){
$courseId = $this->input->post('id');
echo $courseId;
}
EDIT: the success alert box appears - but appears blank and that is my issue I am hoping to see the ID
1. Can you make sure id equals something by doing this:
function buttonCallback(obj){
var id = $(obj).attr('id');
alert( id ); // What does it alert?
$.ajax({
type: "POST",
url: "/project/main/passid",
dataType: "json",
data: { 'id': id },
success: function(msg){
window.alert(msg.id);
}
});
}
2. Your javascript looks good... Can you try this instead to see if it works:
JS
function buttonCallback(obj){
var id = $(obj).attr('id');
$.ajax({
type: "POST",
url: "/project/main/passid",
dataType: "json",
data: { 'id': id },
success: function(msg){
window.alert(msg.id);
}
});
}
PHP
public function passid(){
$courseId = $this->input->post('id');
$response = array( "id" => $courseId );
header('Content-Type: application/json');
echo json_encode( $response );
}
3. If this does not work, can you try and rename from id to something like poopoo, just to make sure id is not taken and being weird?
4. Can you check what the network response is of your ajax request - Go to developer toolbar and goto network section, make sure you hit the record/play button. then send your request off. When you see your request come up in the network list, check the "details" of it and goto response.