No alert from Ajax call - javascript

I´m trying to alert some data from a Ajax call. Can anyone spot what I am doing wrong?
PHP
while($row = $stmt->fetch()){
echo json_encode($row);
}
echo "Done!";
Result from Json_encode / Network Preview
{"flakId":"21098-10_flak-2"}{"flakId":"21098-10_flak-1"}Done!
JS
if(chosenObjNr){
alert('I CAN see this alert')
$.ajax({
url:'php/update.php',
type: 'POST',
data: 'chosenObjNr=' + chosenObjNr,
dataType: 'json',
error: function (data){ alert("failed, i can see this!");},
success: function(data){
alert('I cannot see this alert!');
alert(data);
var data0;
data0 = data[0];
alert(data0);
var falkId;
flakId = data[0];
alert(flakId);
console.log(data);
}
});
};
RESULT
No alert and nothing in the console.

The problem is, that the success part of the ajax never will run. You defined the dataType as a json, so it expecting json. Your PHP is echos 2 json and an unwanted string.
So, to check what is your error add the fail function as Sina sad in the comment:
if (chosenObjNr) {
alert('I CAN see this alert')
$.ajax({
url: 'php/update.php',
type: 'POST',
data: 'chosenObjNr=' + chosenObjNr,
dataType: 'json',
}).done(function (data) {
alert('I cannot see this alert!');
//Do what you want to do here
}).fail(function (msg) {
alert('An error occured: ' + msg.statusText);
});
}
And, if you want to fix your .php remove the echo 'Done'; part, and add your records to an array, and when its done, encode it to json:
$return = array();
while ($row = $stmt->fetch()) {
$return[] = $row;
}
echo json_encode($return);

Related

unable to parse xml data with AJAX + Wordpress

Ok, I am officially stumped. I have been trying to find why my calls for specific items in a PubMed xml data file are not working... I can execute this one with my current coding:
$test = (string)$id_json->PubmedArticle->MedlineCitation->PMID;
but if I try to get a variable that is in a deeper array, it does not return a value. I have even tested with console.log(data) and I get my PMID returning but not my other, deeper values in the XML file. For example;
$test = (string)$id_json->PubmedArticle->MedlineCitation->Article->Journal->ISSN;
returns nothing for data in console.log(data)
Here is my function in wordpress:
function get_abstract(){
$id = $_POST['abstractid'];
$pubmed_api_call = 'https://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?db=pubmed&retmode=xml&rettype=abstract&id='.$id;
$id_wpget = wp_remote_get($pubmed_api_call, array('timeout' => 20));
if( is_wp_error( $id_wpget ) ) {
echo "Error Contacting PubMed, please refresh page and try again";
die();
}
$id_xml = wp_remote_retrieve_body($id_wpget);
$id_json = simplexml_load_string($id_xml);
$test = (string)$id_json->PubmedArticle->MedlineCitation->Article->Journal->ISSN;
if($test === ""){
echo "NOTHING";
die();
}
echo $test;
die();
}
and here is my javascript AJAX call:
jQuery(document).ready(function() {
jQuery('.reference_header').click(function(e) {
jQuery(this).find("i").toggleClass("arrow-down arrow-up");
jQuery(this).nextUntil('.reference_header').slideToggle('fast');
var abstractid = jQuery(this).data("id");
e.preventDefault();
jQuery.ajax({
url: get_abstract.ajaxurl,
type: 'POST',
dataType: 'json',
data: {
abstractid: jQuery(this).data("id"),
action: 'get_abstract'
},
success : function(data){
jQuery('.'+abstractid).html("TESTING: "+data);
console.log(data);
}
});
});
});
I cannot find out why it doesnt work... any help is greatly appreciated.
So I figured out the solution to the issue... you need to pass the string text as a json object to AJAX for it to read properly...
working code:
PHP:
echo json_encode(array("result" => "$test"));
die();
AJAX:
success : function(data){
jQuery('.'+abstractid).html("TESTING: "+data.result);
console.log(data.result);
}

How to get POST data using Jquery AJAX

I am trying to POST simple data using AJAX. My HTML code is
<input type="text" value="myvalue" id="sweet" name="sweet">
<button type="submit" id="mybtn-1">
My JQuery code is
$('#mybtn-1').click(function(){
var newSweet = $('#sweet').val();
if($.trim(newSweet) !== '')
{
$.ajax({
url:"../test_chat.php",
method:"POST",
data:{sweet:newSweet},
dataType:"text",
success:function(data){
$('#test_wrap').load("../test_chat.php").fadeIn("slow");
alert('Success');
}
});
}
});
And my test_chat.php code is
<?php
echo $_POST["sweet"];
echo 'hello';
?>
I want to echo the POST data in a div with the name "test_wrap". The problem is after clicking the button, I can only echo "hello" on the page.
I know it's happening because the load function is reloading the PHP file but I am looking for a solution so that I can show the POST data on my page.
You could return the data directly from your test_chat.php file after the post request, no need for double request here, return data like :
<?php
echo $_POST["sweet"];
echo 'hello';
?>
Then append it to the div #test_wrap like :
$('#mybtn-1').click(function(){
var newSweet = $('#sweet').val();
if($.trim(newSweet) !== ''){
$.ajax({
url:"../test_chat.php",
method:"POST",
data:{sweet:newSweet},
dataType:"text",
success:function(data){
$('#test_wrap').html(data).fadeIn("slow");
alert('Success');
}
});
}
});
Hope this helps.
You don't need to echo it with PHP, you can display it directly from the jQuery success callback:
$.ajax({
url: "../test_chat.php",
method: "POST",
data:{
sweet: newSweet
},
success: function(data) {
$('#test_wrap').load("../test_chat.php").fadeIn("slow");
if (data !== null && data !== undefined) {
alert('Success');
// Here "data" is whatever is returned from your POST
$("#some_content").html(data);
}
}
});
do ajax request of this way in js file:
$.ajax({
data: {keys: values}/*keys you need to post (sweet: newsweet)*/
, type: 'post'
, dataType: 'json'
, url: './php/someFile.php'
, error: function (jqXHR, status, err) {
console.log(jqXHR, status, err);
}
, success: function (response) {
/*use response to innerHTML into a div here*/
}
});
use echo json_encode in php:
<?php
echo json_encode($_POST["sweet"] /*or some value from function in php*/);/*of this way, you can return a response
from server to client, echo just print something, but does not return...*/
?>

