jQuery's JSON Request - javascript

I'm trying to send an AJAX request to a php file, and I want the php file to respond with a JSON object, however the AJAX function is continually failing when declare that I specifically want JSON returned. Any help will greatly be appreciated.
this is my ajax function
function getMessages(){
$.ajax({
type: 'POST',
url: 'viewInbox',
dataType: 'json',
success: function(msg){
//var content = data.substr(0, data.indexOf('<'));
populateMessages(msg);
},
error: function(){
alert("ERROR");
}
});
}
and this is the relevant code for the php file
$message_links[] = array();
.....
while($run_message = mysql_fetch_array($message_query)){
$from_id = $run_message['from_id'];
$message = $run_message['message'];
$user_query = mysql_query("SELECT user_name FROM accounts WHERE id=$from_id");
$run_user = mysql_fetch_array($user_query);
$from_username = $run_user['user_name'];
$message_links[] = array("Hash" => "{$hash}", "From" => "{$from_username}", "Message" => "{$message}");
// is that not valid json notation???
}
}
echo json_encode( $message_links, JSON_FORCE_OBJECT);
//$arr = array("a" => "1", "b" => "2");
//echo json_encode($arr);
UPDATE:
Well, I ended up switching the dataType request to 'html' and I am now able to actually access these values via JSON, however, I would still like to know why the php file was not returning correct JSON notation. Any insight would be awesome, cheers.
function getMessages(){
$.ajax({
type: 'POST',
url: 'viewInbox',
dataType: 'html',
success:function(msg){
var content = msg.substr(0, msg.indexOf('<'));
msg = JSON.parse(content);
populateMessages(msg);
},
error: function(xhr, textStatus, errorThrown) {
alert(errorThrown);
alert(textStatus);
alert(xhr);
}
});
}
function populateMessages(data){
var out = '';
var json;
for (var i in data){
var my_string = JSON.stringify(data[i],null,0);
json = JSON.parse(my_string);
alert(json.Hash);
out += i + ': ' + my_string + '\n';
}
alert(out);
}

You need to set the header as json type before your echo in PHP:
header('Content-Type: application/json');

Related

how to return data php to ajax

I didn't understand how to get data from php by ajax.
Here is my javascript code :
$('#value').on('keyup', function(event){
event.preventDefault();
var form_data = $(this).serialize();
var sending = $("#sending").val();
var value = $("#value").val();
var recevied = $("#recevied").val();
$.ajax
({
type: "POST",
//async: true,
dataType : 'json',
url: "{{url('/calculate')}}",
data: {_token:"{{csrf_token()}}", sending:sending,value:value,recevied:recevied}
}).done( function(data){
//swal("Good job!", "Your personal information has been successfully updated!", "success")
$("#mainvalue").val(data)
console.log('Ajax was Successful!')
console.log(data)
}).fail(function(xhr, textStatus, error){
console.log(textStatus)
console.log(error)
});
});
here is my php code :-
public function index(Request $request)
{
$sending = $request->get('sending');
$value = $request->get('value');
$recevied = $request->get('recevied');
$relations = DB::table('tbl_relations')
->where('exid1',$sending)
->where('exid2',$recevied)
->select()
->first();
if ($relations != null) {
$rate = $relations->exrate2;
$mainvalue = $sending * $rate;
return $rate;
}else{
return $request->all();
}
}
How to restore $rate value into #mainvalue ?
well i guess you can try the following inside the php code :
$post = file_get_contents('php://input');

Don't alert AJAX

I'm trying to get result and alert it if the solicitude was successful or not on the PHP file, it worked (because changed the results) but the AJAX didn't show alerts (No error and no "true")
js:
function addentrys() {
var nwentry = {};
el = document.getElementById('addname').value;
eldmn = document.getElementById('adddomain').value;
nwentry.name = el;
nwentry.domain = eldmn;
$.ajax({
type: 'POST',
url: 'api/domain',
dataType: 'json',
data: nwentry
}).done(function(data) {
alert(data);
});
}
php:
$app->post('/domain', function () {
$jsonContents = file_get_contents('data/data.json');
$name = $_POST['name'];
$domain = $_POST['domain'];
$data = json_decode($jsonContents, true);
$last_item = end($data);
$last_item_id = $last_item['id'];
$data[] = array(
'name' => $name,
'domain' => $domain,
'id' => $last_item_id+1
);
$json = json_encode($data);
file_put_contents('data/data.json', $json);
return true;
});
The result is probably not in JSON format, so when jQuery tries to parse it as such, it fails. You can catch the error with error: callback function.
You don't seem to need JSON in that function anyways, so you can also take out the dataType: 'json' row.

