Get array as response from Ajax request - javascript

I use the following Ajax request to pass data:
var query = {
"username" : $('#username').val(),
"email" : $('#email').val(),
}
$.ajax({
type : "POST",
url : "system/process_registration.php",
data : query,
cache : false,
success : function(html) {
// output
}
});
My php-file (process-registration.php), in which the query is being processed, looks like this:
require_once 'db.php';
$username = $_REQUEST['username'];
$email = $_REQUEST['email'];
// Include new user into database
$db -> query("INSERT INTO users (username, email) VALUES ('$username', '$email');");
//Identify user id of this new user (maybe there is a faster way???)
$results = $db -> query("SELECT * FROM users WHERE username='$username'");
while ($result = $results->fetch_assoc()) {
$user_id = $result['id'];
}
// My output?
Now comes my question: How can I tell the Ajax command / the PHP script to return as a result two elements:
a HTML message: <p>You have registered successfully</p>
the $user_id that I have identified via the loop above
I need the user_id, because in the frontend I want to include it as a GET parameter into the href of the button "Go to admin area" that will appear AFTER the Ajax request will be completed.

Try this:
$response = array('user_id'=>$user_id,'message'=>'Success - user created');
echo json_encode($response);
This will give return a json object that you can access in JS.
$.ajax({
type : "POST",
url : "system/process_registration.php",
data : query,
cache : false,
dataType: 'json',
success : function(html) {
// output - do something with the response
console.log(html.user_id);
console.log(html.message);
}
});

I think it would be better to change the array in string by putting a special character(I use % or #)between different values. In your case just echo 'You have registered successfully%'.$user_id ;. Now explode the response string and use both.

Related

How to store PHP array in MySQL?

I tried to store a JavaScript array into MySQL table using PHP, see the following script below.
I first converted the string using JSON.stringify and passed it into a PHP file via AJAX request.
I then converted it to a PHP array, and after after I inserted those arrays using serialize();.
Finally, it properly stored using localhost but it does not work on my live server.
sample.Js
$.ajax(
{
type: "POST",
url: "save_plan_ajax.php",
data: {plan: plan,totalInvesment: totalInvesment, location: JSON.stringify(locationsArr), cost: JSON.stringify(cost), personalised: JSON.stringify(personalised)},
success: function(data){
//alert(data);
}
}
)
In this above script I passed the JavaScript array into save_plan_ajax.php using JSON.stringify.
save_plan_ajax.php
<?php
session_start();
include 'config.php';
if(isset($_POST)){
$planname = $_POST['plan'];
$cost = json_decode($_POST['cost'], true);
$personalised = json_decode($_POST['personalised'], true);
$locations = json_decode($_POST['location'], true);
$userid = $_SESSION['BIID'];
$constriant = $_SESSION['CONSTRAINT'];
$created_date = date("Y-m-d H:i:s");
$total_invs = $_POST['totalInvesment'];
$query = "INSERT INTO `plans` (
`refid` ,
`userid` ,
`plan_name` ,
`cost` ,
`locations`,
`personalised` ,
`total_invs`,
`constriant` ,
`created_date` ,
`stat`
)
VALUES (
NULL , '$userid', '$planname', '".serialize($cost) ."', '".serialize($locations)."','".serialize($personalised)."', '$total_invs', '$constriant', '$created_date', 'A'
)";
$res = $GLOBALS['Db']->Insert($query);
if($res){
echo $res;
}
else{
echo "Error";
}
}
?>
In the above script, the record stores correctly at local server, but in this same script insert N; in server.. how do I fix this error, is the above way correct?
In the MySQL database table I have set the cost, location and personalized fields datatype as LONGTEXT.

Successful AJAX call on working PHP script returns nothing

