JSON, jquery, and ajax parsing issue - javascript

Here's my java script file:
$('#addSchoolForm').trigger("reset");
//$(document).ready(function() {
$(function() {
$("#dialog").dialog({
autoOpen: false,
maxWidth:600,
maxHeight: 350,
width: 500,
height: 300,
});
$("#addSchool").on("click", function() {
$("#dialog").dialog("open");
});
$("#addSchoolForm").submit(function(e) {
e.preventDefault();
$("#dialog").dialog("close")
var postData = jQuery(this).serialize();
$.ajax({
type: "POST",
url: "AddSchools.php",
data: postData,
success: function(data){
alert(data); }
});
});
$("#editSchool").submit(function(e) {
e.preventDefault();
var editData = jQuery(this).serialize();
$.ajax({
type: "POST",
url: "GetSchoolID.php",
data: editData,
dataType: 'json',
success: function(data){
var schoolID = $.parseJSON(data);
alert("success");
alert(schoolID.name);
//alert(data["json"]);
//alert(data);
//document.addSchoolForm[sname].value = data[0].name;
//document.addSchoolForm[abbrev].value = data[abbrev];
//document.addSchoolForm[abbrev].value = data[0].abbrev;
}
alert(schoolID.name);
});
//$("#dialog").dialog("open");
});
})
And here's my get schoolID php file
<?php
$school_id = $_POST['school_id'];
$db = mysqli_connect("localhost", "root", "imagroup123","mytrack");
if(!$db){
exit("Error in database connection");
echo("couldn't connect to database");
}
else{
$q = "SELECT * FROM `School` WHERE `SchoolID`='$school_id'";
$schoolresults = mysqli_query($db,$q);
$row = mysqli_fetch_assoc($schoolresults);
$school["name"] = $row['SchoolLong'];
$school["abbrev"] = $row['SchoolShort'];
echo json_encode($school);
}
?>
When I just tested the php file with jsonlint.com I get a correct json object but it's not getting carried through the javascript file. I'm fairly new to this so I'm pretty suck with this problem. I also want to add the data to a form values and then open the dialog form after.