PHP not catching data from Ajax Jquery

Im trying to pass data from using Ajax and PHP on server side. the php file is not catching the data sent through Ajax.
the code gets the values with jquery and make a long string called data
the jquery code looks like this:
var data = 'ppemail=' + $('#email').val()
+ '&monto_enviar=' + montoEnviarDisp
+ '&monto_pub=' + montoPubDisp
+ '&tasa=' + tasaDisp
+ '&monto_recibir=' + monto_recibirDisp
+ '&banco=' + $('#banco').val()
+ '&receptor=' + $('#receptor').val()
+ '&cuenta=' + $('#cuenta').val()
+ '&cedula=' + $('#cedula').val();
$.ajax({
type: "POST",
url: 'crear_oferta.php',
data: ({data}),
success: function (response) {
alert(response);
}
});
the php file is this:
<?php
session_start();
require_once 'dbconfig3.php';
var_dump($_POST);
try {
$userID = $_SESSION['userSession'];
$ppemail = $_POST['ppemail'];
$monto_e = $_POST['monto_enviar'];
$monto_p = $_POST['monto_pub'];
$tasa = $_POST['tasa'];
$monto_rec = $_POST['monto_recibir'];
$banco = ($_POST['banco']);
$receptor = ($_POST['receptor']);
$cuenta = ($_POST['cuenta']);
$cedula = ($_POST['cedula']);
/// luego de confirmar hacer el try e insertar
//if(isset($_POST['btnferta'])){
//$password = md5($upass);
$bid_date = date('Y-m-d H:i:s');
$stmt = $db_con->prepare("INSERT INTO ofertas(uid,email_pp,nombre_receptor,banco_receptor,cuenta_receptor,cedula_receptor,monto_enviar,monto_publicar,tasa,monto_recibir,fecha)
VALUES(:userid, :emailpp, :nombre, :banco, :cuenta, :cedula, :monto_e, :monto_p, :tasa, :monto_r, :fecha)");
$stmt->bindParam(":userid", $userID);
$stmt->bindParam(":emailpp", $ppemail);
$stmt->bindParam(":nombre", $receptor);
$stmt->bindParam(":banco", $banco);
$stmt->bindParam(":cuenta", $cuenta);
$stmt->bindParam(":cedula", $cedula);
$stmt->bindParam(":monto_e", $monto_e);
$stmt->bindParam(":monto_p", $monto_p);
$stmt->bindParam(":tasa", $tasa);
$stmt->bindParam(":monto_r", $monto_rec);
$stmt->bindParam(":fecha", $bid_date);
$stmt->execute();
echo 'ok';
} catch (PDOException $ex) {
echo $ex->getMessage();
}
?>
why the $_POST is not getting any data? Thanks for the help!
You should set data to an object. This ensures that the URL parameters will be properly encoded; otherwise, you need to call encodeURIComponent on any parameter that could contain special characters.
var data = {
'ppemail': $('#email').val(),
'monto_enviar': montoEnviarDisp,
'monto_pub': montoPubDisp,
'tasa': tasaDisp,
'monto_recibir': monto_recibirDisp,
'banco': $('#banco').val(),
'receptor': $('#receptor').val(),
'cuenta': $('#cuenta').val(),
'cedula': $('#cedula').val()
};
Then you shouldn't wrap it in another object when calling $.ajax:
$.ajax({
type: "POST",
url: 'crear_oferta.php',
data: data,
success: function(response) {
alert(response);
}
});
It looks like you're trying to pass a string as an object property. Change your $.ajax options:
$.ajax({
type: "POST",
url: 'crear_oferta.php',
data: data,
success: function(response) {
alert(response);
}
});

Fetching PHP Data with Javascript and assign it to an array

I've got a php script with collects data from a server and displays it in an array and after that as a json with the function.
echo json_encode($result);
Now I want to access that array with my javascript and display it. It should be saved in a var as an array so it should look like:
data = [ "xxxx" , "ssss",];
But I guess I can simply put in my function which gets the array data instead so it'd be:
data = myfunction ;
What I've tried so far:
function reqListener () {
console.log(this.responseText);
}
var oReq = new XMLHttpRequest(); //New request object
oReq.onload = function() {
};
oReq.open("get", "http://myserver.com/myscript.php", true);
oReq.send();
and
function getdata(url) {
jQuery.ajax(
{
type: "GET",
url: "http://myserver.com/myscript.php/",
dataType: "text",
success: function (response) {
var JSONArray = jQuery.parseJSON(response);
connsole.log(JSONArray);
}
});
}
But none seems to work and I get displayed 'undefined' instead of my arrays.
Would be really great if somebody has some ideas on that and can help me out.
Edit:
Since we are getting nowhere here's my php code:
<?php
error_reporting(0);
$html = file_get_contents("url here");
$dom = new DOMDocument();
$dom->loadHTML($html);
$tbodyRows = $dom->getElementsByTagName( 'tbody' )
->item( 0 ) // grab first tbody
->getElementsByTagName( 'tr' );
$result = array();
foreach( $tbodyRows as $tbodyRow )
{
$result[] = $tbodyRow->getElementsByTagName( 'td' )
->item( 2 ) // grab 3rd column
->nodeValue;
}
echo json_encode($result);
?>
Try this code:
function getdata(url) {
console.log('Started');
jQuery.ajax({
type: "GET",
url: "http://myserver.com/myscript.php",
dataType: "text",
error: function (xhr) {
console.log('Error',xhr.status);
},
success: function (response) {
console.log('Success',response);
}
});
}
Open the browser's console, and let me know about its contents. If you don't see Error or Success, your code isn't actually executing
I have done a similar thing earlier. I will describe it and I wish it will help you.
In the following code (get_categories.php), I am retrieving data from the database and add them to an array. Then return it by encoding as a JSON.
$sql = "SELECT category_name FROM category;";
$dataArray = [];
$result = $connection->query($sql);
if ($result) {
while ($row = $result->fetch_assoc()) {
$dataArray[] = $row;
}
echo json_encode($dataArray);
}
Then in my Javascript code, I can get the data as follows.
$.ajax({
url: "/get_categories.php",
type: "GET",
dataType: "json",
success: function (categories) {
for (var i = 0; i < categories.length; i++) {
console.log(categories[i]);
}
},
error: function (jqXHR, textStatus, errorThrown) {
// Error handling code
}
});

Send variable to php via ajax

I'm trying to send a input value to php via ajax but I can't seem to get this right. I'm trying to create a datatable based on the user input.
This is my code:
<input class="form-control" id="id1" type="text" name="id1">
My javascript code:
<script type="text/javascript">
$(document).ready(function() {
var oTable = $('#jsontable').dataTable(); //Initialize the datatable
$('#load').on('click',function(){
var user = $(this).attr('id');
if(user != '')
{
$.ajax({
url: 'response.php?method=fetchdata',
data: {url: $('#id1').val()},
dataType: 'json',
success: function(s){
console.log(s);
oTable.fnClearTable();
for(var i = 0; i < s.length; i++) {
oTable.fnAddData([
s[i][0],
s[i][1],
s[i][2],
s[i][3],
s[i][4],
s[i][5],
s[i][6],
s[i][7]
]);
} // End For
},
error: function(e){
console.log(e.responseText);
}
});
}
});
});
</script>
My php script:
<?php
$conn = pg_connect(...);
$id1 = $_POST["id1"];
$result = pg_query_params($conn, 'SELECT * FROM t WHERE id1 = $1 LIMIT 20', array($id1));
while($fetch = pg_fetch_row($result)) {
$output[] = array ($fetch[0],$fetch[1],$fetch[2],$fetch[3],$fetch[4],$fetch[5],$fetch[6],$fetch[7]);
}
echo json_encode($output);
?>
I don't know a lot of js but my php is correct i test it. So i guess the problem is in the javascript code.
The problem is, my datatable is not being created based on the user input.
Thank you!
change
data: {url: $('#id1').val()},
to:
type: 'POST',
data: {id1: $('#id1').val()},
However the problem might be bigger. You might not be getting the correct data from PHP. You can debug by adding the error option to your ajax() call, like this:
$.ajax({
url: 'response.php?method=fetchdata',
type: 'POST',
data: {id1: $('#id1').val()},
dataType: 'json',
success: function(s){
},
error: function (xhr, status, errorThrown) {
console.log(xhr.status);
console.log(xhr.responseText);
}
});
Then check your browser's Console for the output, this should give you some type of error message coming from PHP.
My assumption is that since you are using dataType: 'json', the ajax request expects JSON headers back, but PHP is sending HTML/Text. To fix, add the correct headers before echoing your JSON:
header('Content-Type: application/json');
echo json_encode($output);

Categories