AJAX "success" not called - javascript

All of this worked before, I haven't changed anything and now it doesn't. I have two elements named with id="live_title" and id="live_game". AJAX purpose is to update them.
My jQuery:
var tytul = function getTitle(){
$.ajax({
type : 'GET',
dataType: 'json',
url : 'ajax/getTitle.php',
success : function(data) {
for (var prop in data) {
$('#live_'+prop).html(data[prop]);
}
}
});
}
setInterval( tytul, 10000 );
AJAX response as seen in Firebug:
{"title":"Some title title...","game":"Name of the game"}
PHP Code sending stuff:
header('Content-Type: application/json');
// creating assoc array here
echo json_encode(array( 'title' => $title, 'game' => $game));
JavaScript console is empty.
When I visit ajax/getTitle.php in my browser, there is no error and displayed is the same thing as normally in Firebug. Response gives correct header (it's "Content-Type: application/json").
I've added
error : function(data) {
alert(data);
}
To my .ajax() function. It pops [object Object]. for alert(data.title) or alert(data['title']) it's undefined

Try to console your ajax response first and then step forward to further operations
var tytul = function getTitle(){
$.ajax({
type : 'GET',
dataType: 'json',
url : 'ajax/getTitle.php',
success : function(data) {
//if successfull
console.log(data);
},
error:function(data){
//if error
console.log(data);
}
});
}
setInterval( tytul, 10000 );

Related

Ajax and PHP, post request not working

So I am trying to post some some data from one PHP file to another PHP file using jquery/ajax. The following code shows a function which takes takes data from a specific div that is clicked on, and I attempt to make an ajax post request to the PHP file I want to send to.
$(function (){
$(".commit").on('click',function(){
const sha_id = $(this).data("sha");
const sha_obj = JSON.stringify({"sha": sha_id});
$.ajax({
url:'commitInfo.php',
type:'POST',
data: sha_obj,
dataType: 'application/json',
success:function(response){
console.log(response);
window.location.replace("commitInfo");
},
error: function (resp, xhr, ajaxOptions, thrownError) {
console.log(resp);
}
});
});
});
Then on inside the other php file 'commitInfo.php' I attempt to grab/print the data using the following code:
$sha_data = $_POST['sha'];
echo $sha_data;
print_r($_POST);
However, nothing works. I do not get a printout, and the $_POST array is empty. Could it be because I am changing the page view to the commitInfo.php page on click and it is going to the page before the data is being posted? (some weird aync issue?). Or something else? I have tried multiple variations of everything yet nothing truly works. I have tried using 'method' instead of 'type', I have tried sending dataType 'text' instead of 'json'. I really don't know what the issue is.
Also I am running my apache server on my local mac with 'sudo apachectl start' and running it in the browser as 'http://localhost/kanopy/kanopy.php' && 'http://localhost/kanopy/commitInfo.php'.
Also, when I send it as dataType 'text' the success function runs, but I recieve NO data. When I send it as dataType 'json' it errors. Have no idea why.
If anyone can help, it would be greaat!
You don't need to JSON.stringify, you need to pass data as a JSON object:
$(function() {
$(".commit").on('click', function() {
const sha_id = $(this).data("sha");
const sha_obj = {
"sha": sha_id
};
$.ajax({
url: 'commitInfo.php',
type: 'POST',
data: sha_obj,
dataType: 'json',
success: function(response) {
console.log(response);
},
error: function(resp, xhr, ajaxOptions, thrownError) {
console.log(resp);
}
});
});
});
And on commitInfo.php, you have to echo string on json format
=====================================
If you want to redirect to commitInfo.php you can just:
$(".commit").on('click',function(){
const sha_id = $(this).data("sha");
window.location.replace("commitInfo.php?sha=" + sha_id );
});

Ajax post request is appending sent data to the returned JSON

I have an ajax call like so:
$.ajax({
url: '/assets/functions.php',
type: 'POST',
data: {
"functionCall": "get-uploads",
"type": type
},
dataType: 'json',
success: function (data, textStatus) {
console.log("done");
console.log(data);
console.log(textStatus);
},
error: function(textStatus, errorThrown) {
console.log("uh oh");
console.log(textStatus);
console.log(errorThrown);
}
});
Which gets sent to and handled with this:
switch($_POST['functionCall']) {
.
.
.
case "get-uploads":
$type = $_POST['type'];
$getUploads = "SELECT * FROM pp_uploads WHERE type = '$type';";
$docArray = array();
while($row = mysql_fetch_assoc($documents)) {
$docArray[] = $row;
}
echo json_encode($docsArray);
}
When I run this I get a parsing error, which from what I understand means that the returned data isn't being returned as JSON. So I changed the dataType to html, and I see that the returned data in the console is:
[{"id":"35","filename":"fdgsdf","path":"ConfiguratorTreeDiagram.pdf","type":"resources"},{"id":"36","filename":"gsrewg","path":"dhx_advertising.pdf","type":"resources"}]Array
(
[functionCall] => get-uploads
[type] => resources
)
So it looks like the data I passed into the call is being appended to the end of my data. How do I prevent that from happening?
It looks like you might be doing a print_r somewhere on an Array variable?

AJAX jquery json sending array to php

I'm trying to send a associative array via AJAX $.post to php. Here's my code:
var request = {
action: "add",
requestor: req_id,
...
}
var reqDetails = $("#request_details").val();
switch(reqDetails){
case 1:
request[note] = $("#note").val();
break;
...
}
if(oldRequest()){
request[previousID] = $("old_id").val();
}
$('#req_button').toggleClass('active');
$.post("scripts/add_request.php", {
request_arr: JSON.stringify(request)
}, function(data){
console.log(data);
$('#req_button').toggleClass('active');
}, 'json');
And i'm simply trying to read the received data in my php script:
echo json_decode($_POST["request_arr"]);
But it's not working. I'm a newbie to js, I can't figure out what I'm doing wrong.
Check below link for your reference
Sending an array to php from JavaScript/jQuery
Step 1
$.ajax({
type: "POST",
url: "parse_array.php",
data:{ array : JSON.stringify(array) },
dataType: "json",
success: function(data) {
alert(data.reply);
}
});
Step 2
You php file looks like this:
<?php
$array = json_decode($_POST['array']);
print_r($array); //for debugging purposes only
$response = array();
if(isset($array[$blah]))
$response['reply']="Success";
else
$response['reply']="Failure";
echo json_encode($response);
Step 3
The success function
success: function(data) {
console.log(data.reply);
alert(data.reply);
}
You are already using "json" as dataType, so you shouldn't apply 'stringify' operation on your data.
Instead of request_arr: JSON.stringify(request), can you try request_arr: request directly?

"[Error] ReferenceError: Can't find variable: data" when trying to get JSON data with AJAX / jQuery request

I am getting the error "[Error] ReferenceError: Can't find variable: data" when trying to get JSON data with AJAX / jQuery request.
I have an index.html file which loads jQuery and tries to get data from an ajax.php file.
CONTENT of index.html
$.ajax({
url : 'ajax.php',
type : 'POST',
data : data,
dataType : 'json',
success : function (result) {
alert(result['ajax']);
},
error : function () {
alert("error");
}
});
CONTENT of ajax.php
$someVariable = array(
'ajax' => 'Hello world!'
);
echo json_encode($someVariable);
Accessing ajax.php through the browser displays the data correctly:
{"ajax":"Hello world!"}
What am I missing? Thanks.
I dont know which error you are refering to, but I'm guessing you are enable to read the response of your json response in the success callback, if thats the case you will need to modify the response headers
$data = /** whatever you're serializing **/;
header('Content-Type: application/json');
echo json_encode($data);
You haven't defined data variable
If you not post any data try this:
$.ajax({
url : 'ajax.php',
type : 'POST',
dataType : 'json',
success : function (result) {
alert(result['ajax']);
},
error : function () {
alert("error");
}
});

Send array with ajax request to php

I created array like this ["9", "ques_5", "19", "ques_4"]. Now I want to send it from JS to PHP but I'm not getting proper results. My JS code is:
$(".button").click(function(e) {
e.preventDefault();
$.ajax({
type : 'post',
cache : false,
url : 'test/result.php',
data : {result : stuff},
success: function(resp) {
alert(resp);
}
});
});
In the above code stuff is an array which contains records. How can I send this array with above code and then in PHP I want to process this array like ques_5 is the key and 9 become the value for that key.
You can pass the data to the PHP script as a JSON object. Assume your JSON object is like:
var stuff ={'key1':'value1','key2':'value2'};
You can pass this object to the php code in two ways:
1. Pass the object as a string:
AJAX call:
$.ajax({
type : 'POST',
url : 'result.php',
data : {result:JSON.stringify(stuff)},
success : function(response) {
alert(response);
}
});
You can handle the data passed to the result.php as :
$data = $_POST["result"];
$data = json_decode("$data", true);
//just echo an item in the array
echo "key1 : ".$data["key1"];
2. Pass the object directly:
AJAX call:
$.ajax({
type : 'POST',
url : 'result.php',
data : stuff,
success : function(response) {
alert(response);
}
});
Handle the data directly in result.php from $_POST array as :
//just echo an item in the array
echo "key1 : ".$_POST["key1"];
Here I suggest the second method. But you should try both :-)
If you want to send key value pairs, which is what I am seeing, it would be better to use a PHP JSON library (like this one... http://php.net/manual/en/book.json.php)
Then you can send actual key value pairs, using JSON format like...
{"ques_5" : "19", "ques_4": "19"}
Try this
var array = ["9", "ques_5", "19", "ques_4"];
console.log(array.join(","));
above code will output string with comma separated like 9,ques_5,19,ques_4then paste it to ajax call.
And then in php explode that string.
Other possible solutions.
First
var obj = { 'item1': 'value1', 'item2': 'value2' };
$.ajax(
{
type: 'post',
cache: false ,
url: 'test/result.php',
data: { result : JSON.stringify(obj) },
success: function(resp)
{
alert(resp);
}
});
Second
var a = $.JSON.encode(obj);
$.ajax(
{
type: 'post',
cache: false ,
url: 'test/result.php',
data: { result : a },
success: function(resp)
{
alert(resp);
}
});
In PHP File
<?php
$json = $_POST["data"]
var_dump(json_decode($json));
?>
You can send the array in json format to the php and then use json_decode function to get back the array like
In ajax call you have to send json for that you need to first make array of the values so that you get it in right form
so that you json look like {"ques_5":"9","ques_4":19}
and use in ajax call
data: JSON.stringify(`your created json`),
contentType: "application/json; charset=utf-8",
dataType: "json",
IN PHP it look like
<?php
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
var_dump(json_decode($json));
?>
I would like to share a complete example that works for me in order to avoid making each JavaScript function for each PHP function
// on the HTML side a simple JavaScript call from a link
<a href="javascript:CargaZona('democonllamada', 'tituloprin', {'key1':'value1','key2':'value2'})" >test</a>
<div id='tituloprin' >php function response here!</div>
// on JavaScript side
function CargaZona(fc, div, params) {
var destino = "#" + div;
var request = $.ajax({
url : "inc/phpfunc.php",
type : "POST",
data : {
fc : fc,
params : JSON.stringify(params)
},
dataType : "html"
});
request.done(function (msg) {
$(destino).html(msg);
});
request.fail(function (jqXHR, textStatus) {
alert("Request failed: " + textStatus);
});
}
// on phpfunc.php page
<?php
$params = "{'key1':'value1','key2':'value2'}";
$fc = 'def';
if (isset($_POST['fc'])) { $fc = $_POST['fc']; }
if (isset($_POST['params'])) { $params = $_POST['params']; }
switch ($fc) {
default:
call_user_func($fc,$params);
}
function democonllamada($params) {
$params = json_decode("$params", true);
echo "ok llegaron".$params['key1'];
}
?>

Categories