Change:
success: function(data){
var schoolID = $.parseJSON(data);
to:
success: function(schoolID){
because $.ajax automatically calls $.parseJSON() when you specify dataType: 'json'.

Here is the php backend structure that I use all the time:
$query = " SELECT *
FROM school
WHERE SchoolID = $school_id;
$result = mysqli_query($cxn, $query) or die ("could not query database 1");
if (mysqli_num_rows($result) > 0)
{
$row = mysqli_fetch_array($result);
$variablestopass = array
(
'schoolname' => $row['SchoolLong'],
'schoolabbrev' => $row['SchoolShort'],
);
echo json_encode($variablestopass);}
else
{ echo "Error selection id"; }
And here is some js to call it and read it:
$.ajax({
type: 'POST',
url: 'thenameofyourfile.php';
data: {schoolid: schoolid},
dataType: 'json'
})
.done( function() { alert( "Got it!"" );
Do other stuff here
})
.fail(function(jqXHR, textStatus, errorThrown){
console.log(jqXHR.responseText, textStatus, errorThrown);
});

Related

can't get data from json even getting a response on the console

I've been trying to send this information to the js.
$statement = ibase_prepare($sql);
$query = ibase_execute($statement);
while ($row = ibase_fetch_assoc($query)) {
$data[] = $row;
}
echo json_encode($data);
However, when I try to, I get the response, but I can't get the data.
$('document').ready(function (){
$.ajax({
method: "POST",
url: "../Dashboard/php/chart.php",
dataType: "json",
sucess: function (data){
console.log(JSON.stringify(data));
}
});
})
You just have a grammatical error in a word "sucess", the correct word is "success"
$.ajax({
method: "POST",
url: "./data.php",
dataType: "json",
sucess: function (data){ // Here -> success
alert(JSON.stringify(data));
}
});

Cant fetch array from server side

I want to get some data from a php script to my html page. They array $UniqueNames has a value on the server side, but nothing seems to happen when i use json_encode on the html page, the console.log returns an empty array (BilderID). Any suggestions?
code:
<script>
var BilderID = [];
$(document).ready(function (e) {
$('#SubmitBild').on('click', function () {
var form_data = new FormData();
var ins = document.getElementById('Myfilefield').files.length;
for (var x = 0; x < ins; x++) {
form_data.append("Bilder[]", document.getElementById('Myfilefield').files[x]);
}
$.ajax({
url: 'Includes/Bildhantering.php', // point to server-side PHP script
dataType: 'text', // what to expect back from the PHP script
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function (response) {
$('#msg').html(response); // display success response from
},
error: function (response) {
$('#msg').html(response); // display error response from the PHP script
}
});
BilderID = <?php echo json_encode($UniqueNames); ?>
console.log(BilderID);
});
});
</script>
Php:
$UniqueNames = array();
for($i=0;$i<count($file_array);$i++)
{
if($file_array[$i]['error']){
echo $phpFileUploadErrors[$file_array[$i]['error']];
} else {
$extensions = array('jpg','png','gif','jpeg');
$file_ext = explode('.',$file_array[$i]['name']);
$file_ext = end($file_ext);
if (!in_array($file_ext, $extensions)){
echo "Invalid file extension!";
} else {
$fileNameNew = uniqid('', true).".".$file_ext;
$UniqueNames[] = $fileNameNew;
move_uploaded_file($file_array[$i]['tmp_name'], 'Bilder/'.$fileNameNew);
echo $phpFileUploadErrors[$file_array[$i]['error']];
}
}
}
The solution was to remove the datatype specifier, echo out the array in php and receive it inside the success method:
$.ajax({
url: 'Includes/Bildhantering.php', // point to server-side PHP script
//dataType: 'text', // what to expect back from the PHP script
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function (response) {
BilderID = response;
console.log(BilderID);
},
error: function (response) {
console.log("error:");
}
});
i mean, why use "datatype" if javascript figures it out anyway?

Javascript dynamic post ajax/json not sending parameters

I'm trying to send a POST dinamically in a javascript code to a PHP script.
It seems to me that there is something wrong that the data are not sending json data as parameters.
Here is how I generate de json data:
query_string_fn = {};
query_string_fn ["cdinterno"] = cdinterno;
o.row.find("input, select").each(function() {
var val = $(this).val();
var id = $(this).attr('name');
query_string_fn [id] = val;
if (id == 'cdfornecedor_new') {
var cmbSelected = $(this)[0];
value_label = cmbSelected.options[cmbSelected.selectedIndex].text;
} else if (id == 'cdtipo_new') {
var tipocmbSelected = $(this)[0];
tipovalue_label = tipocmbSelected.options[tipocmbSelected.selectedIndex].text;
} else {
$(this).val(val);
}
}).end();
if (value_label.length > 0)
o.row[0].innerHTML = value_label;
if (tipovalue_label.length > 0)
o.row[11].innerHTML = tipovalue_label;
editarFN_Post(query_string_fn);
Here is how I'm sending the data to php. There are some tests commented that I have tested:
function editarFN_Post(query) {
query["action"] = 2;
var data = query;
$.ajax({
type: "POST",
dataType: "json",
url: "funcoesFN_Fornecedor_Produto_post.php",
//processData: false,
//contentType: "application/json; charset=UTF-8",
//contentType: 'application/json; charset=UTF-8',
//data: data,
//data: data.toString(),
data: JSON.stringify(data),
//data: {data: query},
success: function(rsp) {
alert ("Success!");
alert (rsp);
},
failure: function(rsp) {
alert ("Failed...");
alert (rsp);
}
});
}
Here is the PHP code that I check if the parameters have been sent:
header("Content-type: application/json; charset=utf-8");
echo "action=" . $_POST["action"] . "<br>";
foreach ($_POST as $key => $value)
echo "Field ".htmlspecialchars($key)." is ".htmlspecialchars($value)."<br>";
var_dump($_POST);
None of these tests above return data.
Thanks!

AJAX success function not working when the page is load

here is my code in ajax
function loadcountries()
{
var p = document.getElementById("selectCntry");
while(p.firstChild)
{
p.removeChild(p.firstChild);
}
var data = {
action: "loadccc"
};
jQuery.ajax
(
{
type: "POST",
url: "ajax-ows2.php",
dataType: 'json',
async:false,
data:data,
success: function(msg)
{
alert(msg.test);
}
}
);
}
here is my ajax-ows2.php
<?php
$action = $_POST["action"];
include "dbconnect.php";
if($action == "loadccc")
{
$var = $action;
$response_array['test'] = $var;
header('Content-type: application/json');
echo json_encode($response_array);
}
?>
and here is my function call:
<script>
window.onload = loadcountries;
</script>
my ajax way is different. I really have no idea why it is not alerting when the page is load. Im really sure that my ajax-ows2.php is good and im sure that my function call is correct. Can somebody help me with this. This is not a duplicate one. I tried to used asynch:false but still not working.
try this format:
$.ajax({
method: "POST",
contentType: "application/json; charset=utf-8",
data: data,
url: 'ajax-ows2.php',
success: function (data) {
console.log(data);
},
error: function (error){
console.log(error);
}
});
since you are doing POST method, your data parameter must be a stringify, https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify

How to pass form value and individual value throught AJAX?

How to pass a form value and also user id into ajax?
javascript:
jQuery("#DoneBtn").click(function(){
var data = $("#insertsubs_form").serialize();
<?php
$db = JFactory::getDBO();
$user = JFactory::getUser();
?>
var userid = <?php echo $user->id; ?>
$.ajax({
data: {
data:data,
userid : userid
},
type: "post",
url: "../insert_subs.php",
success: function(data){
alert(data);
}
});
});
in insert_subs.php:
$userid = $_GET['userid'];
**** APPRECIATED Anand Patel, Deena. Both are the same answers that I want! :D Also thanks to epascarello! I didnt try this but I think is working as well. :)
try this
jQuery("#DoneBtn").click(function(){
<?php
$db = JFactory::getDBO();
$user = JFactory::getUser();
?>
var userid = <?php echo $user->id; ?>;
var data = $("#insertsubs_form").serialize() + "&userid=" + userid;
$.ajax({
data: data,
type: "post",
url: "../insert_subs.php",
success: function(data){
alert(data);
}
});
})
Try this...
var userid = <?php echo $user->id; ?>
$.ajax({
type : 'POST',
url : '../insert_subs.php',
data : $('#form').serialize() + "&userid=userid"
});
Try using serializeArray:
var data = $('#insertsubs_form').serializeArray();
data.push({name: 'userid', value: userid });
$.ajax({
data: data,
type: "post",
url: "../insert_subs.php",
success: function(data){
alert(data);
}
or you can use serializeObject
var data = $('#insertsubs_form').serializeObject();
$.extend(data, {'userid': userid });
$.ajax({
data: data,
type: "post",
url: "../insert_subs.php",
success: function(data){
alert(data);
}
or you can use serialize and param
var data = $('#form').serialize() + $.param({"userid":userid});
$.ajax({
data: data,
type: "post",
url: "../insert_subs.php",
success: function(data){
alert(data);
}
or the best solution just add a hidden field in the form with the user id and use serialize!
<input name="userid" type="hidden" value="<?php echo $user->id; ?>" />

Categories