jQuery Success Function doesn't alert - php

here is the problem, I have the following function
$(document).ready(function() {
$('#selectTypeDD').change(function() {
var type = $("#selectTypeDD option:selected").text();
changeType(type);
alert(type);
});
});
The alert prints out pub when I choose city of my drop down menu.
changeType is this function
function changeType(type)
{
$.ajax
({
type: 'GET',
url: 'webservice.php',
data: {type: type},
success: function(response, textStatus, XMLHttpRequest)
{
alert("SUCCESS");
}
});
}
I get this result here in Firebug
pub[{"name":"The Master Builder","lon":"-1.34532","lat":"50.9303"},{"name":"Goblets","lon":"-1.40455","lat":"50.9088"},{"name":"Rat and Parrot","lon":"-1.40442","lat":"50.9085"},{"name":"The Victory Inn","lon":"-1.31415","lat":"50.8588"},{"name":"The King and Queen","lon":"-1.31356","lat":"50.8586"}
The list goes on and on, but I think those are the most important ones. The problem is now, that I want to do something with the result and it didn't work, so I tested why it is so, and typed in the alert("SUCCESS") in the success-function. But it doesn't even print out the alert. Why? What am I doing wrong? The werbservice runs without problems. When I open my site localhost/blabla/webservice.php?type=pub it prints out everything. So what could be the problem?
Here is the party of my webservice
else if(isset($_GET['type']))
{
$type = $_GET['type'];
echo $type;
if($result = $mysqli->query("SELECT name, lon, lat FROM pointsofinterest WHERE type = '".$type."'"))
{
$tempArray = array();
while($row = $result->fetch_assoc())
{
$tempArray = $row;
array_push($array, $tempArray);
}
echo json_encode($array);
}
}

change your
success: function(response, textStatus, XMLHttpRequest)
to
success: function(response)

Related

Ajax success function not working with json answer

If I set dataType to 'json' and inside my PHP file I print whatever I want (event a letter), success function works, but if I don't print anything else besides the JSON I need, stops working. I can't handle my data with something else printed, because it turns the answer into HTML, instead of JSON. I'm able to see in Network -> Answer the JSON file (only when I don't print anything else beside the JSON), but I don't know why I can't even do an alert in success function when that is the case.
This is my ajax, which only works because I'm printing 'true' on the server:
$(document).on("click", "#btnEditarInstructor", function(event) {
event.preventDefault();
let rfc = $(this).attr("value");
$.ajax({
type: "POST",
url: "../utils/ajax/ajax_consulta_instructor.php",
data: {
rfc: rfc,
},
dataType: "json",
succes: function(response) {
if (response == true) {
// alert(response);
}
},
error: function(request, status, error) {
var val = request.responseText;
alert("error" + val);
alert(status);
alert(error);
},
});
})
This is my PHP code:
$rfc = $_POST['rfc'];
$sql = "SELECT * FROM instructores WHERE rfc = '$rfc'";
$sql_run = mysqli_query($con, $sql);
while ($row = mysqli_fetch_array($sql_run)) {
echo "true";
$datos['status'] = 'OK';
$datos['nombre'] = $row['nombre'];
$datos['apellidos'] = $row['apellidos'];
$datos['email'] = $row['email'];
$datos['tipo_promotor'] = $row['tipo_promotor'];
echo json_encode($datos);
}
By the way, with that code, I get this error on the alert:
SyntaxError: JSON.parse: unexpected non-whitespace character after JSON data at line 1 column 5 of the JSON data
I'm using jQuery 3.6.0 (https://code.jquery.com/jquery-3.6.0.js)
If you're returning JSON, you can only echo the JSON once, not each time through the loop.
If there can only be one row, you don't need the while loop. Just fetch the row and create the JSON.
You also can't echo anything else, so the echo "true"; lines are breaking it.
And your code is wide open to SQL-injection. You should use a prepared statement with a parameter, which I've shown how to do.
$rfc = $_POST['rfc'];
$stmt = $con->prepare("SELECT * FROM instructores WHERE rfc = ?");
$stmt->bind_param("s", $rfc);
$stmt->execute();
$sql_run = $stmt->get_result();
$datos = [];
if($row = mysqli_fetch_array($sql_run)){
$datos['status'] = 'OK';
$datos['nombre'] = $row['nombre'];
$datos['apellidos'] = $row['apellidos'];
$datos['email'] = $row['email'];
$datos['tipo_promotor'] = $row['tipo_promotor'];
}
echo json_encode($datos);
$(document).on("click", "#btnEditarInstructor", function (event) {
event.preventDefault();
let rfc = $(this).attr("value");
$.ajax({
type: "POST",
url: "../utils/ajax/ajax_consulta_instructor.php",
data: {
rfc: rfc,
},
dataType: "json",
success: function (response) {
if (response == true) {
// alert(response);
}
},
error: function (request, status, error) {
var val = request.responseText;
alert("error" + val);
alert(status);
alert(error);
},
});

Save Ajax JQuery selector in an array

I'm very new with Ajax and I need help to store the data from an Ajax request into an array. I looked at answers here at the forum, but I'm not able to solve my problem.The Ajax response is going into $('#responseField').val(format(output.response)) and I'm want store "output.response" into an array that can be used outside of the Ajax. I tried to declare a variable outside of the Ajax and call it later, but without success. I'm using $json_arr that should get the data. How do I do to get the data from the Ajax and store it in a variable to be used outside of the Ajax? This variable will an array that I can access the indexes.
function sendRequest(postData, hasFile) {
function format(resp) {
try {
var json = JSON.parse(resp);
return JSON.stringify(json, null, '\t');
} catch(e) {
return resp;
}
}
var value; // grade item
$.ajax({
type: 'post',
url: "doRequest.php",
data: postData,
success: function(data) { //data= retArr
var output = {};
if(data == '') {
output.response = 'Success!';
} else {
try {
output = jQuery.parseJSON(data);
} catch(e) {
output = "Unexpected non-JSON response from the server: " + data;
}
}
$('#statusField').val(output.statusCode);
$('#responseField').val(format(output.response));
$("#responseField").removeClass('hidden');
data = $.parseJSON(output.response)
$json_arr=$('#responseField').val(format(output.response));
},
error: function(jqXHR, textStatus, errorThrown) {
$('#errorField1').removeClass('hidden');
$("#errorField2").innerHTML = jqXHR.responseText;
}
});
}
window.alert($json_arr);
let promise = new Promise(function(resolve, reject) {
$.ajax({
type: 'post',
url: "doRequest.php",
data: postData,
success: function(data) { //data= retArr
var output = {};
if(data == '') {
output.response = 'Success!';
} else {
try {
output = jQuery.parseJSON(data);
} catch(e) {
output = "Unexpected non-JSON response from the server: " + data;
}
}
$('#statusField').val(output.statusCode);
$('#responseField').val(format(output.response));
$("#responseField").removeClass('hidden');
data = $.parseJSON(output.response)
resolve(format(output.response));
},
error: function(jqXHR, textStatus, errorThrown) {
$('#errorField1').removeClass('hidden');
$("#errorField2").innerHTML = jqXHR.responseText;
}
});
});
promise.then(
function(result) { /* you can alert a successful result here */ },
function(error) { /* handle an error */ }
);
The issue is you are calling asynchronously.
You call the alert synchronously, but it should be called asynchronously.
A little snippet to help you see the difference:
// $json_arr initialized with a string, to make it easier to see the difference
var $json_arr = 'Hello World!';
function sendRequest() {
$.ajax({
// dummy REST API endpoint
url: "https://reqres.in/api/users",
type: "POST",
data: {
name: "Alert from AJAX success",
movies: ["I Love You Man", "Role Models"]
},
success: function(response){
console.log(response);
$json_arr = response.name;
// this window.alert will appear second
window.alert($json_arr);
}
});
}
sendRequest();
// this window.alert will appear first
window.alert($json_arr);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Ajax timed update issue

Simply I have a menu bar with an animated notification badge made by CSS and implemented by SPAN class on the HTML. this badge should show the count of new messages and disappear if that count is 0. I need to check that every 1 second but with no luck.
my js:
<script type="text/javascript">
function removeAnimation(){
setTimeout(function() {
$('.bubble').removeClass('animating')
}, 200);
}
setInterval(function() {
$.ajax({
type: 'GET',
url: 'models/bubble.php',
data: 'html',
success: function(response){
document.getElementById("bub").innerHTML=response;
document.getElementById("bub").className = "bubble";
}
error: function(response) {
document.getElementById("bub").className = "hidden";
});
}
}, 1000);
</script>
my php (working and tested):
<?php
require_once("db.php");
$receiver = $this_user
$isnew = 1;
$stmt = $mysqli->stmt_init();
if ($stmt->prepare("SELECT * FROM messenger
WHERE receiver = ? AND isnew = ? ORDER BY timestamp")) {
$stmt->bind_param("si", $receiver,$isnew);
$stmt->execute();
$stmt->store_result();
$ttlrows = $stmt->num_rows;
$stmt->close();
}
echo $ttlrows;
?>
any help?
Below works for me. You need to call the function inside success again as setTimeout/setInterval will call the function only once after the delay you mentioned
setTimeout('pullNewMessageCount()', 100);
function pullNewMessageCount() {
var url = 'PHP Url';
$.ajax({
url: url,
dataType: 'html',
data:{
"whatever data you want to send, skip it if not require",
},
type: 'POST',
success: function(latestCount) {
setTimeout('pullNewMessageCount()', 100);// Important comment (this what you need to do)
},
error: function(jqXHR, textStatus, errorThrown) {
}
});
}

How to handle json response from php?

I'm sending a ajax request to update database records, it test it using html form, its working fine, but when i tried to send ajax request its working, but the response I received is always null. where as on html form its show correct response. I'm using xampp on Windows OS. Kindly guide me in right direction.
<?php
header('Content-type: application/json');
$prov= $_POST['prov'];
$dsn = 'mysql:dbname=db;host=localhost';
$myPDO = new PDO($dsn, 'admin', '1234');
$selectSql = "SELECT abcd FROM xyz WHERE prov='".mysql_real_escape_string($prov)."'";
$selectResult = $myPDO->query($selectSql);
$row = $selectResult->fetch();
$incr=intval($row['votecount'])+1;
$updateSql = "UPDATE vote SET lmno='".$incr."' WHERE prov='".mysql_real_escape_string($prov)."'";
$updateResult = $myPDO->query($updateSql);
if($updateResult !== False)
{
echo json_encode("Done!");
}
else
{
echo json_encode("Try Again!");
}
?>
function increase(id)
{
$.ajax({
type: 'POST',
url: 'test.php',
data: { prov: id },
success: function (response) {
},
complete: function (response) {
var obj = jQuery.parseJSON(response);
alert(obj);
}
});
};
$.ajax({
type: 'POST',
url: 'test.php',
data: { prov: id },
dataType: 'json',
success: function (response) {
// you should recieve your responce data here
var obj = jQuery.parseJSON(response);
alert(obj);
},
complete: function (response) {
//complete() is called always when the request is complete, no matter the outcome so you should avoid to recieve data in this function
var obj = jQuery.parseJSON(response.responseText);
alert(obj);
}
});
complete and the success function get different data passed in. success gets only the data, complete the whole XMLHttpRequest
First off, in your ajax request, you'll want to set dataType to json to ensure jQuery understands it is receiving json.
Secondly, complete is not passed the data from the ajax request, only success is.
Here is a full working example I put together, which I know works:
test.php (call this page in your web browser)
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
// Define the javascript function
function increase(id) {
var post_data = {
'prov': id
}
$.ajax({
'type': 'POST',
'url': 'ajax.php',
'data': post_data,
'dataType': 'json',
'success': function (response, status, jQueryXmlHttpRequest) {
alert('success called for ID ' + id + ', here is the response:');
alert(response);
},
'complete': function(jQueryXmlHttpRequest, status) {
alert('complete called');
}
});
}
// Call the function
increase(1); // Simulate an id which exists
increase(2); // Simulate an id which doesn't exist
</script>
ajax.php
<?php
$id = $_REQUEST['prov'];
if($id == '1') {
$response = 'Done!';
} else {
$response = 'Try again!';
}
print json_encode($response);

can't get AJAX get call to work even so the code seems correct

Ok fixed jQuery code with help of others on stack overflow
$(document).ready(function() {
$(".note").live('click',function() {
$("#note_utm_con").show();
$("#note_utm_nt").html("<img src='http://www.ajaxload.info/images/exemples/4.gif' />");
$.ajax({
type: "GET",
url: "view.php",
data: "ajax=1&nid=' + parent.attr('id').replace('record-','')",
success: function(html){
$("#note_utm").html(html);
$("#note_utm_nt").html("");
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
$("#note_utm_nt").html("<img src='http://www.ajaxload.info/images/exemples/4.gif' /> Error...");
}
});
});
});
The PHP code for view.php
include 'object/db.class.php';
if($_GET['ajax'] == '1') {
#make a call to my sql to fetch some sort of ID
$nid = $_GET['nid'];
$q = mysql_query("SELECT * FROM `notice` WHERE nid = '".$nid."'");
$a = mysql_fetch_array($q);
$nid = stripslashes($a['nid']);
$note = stripslashes($a['note']);
$type = stripslashes($a['type']);
$private = stripslashes($a['private']);
$date = stripslashes($a['date']);
$author = stripslashes($a['author']);
$note_viewer .= <<<NOTE_VIEWER
<h2>By: $author</h2> - <h2>$date</h2>
<br/>
<p>$note</p>
<p>Request: $private</p>
NOTE_VIEWER;
echo $note_viewer;
}
The AJAX seems to be working now as it gives me Error...
concerning the docu of jQuery, you attach an event with the live() method. In your code, you define the click-method of node twice, I think: once with the live-attaching-stuff and once with note.click(). So it is not clear what to do when clicking or better when node is clicked, the click-event is defined :-) You define two different actions when note is clicked... try this one:
$(document).ready(function() {
$(".note").live('click',function() {
$("#note_utm_con").show();
$("#note_utm_nt").html("<img src='http://www.ajaxload.info/images/exemples/4.gif' />");
$.ajax({
type: "GET",
url: "view.php",
data: "ajax=1&nid=' + parent.attr('id').replace('record-',''),
success: function(html){
$("#note_utm").html(html);
$("#note_utm_nt").html("");
}
});
});
});
So what exactly is it doing? and What element is not visible? Your AJAX call isnt even using the response. If I understand your logic correctly, it should be...
$.ajax({
type: "GET",
url: "view.php",
data: "ajax=1&nid=' + parent.attr('id').replace('record-',''),
success: function(html){
$("#note_utm").html(html);
$("#note_utm_nt").html(html);
}
});
the "html" variable in the success function is the response from the php script.

Categories