I'm running a script which is supposed to send a user ID number to a database. The database grabs a bunch of image IDs from whichever row has the matching user ID, then goes to a different table and grabs the image URLs which match the image IDs. Then it returns the URLs.
The PHP script runs fine on its own, it returns the correct URL in either straight text or JSON, as requested.
As for the jQuery, the AJAX call does indeed get to the success function, because I can ask it to document.write something there and it will do it. When I ask it to print out the data, however, the AJAX call runs forever (I think it is repeatedly calling the success function? Based on the browser telling me that it is either waiting or transferring data repeatedly). Regardless, nothing is printed to the screen despite the repeating script.
Oh, also, no errors are returned to the console.
I am not sure why it is doing this and so here I am. I've browsed through the other posts here and randomly on the internet, with no luck. Any help is appreciated!
Here is the PHP:
<?php
header('Content-type: text/plain; charset=utf-8');
// define variables and set to empty values
$servername = "localhost";
$username = "root";
$password = "Wolf*6262";
$dbname = "Game";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if ($_SERVER["REQUEST_METHOD"] == "GET") {
$id = $_GET["id"];
}
$query1 = mysqli_query($conn, "SELECT imageids FROM users WHERE id = $id");
// Start user session
if ($imageIds = mysqli_fetch_array($query1)) {
fetchUrls($imageIds, $conn);
} else {
echo "Fail";
}
function fetchUrls($imageIds, $conn) {
$query2 = mysqli_query($conn, "SELECT url FROM charimages WHERE id = '1'");
$array = mysqli_fetch_assoc($query2);
$url = $array["url"];
exit($url);
}
$conn->close();
The jQuery:
function getUrls (userId) {
$.ajax({
type: 'GET',
data: {id:userId},
URL: 'fetchChar.php',
async: false,
dataType: 'text',
success: function (data) {
document.write(data);
document.write(userId);
}
});
}
Aaand here's where I define userId and call getUrls, it's in a separate HTML file:
var userId = <?php echo $_SESSION["id"]; ?>;
$(document).ready(getUrls(userId));
Can you please modify your script: as standard way what prefer from jQuery:
1. Change URL to url
2. Please avoid async defining
Like this
$.ajax({
type: 'GET',
data:{ id: userId },
url: 'fetchChar.php',
// async: false,
dataType: 'text',
success: function (data) {
console.log(data);
//document.write(data);
//document.write(userId);
}
});
I added console log to show the return data, so that you can make sure that your data is returning correctly from fetchChar.php file using console log.
Ended up doing the following, question solved:
Javascript file:
$.ajax({
type: "POST",
dataType: "json",
url: "fetchChar.php",
data: {id:userId},
success: function(data) {
document.write(JSON.stringify(data));
}
});
PHP file, near the end:
function fetchUrls($imageIds, $conn) {
$query2 = mysqli_query($conn, "SELECT url FROM charimages WHERE id = 1");
$array = mysqli_fetch_assoc($query2);
$url = $array['url'];
$url = json_encode($url);
echo $url;
exit();
}

Receive multiple value from php file via ajax call

Below is my ajax call code. I want to send one data in .php file via ajax call and want to get two values from .php file. This two values I want to set in different 'input' tags whose id are 'course_name' and 'course_credit'.
Here my ajax call return correct value(real value from DB table) of 'course_name' input tag.
But 'MY PROBLEM IS' the value of input tag whose id is 'course_credit' shows 'success'. How can I get the correct value(real value from DB table) of id 'course_credit' ?
I have a 'select' tag which id is 'c_select'
HTML:
<input type="text" name="course_name" id="course_name" value=""/>
<input type="text" name="course_credit" id="course_credit" value=""/>
AJAX :
$('#c_select').change(function(){
$.ajax({
type:'post',
url:'get_course_info_db.php',
data: 'c_id='+ $(this).val(),
success: function(reply_data1,reply_data2){
$('#course_name').val(reply_data1);
$('#course_credit').val(reply_data2);
}
});
});
get_course_info_db.php
<?php
include('db_connection.php');
$c_id = $_POST['c_id'];
$result = mysql_query("SELECT * FROM course WHERE c_id = '$c_id'");
$all_course_data = mysql_fetch_array($result);
$c_name = $all_course_data['c_name'];
$c_credit = $all_course_data['c_credit'];
echo $c_name,$c_credit;
exit();
?>
AJAX code:-
$('#c_select').change(function(){
$.ajax({
type:'post',
url:'get_course_info_db.php',
data: 'c_id='+ $(this).val(),
success: function(value){
var data = value.split(",");
$('#course_name').val(data[0]);
$('#course_credit').val(data[1]);
}
});
});
PHP code:-
<?php
include('db_connection.php');
$c_id = $_POST['c_id'];
$result = mysql_query("SELECT * FROM course WHERE c_id = '$c_id'");
$all_course_data = mysql_fetch_array($result);
$c_name = $all_course_data['c_name'];
$c_credit = $all_course_data['c_credit'];
echo $c_name.",".$c_credit;
exit();
?>
The success callback is Function( PlainObject data, String textStatus, jqXHR jqXHR ); http://api.jquery.com/jQuery.ajax/
php:
$data = array(
'name' => $c_name,
'credit' => $c_credit,
);
echo json_encode($data);
javascript:
success: function(data) {
var result = $.parseJSON(data);
$('#course_name').val(result.name);
$('#course_credit').val(result.credit);
}
success: function(reply_data1,reply_data2){
$('#course_name').val(reply_data1);
$('#course_credit').val(reply_data2);
}
second arguement is the status of http request, you have to encode the answer, i suggest you JSON
in your php
$c_credit = $all_course_data['c_credit'];
echo json_encode(array('name' => $c_name,'credit' => $c_credit));
exit();
and in your javascript
success: function(response,status){
var datas = JSON.parse(response);
$('#course_name').val(datas.name);
$('#course_credit').val(data.credit);
}
this is not tested, but this is the way to do it
I'd suggest using JSON to encode the data you fetch from the database.
Try changing your ajax call as follows:
$('#c_select').change(function(){
$.ajax({
type:'post',
url:'get_course_info_db.php',
data: 'c_id='+ $(this).val(),
dataType: 'json', // jQuery will expect JSON and decode it for you
success: function(reply_data){
$('#course_name').val(reply_data['c_name']);
$('#course_credit').val(reply_data['c_credit']);
}
});
});
And your PHP as follows:
include('db_connection.php');
// Escape your input to prevent SQL injection!
$c_id = mysql_real_escape_string($_POST['c_id']);
$result = mysql_query("SELECT * FROM course WHERE c_id = '$c_id'");
$all_course_data = mysql_fetch_array($result);
echo json_encode($all_course_data);
exit();
I haven't tested this but I imagine it'd work for you.

