I'm new to JSON and AJAX, and as such have searched for solutions and experimented for a few days before resorting to asking here.
I am using AJAX to process a PHP page on submit. It is saving the information fine, but I also need the PHP page to pass back the inserted ID. Here is what I have so far.
In the success:
success: function(){
$('#popup_name img').remove();
$('#popup_name').html('Saved');
$('#fade , .popup_block').delay(2000).fadeOut(function() {
$('#fade, a.close').remove(); //fade them both out
$.getJSON(pathName, function(json){
alert('You are here');
alert("Json ID: " + json.id);
});
});
}
Then, the PHP script calls this method to insert the info and return the inserted id:
public static function doInsertQuery($sparamQuery="",$bparamAutoIncrement=true,$sparamDb="",$sparamTable=""){
//do the insert
$iReturn = 0;
$result = DbUtil::doQuery($sparamQuery);
if(!$result){
$iReturn = 0;
}
elseif(!$bparamAutoIncrement){
$iReturn = DbUtil::getInsertedId();
}
else{
$iReturn = DbUtil::getInsertedId();
}
//log the insert action
//if not a client logged in- cannot log to client db
if(Session::get_CurrentClientId() > 0){
if($sparamTable != LogLogin::table_LOGLOGINS()){
$oLog = new LogDbRequest();
$oLog->set_Type(LogDbRequest::enumTypeInsert);
$oLog->set_Request($sparamQuery);
$oLog->set_RowId($iReturn);
$oLog->set_TableName($sparamTable);
$oLog->set_Before("NULL");
$oLog->set_After(serialize(DbUtil::getRowCurrentValue($sparamDb,$sparamTable)));
$oLog->insertorupdate_LogDbRequest();
}
}
echo json_encode($iReturn);
return $iReturn;
}
I hope this makes sense. I'm at a complete loss here. Any help at all would be greatly appreciated!
~Mike~
It's simple really. The success function accepts an argument corresponding to the response from the server.
Client side:
$.ajax({
'url':'/path/to/script.php',
'dataType':'json',
'success':function(response){ //note the response argument
alert(response.id); //will alert the id
}
});
Server side:
<?php
//...previous stuff here...
$response = array('id' => $id); //where $id is the id to return to the client
header('Content-type: application/json'); //Set the right content-type header
echo json_encode($response); //Output array as JSON
?>
Related
I really have never done this before and I am getting frustrated because I'm not sure how it fits together. I have a function that I want to call my php (one php file selects info from a database and the second inserts into the database)... I need to use ajax in the way my site is setup but I don't know how to pass data from and to the php files.
In first .js file:
q1LoadVar();
This is my ajax function in second .js file that I have so far (not working):
//ajax code has been edited here since original post:
function q1LoadVar() {
alert("called"); //works!
$.get( "q1LoadVar1.php", function( data ) {
console.log(data); //nothing happens!
// alert(data); //nothing happens!
}, "json" );
}
And here is the code I have in q1LoadVar1.php that I want to select data back from and be able to populate a text area in my html:
/*works when I type this file path directly into the url;
but the file is not communicating back to the ajax function on the
.js file that is calling it*/
<?php
$config = parse_ini_file('../config.ini');
$link = mysqli_connect('localhost',$config['username'],$config['password'],$config['dbname']);
if(mysqli_connect_errno()){
echo mysqli_connect_error();
}
echo '<script type="text/javascript">alert("working from php!");</script>';
$query = "SELECT * FROM Game1_RollarCoaster";
$result = mysqli_query($link, $query);
while ($row = mysqli_fetch_array($result)) {
$newRow[] = $row;
}
$json = json_encode($newRow);
echo $json; //works on php file directly!
/*while ($row = mysqli_fetch_array($result)) {
echo $row[Q1_AnswerChoosen];
}*/
mysqli_free_result($result);
mysqli_close($link);
?>
Can someone help me understand how to make this all work together? Thank you, Kristen
You can retrieve post data from ajax in php with
$_POST['action']
//in your case will return: test
To return data to ajax you need to use echo
If the success: callback function doesnt get called try to remove datatype: 'json'
I also think that you need to echo $newrow instead of $row.
If this still doesnt work you can catch the error with the error: callback function to see what is wrong.
Try to start with a simple request and work from there.
$(document).ready(function() {
$.ajax({
type: "POST",
url: "yourphp.php",
data: {simplestring: "hi"},
success: function(result){
alert(result);
}
});
});
and yourphp.php
<?php
$simplestring = $_POST['simplestring'];
echo $simplestring;
I have a very strange problem and couldn't figure it out. I am working with AJAX/PHP and fetching the data from mysql database on user interaction by ajax call. Everything is working very fine and no problem at all. But only one issue which is persisting is when the data is not found in mysql database, then a user-friendly message is not returned from the server ajax file - the one part works and other doesn't. Here is my code -
This is my first file where the form reside (full code is not there; only js code) -
<script type="text/javascript">
$(document).ready(function(){
$("#selcustomer").change(function(){
var customers_id = $(this).val();
if(customers_id > 0)
{
$.ajax({
beforeSend: startRequest,
url: "ajax/ajax.php",
cache: false,
data: "customers_id="+customers_id,
type: "POST",
dataType: "json",
success: function(data){
if(data != "No result found.")
{
$("#img_preloader").hide();
$("#error").html('');
// $("#txtfname").val(data.fname);
// $("#txtlname").val(data.lname);
for(var key in data)
{
document.getElementById("txt"+key).value = data[key];
}
}
else
{
$("#img_preloader").hide();
$("#error").html(data);
$("input").each(function(){
$(this).val('');
});
}
}
});
}
else
{
$("#error").html('');
$("input").each(function(){
$(this).val('');
});
}
});
});
function startRequest()
{
$("#img_preloader").show();
}
</script>
And this is my server-side ajax file (php file) which interacts with database -
<?php
include("../includes/db-config.php");
if(isset($_POST["customers_id"]))
{
$customers_id = $_POST["customers_id"];
$query = "SELECT * FROM `tb_customers` WHERE `customers_id` = '$customers_id'";
$rs = mysql_query($query);
if(mysql_num_rows($rs) > 0)
{
$row = mysql_fetch_array($rs);
$customers_first_name = $row['customers_first_name'];
$customers_last_name = $row['customers_last_name'];
$customers_email_id = $row['customers_email_id'];
$customers_phone_no = $row['customers_phone_no'];
$customers_address_line_1 = $row['customers_address_line_1'];
$customers_address_line_2 = $row['customers_address_line_2'];
$customers_country = $row['customers_country'];
$data = array('fname' => $customers_first_name, 'lname' => $customers_last_name, 'emailid' => $customers_email_id, 'phoneno' => $customers_phone_no, 'addressline1' => $customers_address_line_1, 'addressline2' => $customers_address_line_2, 'country' => $customers_country);
echo json_encode($data);
}
else
{
echo "No result found.";
}
}
?>
The if part is working fine but when no data is found in database the else part is not sending the data back to jQuery code. I checked in browser console and saw the else part is returning the response but the jquery code in success: part of $.ajax is not running - neither within if, nor in else and also not outside of if/else. I mean to say that a simple alert is not fired with data under success when no data is found in mysql database. But when i remove all the data in ajax/php file and say simply write 123 then alert comes with 123 but not when the actual code is there. Can you plz tell me what is the issue behind this strange problem?
Your datatype is set to JSON in your AJAX call, so the return value must be a valid JSON.
When you are encountering the else condition, you are returning something that is not JSON.
Try this -
else
{
echo json_encode("No result found.");
}
Or something more flexible-
else{
echo json_encode(Array("err"=>"No result found."));
}
EDIT-
...But when i remove all the data in ajax/php file and say simply write
123 then alert comes with 123...
That is because a 123 (number) is valid JSON. Instead of 123, try writing No result and an error would be thrown, because No result (a string) needs quotes(which is taken care when you use json_encode).
I've been trying to figure out what I have done wrong but when I use my JavaScript Console it shows me this error : Cannot read property 'success' of null.
JavaScript
<script>
$(document).ready(function() {
$("#submitBtn").click(function() {
loginToWebsite();
})
});
</script>
<script type="text/javascript">
function loginToWebsite(){
var username = $("username").serialize();
var password = $("password").serialize();
$.ajax({
type: 'POST', url: 'secure/check_login.php', dataType: "json", data: { username: username, password: password, },
datatype:"json",
success: function(result) {
if (result.success != true){
alert("ERROR");
}
else
{
alert("SUCCESS");
}
}
});
}
</script>
PHP
$session_id = rand();
loginCheck($username,$password);
function loginCheck($username,$password)
{
$password = encryptPassword($password);
if (getUser($username,$password) == 1)
{
refreshUID($session_id);
$data = array("success" => true);
echo json_encode($data);
}
else
{
$data = array("success" => false);
echo json_encode($data);
}
}
function refreshUID($session_id)
{
#Update User Session To Database
session_start($session_id);
}
function encryptPassword($password)
{
$password = $encyPass = md5($password);
return $password;
}
function getUser($username,$password)
{
$sql="SELECT * FROM webManager WHERE username='".$username."' and password='".$password."'";
$result= mysql_query($sql) or die(mysql_error());
$count=mysql_num_rows($result) or die(mysql_error());
if ($count = 1)
{
return 1;
}
else
{
return 0;;
}
}
?>
I'm attempting to create a login form which will provide the user with information telling him if his username and password are correct or not.
There are several critical syntax problems in your code causing invalid data to be sent to server. This means your php may not be responding with JSON if the empty fields cause problems in your php functions.
No data returned would mean result.success doesn't exist...which is likely the error you see.
First the selectors: $("username") & $("password") are invalid so your data params will be undefined. Assuming these are element ID's you are missing # prefix. EDIT: turns out these are not the ID's but selectors are invalid regardless
You don't want to use serialize() if you are creating a data object to have jQuery parse into formData. Use one or the other.
to make it simple try using var username = $("#inputUsername").val(). You can fix ID for password field accordingly
dataType is in your options object twice, one with a typo. Remove datatype:"json", which is not camelCase
Learn how to inspect an AJAX request in your browser console. You would have realized that the data params had no values in very short time. At that point a little debugging in console would have lead you to some immediate points to troubleshoot.
Also inspecting request you would likely see no json was returned
EDIT: Also seems you will need to do some validation in your php as input data is obviously causing a failure to return any response data
Try to add this in back-end process:
header("Cache-Control: no-cache, must-revalidate");
header('Content-type: application/json');
header('Content-type: text/json');
hope this help !
i testet on your page. You have other problems. Your postvaribales in your ajax call are missing, because your selectors are wrong!
You are trying to select the input's name attribute via ID selector. The ID of your input['name'] is "inputUsername"
So you have to select it this way
$('#inputUsername').val();
// or
$('input[name="username"]').val();
I tried it again. You PHP script is responsing nothing. Just a 200.
$.ajax({
type: 'POST',
url: 'secure/check_login.php',
dataType: "json",
data: 'username='+$("#inputUsername").val()+'&password='+$("#inputPassword").val(),
success: function(result) {
if (result.success != true){
alert("ERROR");
} else {
alert("HEHEHE");
}
}
});
Try to add following code on the top of your PHP script.
header("Content-type: appliation/json");
echo '{"success":true}';
exit;
You need to convert the string returned by the PHP script, (see this question) for this you need to use the $.parseJSON() (see more in the jQuery API).
I am attempting to add data to my database from my HTML code via the use of JQuery, AJAX/JSON and PHP using an MVC model. Below is a small sample of what I am looking to achieve.
In my front end I have a checkbox with different options and a button named 'Add'. The selected elements from here are picked up by a Javascript function, which I have tested properly, once this is done I call another Javascript function to do the AJAX/JSON . What I am still fresh on is the actual AJAX/JSON process that sends the data to PHP.
My Javascript function:
function add_fruits(fruit_name, fruit_type){
var success = "Fruit added";
var error = "Fruit not added";
var params = {
'fruit_name' : fruit_name,
'fruit_type' : fruit_type
};
$.ajax({
type: "POST",
url: "add_fruits.php",
async: false,
data: params,
success: function(success){
alert(success);
},
error: function(error){
alert(error);
}
});
}
My PHP function:
<?php
header("Access-Control-Allow-Origin: *");
header('Content-type: application/json');
require_once 'lib/connection_files.php';
if($_SERVER['REQUEST_METHOD'] =='POST')
{
$fruit_name = no_sql_injection($_POST['fruit_name']);
$fruit_type = no_sql_injection($_POST['fruit_type']);
$fruits = new fruits();
$result = $fruits->add_fruits($fruit_name, $fruit_type);
$tmp = mysql_num_rows($result);
if($result == 1)
{//RESULT must return 1 to verify successful insertion to database
//send confirmation to front end
}
else
{
//send error message to front end
}
}
else{
//tell front end there was error sending data via AJAX
}
?>
Note that the add_fruits() function takes care of doing the Queries to the database, I did not include it here because it is irrelevant to my issue.
Just do echo in your PHP:
PHP
else {
//send error message to front end
echo "Error Adding Fruits";
}
JS
success: function(data) {
if (data == "1") {
//data added to db
}
else {
alert(data);
}
}
I'm having troubles using ajax and php. What I'm trying to do is call an ajax function that grabs a value from an form's input, and checks if that email exists in a database. Here is my current javascript:
//Checks for Existing Email
function checkExisting_email() {
$.ajax({
type: 'POST',
url: 'checkExist.php',
data: input
});
emailExists = checkExisting_email();
//If it exists
if (emailExists) {
alert("This email already exists!");
}
Unfortunately, I can't get my alert to go off. In my PHP function, it checks whether the input is a username or an email (just for my purposes, and so you know), and then it looks for it in either column. If it finds it, it returns true, and if not, it returns false:
include ('func_lib.php');
connect();
check($_POST['input']);
function check($args)
{
$checkemail = "/^[a-z0-9]+([_\\.-][a-z0-9]+)*#([a-z0-9]+([\.-][a-z0-9]+)*)+\\.[a-z]{2,}$/i";
if (!preg_match($checkemail, $args)) {
//logic for username argument
$sql = "SELECT * FROM `users` WHERE `username`='" . $args . "'";
$res = mysql_query($sql) or die(mysql_error());
if (mysql_num_rows($res) > 0) {
return true;
} else {
return false;
}
} else {
//logic for email argument
$sql = "SELECT * FROM `users` WHERE `email`='" . $args . "'";
$res = mysql_query($sql) or die(mysql_error());
if (mysql_num_rows($res) > 0) {
return true;
} else {
return false;
}
}
}
SO my issue is, how does ajax respond to these returns, and how do I make ajax function accordingly? Mainly, why doesn't this work?
Any help is very much appreciated. Thank you!
You need to add the success option to your Ajax request, which is the JS function which gets executed when the XHR succeeds. Have a look at the jQuery documentation for more info.
Without running the script, I think you'll find that $_POST['input'] is empty; you need to pass your data as something like data: {'input': input} to do that.
Your PHP also needs to return some content to the script; consider changing your call to check() to something like this:
echo (check($_POST) ? 'true' : 'false');
You can now check the content in JavaScript.
Basically ajax is a hand-shaking routine with your server.
Ajax:
$.post('yoursite.com/pagewithfunction.php',
{postkey1:postvalue1, postkey2:postvalue2...},
function (response) {
// response is the data echo'd by your server
}, 'json'
);
pagewithfunction:
yourFunction(){
$var1 = $_POST['postkey1'];....
$result = dosomething($var1..);
echo json_encode($result); // this is passed into your function(response) of ajax call
}
So in $.post you have the url of the php page with the function, { var:val } is the post data, and function(response) is where you handle the data that is echo'd from your server -- the variable, response, is the content that is echo'd.