Create array from PHP SQL query and pass it to ajax

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);
}
});

Using ajax to send a JS variable, but how can I use PHP variables afterwards to my main file?

How can I use some PHP variables from the ajax-send.php to the index.php file? I use AJAX as shown below. Do I have to replace AJAX with something else?
index.php
$.ajax({
type: 'POST',
url: 'ajax-send.php',
data: { one: hash },
success: function(data) {
}
});
ajax-send.php
$token = $_POST['one'];
echo "ok"
$toINDEX = "use this in index.php"
Try this
Ajax
$.ajax({
type: 'POST',
url: 'ajax-send.php',
data: { one: hash },
success: function(data) {
var response = data;
//alert(data);To see what you have received from the server
}
});
PHP
if(isset($_POST['one'])){
$token = $_POST['one'];
echo "ok";
$toINDEX = "use this in index.php";
die();
}
In PHP just echo variable or json_encode array. In JS do the following:
var result = $.ajax({
url: this.fileUrl,
type: "POST",
data: data,
async: false,
dataType: 'json'
}).responseText;
Your vaiable is fully accessable.
take the variables in php sessions
//On page 1(ajax-send.php)
session_start();
$_SESSION['token'] = $_POST['one'];
//On page 2(index.php)
session_start();
$var_value = $_SESSION['token'];
You can simply echo the variable and then access it via javascript inside the success function.
But a better approach would be to json_encode the data. The beauty of this is that it will help you to pass multiple values/variables in a single echo. So
PHP
.
..
if(<all is okay>)
{
$toINDEX = "use this in index.php"
$data['result'] = 'ok';
$data['msg'] = $toINDEX;
$data['some_other_value'] = 'blah blah';
// notice how I'm able to pass three values using this approach
}
else
{
$data['result'] = 'notok';
}
echo json_encode($data);
Javascript
$.ajax({
type: 'POST',
url: 'ajax-send.php',
data: { one: hash },
dataType:'json',
success: function(data) {
if(data.result == 'ok')
{
console.log(data.msg);
console.log(data.some_other_value);
}
else
{
// something went wrong
}
}
});
The important thing to note here is dataType:'json' which tells the function to expect the returned data in json format.
EDIT:
As per you comment, you could do this
$toINDEX = "use this in index.php";
// now use the variable here itself
mysql_query("SELECT * FROM table WHERE column = '$toINDEX'");
.
.
if(<all is okay>)
{
$data['result'] = 'ok';
$data['msg'] = 'anything you would like to show the user';
$data['some_other_value'] = 'blah blah';
// notice how I'm able to pass three values using this approach
}
else
{
$data['result'] = 'notok';
}
echo json_encode($data);

Ajax code for cross-domain request fails

I need to send data through AJAX to another domain. I use the following code which alerts error.
$(document).ready(function(){
$('p').click(function(){
$.ajax({
url:"http://tarjom.ir/demo/javascript/get.php?callback=?",
dataType: 'jsonp', // Notice! JSONP <-- P (lowercase)
type : "GET",
data: "username=mostafa&url="+window.location,
success:function(json){
// do stuff with json (in this case an array)
alert(json);
},
error:function(){
alert("Error");
},
});
});
});
I want each click on <p> tag be reported to a file called get.php on another server. This file would save the click record+the time of the event into a DB.
Due to development stage, I have added an alert(); to the code, to alert whatever received from get.php, but I ONLY get alerted 'error'.
Here is the get.php code:
<?php
if($_POST['username'] != "")
{
$site = new mysqli('localhost', 'tarjomir_mostafa', 'securefiction1916', 'demo');
$stmt = $site->prepare("INSERT INTO demo (url) VALUES(?)");
$stmt->bind_param('s', $a);
$stmt->execute();
$stmt->close();
echo json_encode("success");
}
?>
try this:
$(function(){
$.ajax({
url:"http://tarjom.ir/demo/javascript/get.php",
dataType: 'jsonp',
type : "GET",
data: "username=mostafa&url="+window.location,
jsonpCallback:"myFunction"
})
.done(function(json){
// do stuff with json (in this case an array)
alert('done ' + json);
})
.fail(function(){
alert("Error");
});
});
And the response for http://tarjom.ir/demo/javascript/get.php be something like:
myFunction({"data": "mydata" })

Categories

Resources