Upload and download variables using AJAX/PHP

I have a jQuery script file on a page which requires data to be uploaded. Depending on if the data uploaded has a value or not, the PHP page will either return the current time (if value uploaded !isset()), or some sql data. However, when the variable I upload actually has a value, it still returns the !isset() method. Am I doing something incorrectly?
AJAX
$.ajax({
url: 'download.php',
type: 'REQUEST',
datatype: 'json',
data: ({
last_downloaded: latestTimestamp,
username: username
}),
success: function (data) {
parsedData = $.parseJSON(data);
if (!latestTimestamp) {
latestTimestamp = parsedData.most_recent;
}
}
});
}
if latestTimestamp is null, (it should be the first time this method is run), then the most recent time is run. However when it runs the second time, latestTimestamp has a value when I console.log.
PHP
<?php
// Get variables sent
$last_chat_time = $_REQUEST['last_downloaded'];
$username = $_REQUEST['username'];
// Start echoing JSON
if (!isset($last_chat_time)) {
// User did not send last chat time they have, assume they just joined
// Get the most recent chat date
$SQL = 'SELECT current_timestamp() as "most_recent" from dual';
$results = mysql_fetch_assoc(mysql_query($SQL));
$last_chat_time = $results;
echo '{"most_recent":"' . $results['most_recent'] . '"}';
}
else{
$SQL = 'return some tasty data'
$result = mysql_query($SQL);
$messages = Array();
while ( $row = mysql_fetch_assoc($result) ) {
$messages[] = Array(
'chat' => $row['chat'],
'time' => $row['time_sent'],
'username' => $row['username']
);
}
echo json_encode($messages);
}
On the php, it ALWAYS returns the first if. However, if I visit the url directly for the php page and append ?last_downloaded=somedate, it returns the correct information. Am I doing the AJAX incorrectly?
To me this has to be updated to type : 'post or get' because php's $_REQUEST handles both, so you can change your type to this:
$.ajax({
url: 'download.php',
type: 'post',
or this:
$.ajax({
url: 'download.php',
type: 'get',

Problems posting data to a server using jQuery

I'm a student who is doing an app with jQueryMobile and gonna be compiled with Phonegap. I want to posting data to a server using jQuery but I have problems loading my .php file in the server.
I have the last version of jQuery.
Here I put my script for post the data from a form:
$(document).ready(function() {
var postData = $('#registerForm').serialize();
$('#registerForm').submit(function() {
$.ajax({
type: 'post',
data: postData,
url: 'http://www.smartweb.cat/app/Habana/user_register.php',
success: function(data) {
alert('Usuari registrat correctament.');
},
error: function() {
alert('Hi ha algun problema amb el registre.');
}
});
return false;
});
});
Thanks a lot and sorry for my english wrinting.
Your post data are empty. You retrieve them directly when the DOM is loaded and not when the form is submit. You should move your var postData.
$(document).ready(function() {
//var postData = $('#registerForm').serialize();
$('#registerForm').submit(function() {
var postData = $('#registerForm').serialize(); // here
$.ajax({
//...
});
});
});
First of all I want to say that you should use prepared statements.
Althought you sanitize user input(GOOD) its still recommended using prepared statements.
Not only does it help with readability its also more secure.
Make sure your form sends following postdata:
{name:"YourName", surname:"Yoursurname",date:"<dateobject>",email:"sample#mail.com",user:"username",password:"password}
== THIS LOOKS OK ==
$name = mysql_real_escape_string($_POST["name"]);
$surname = mysql_real_escape_string($_POST["surname"]);
$date = $_POST["date"];
$email = mysql_real_escape_string($_POST["email"]);
$user = mysql_real_escape_string($_POST["user"]);
$pass = mysql_real_escape_string($_POST["pass"]);
enter code here
If the conditions above are the same the server should receive all your data. I do see a problem in your query that may be the problem.
What you are doing is inserting everything as string in the database. You have to make sure when you try to execute a query given values for a table that the given values correspond with the database.
$result = mysql_query("INSERT INTO $tableName (name, surname, date, email, user, pass) VALUES
('$name', '$surname', '$date', '$email', '$user', '$pass')"); //insert
Make sure everything is correct for example your date column in the database is it a string or a mysql date TYPE. Try to lose the '.
$result = mysql_query("INSERT INTO $tableName (name, surname, date, email, user, pass) VALUES
($name, $surname, $date, $email, $user, $pass)");

Categories

Resources