ajax method post send to mysql query - javascript

I pass the variable javascript method by ajax post method to the php file in this way:
$(".btn_ranking").click(function (e) {
e.preventDefault();
var name = localStorage.getItem('name');
var time = localStorage.getItem('timer_end');
$.ajax({
url: 'php/file.php',
type: 'post',
dataType: "json",
contentType: "application/json; charset=utf-8",
data: {
name: name,
time: time
},
success: function(response){
console.log(response);
}
});
});
Request Payload in my Browser returns: name=Adrian&time=00%3A01%3A59. What should I write in the file file.php to send variables using sql query to my mysql database?

You can make good use of php explode() method here:
$string = name=Adrian&time=00%3A01%3A59
$parameters = explode("&", name=Adrian&time=00%3A01%3A59)
This will give you an array $parameters:
($parameters[0] == name=Adrian,
$parameters[1] == time=00%3A01%3A59)
Now you can get the name and time from $parameters:
$name = explode("=", $parameters[0])[1];
$time = explode("=", $parameters[1])[1];

Related

cannot send json data from html to php

I cannot send JSON Data from HTML to PHP with jquery and always show fail status at console.log. Please check my code.
jsonObjects.domain = client_domain;
jsonObjects.pkg = client_package;
jsonObjects.company_name = client_company;
jsonObjects.company_email = client_email;
jsonObjects.personal_name = psn_name;
jsonObjects.personal_phone = psn_phone;
jsonObjects.personal_email = psn_email;
var JsonPush = new Array();
JsonPush.push(jsonObjects);
var JsonArray = JSON.stringify(JsonPush);
$.ajax({
type: "POST",
url: 'order.php',
data: JsonArray,
dataType: 'json',
})
.done(function (data) {
console.log('done');
console.log(data);
}).
fail(function (data) {
console.log('fail');
console.log(data);
});
Order.php file
<?php
$decoded = json_decode($_POST['data']);
var_dump($decoded);
?>
You don't need to stringify first, just post it in a keyed object and access via the key like this
let postData = { object: jsonObjects };
$.ajax({
type: "POST",
url: 'order.php',
data: postData,
dataType: 'json',
})
Then in php:
$jsonObjects = $_POST['object'];
note: you don't access the posted variable by the name of the object itself but rather the keys inside the posted object
You have no data parameter in your AJAX call. It should be:
data: { data: JsonArray },
But there really isn't any need to use JSON at all. You can just given an object as the data: option, and its properties will become POST parameters.
data: jsonObjects,
Then in PHP you can access $_POST['domain'], $_POST['pkg'], etc.

Posting multiple values to PHP from Ajax request

I have an Ajax request to save data from JavaScript and write it to a file using a separate ("saveData.php") PHP file. I want to know if I can "POST" multiple JavaScript variables / strings within the same Ajax request.
For instance, I currently have this:
function saveData(){ //sends an AJAX request to saveData.php
$.ajax({
type: "POST",
url: "saveData.php",
dataType: "text/plain",
ContentType: "charset=utf-8",
data: {"data": dataString},
})
}
And this works great via my PHP file, which as this code:
$data = $_POST["data"];
$theFile = fopen("Data/" . FileNameHere . ".txt", "a+");
// Save data into a file based on their username
fwrite($theFile, $data);
fclose($theFile);
But I want to save the file based on their userID, which is a JavaScript variable.
Can I do something like this:
function saveData(){ //sends an AJAX request to saveData.php
$.ajax({
type: "POST",
url: "saveData.php",
dataType: "text/plain",
ContentType: "charset=utf-8",
data: {"data": dataString},
data1: {"data1": userID}, <-----new line with JS variable 'userID'
})
}
And PHP file like this:
// Prepare line of data to save.
$data = $_POST["data"];
$userID = $_POST["data1"]; <--------New code to POST "data1" from Ajax
$theFile = fopen("Data/" . $userID . ".txt", "a+");
// Save data into a file based on their username
fwrite($theFile, $data);
fclose($theFile);
Yes, you can, you are passing a JSON Object so it can have as many properties as you like.
Read More about, how to send multiple data in server side via ajax.
Try this
function saveData(){ //sends an AJAX request to saveData.php
$.ajax({
type: "POST",
url: "saveData.php",
dataType: "text/plain",
ContentType: "charset=utf-8",
data: {
"data": dataString,
"data2":val2,
"data3":val3,
"data4":val4
},
})
}
And PHP file like this:
$data = $_POST["data"];
$userID = $_POST["data2"];
$theFile = fopen("Data/" . $userID . ".txt", "a+");
// Save data into a file based on their username
fwrite($theFile, $data);
fclose($theFile);

JSON decode is not working with PHP

I have a WAMP server with PHP 5.4.3 version. I encoded the data in JSON by php file below is the code (submit.php).
$username = 'User';
$comment = 'Test comment';
$date = date("Y-m-d G:i:s");
$image = '/img/sephiroth.png';
$return = array(
'username'=> $username,
'comment' => $comment,
'date' => $date,
'image' => $image );
echo json_encode($return);
Now i have a javascript file(script.js).
$.ajax({
type: "POST",
url: "submit.php",
data: dataString,
cache: false,
success: function(result){
alert(result); //It is showing all the JSON data.
$value = result;
$data = json_decode($value,true);
alert($data);
}
});
I want to decode all the JSON data separately. e.g Username, comment, date, image. So, i can show them on webpage, at the moment all data is coming together. I tried multiple times with multiple options (php array or result.username or result['username'] but no luck.
Now i am getting below error.
ReferenceError: json_decode is not defined
$data = json_decode($value,true);
you cannot use json_decode in JS json_decode is PHP function
use jQuery.parseJSON(json_data) to parse your json data;
jQuery.parseJSON( result );
Change
$value = result;
$data = json_decode($value,true);
To :
jQuery.parseJSON( result );
http://api.jquery.com/jQuery.parseJSON/
Try the following:
success: function(result){
var res = $.parseJSON(result);
var data = [res.username, res.comment, res.date, res.image]; // Array of the received response
}
This way you can get required output
try like below:
$.ajax({
type: "POST",
url: "submit.php",
data: dataString,
cache: false,
success: function(result){
alert(result); //It is showing all the JSON data.
jQuery.parseJSON( result );
}
});
Use the dataType option of ajax and set its value to json.
Then you can access the response as result['username']
My example:
Server-side returns {"username":"xxxxx","data":"xxxxxxxxxxxx and more"}
You can just deal with json like a javascript array, do not need to decode it.
the data below itself is the array of result.
$.ajax({
type: "POST",
url: "submit.php",
cache: false,
success: function(data){
var username = data['username'];
var data = data['data'];
//and so on
}
});
And make sure php sent the header Content-Type:application/json
header('Content-Type: application/json');

jQuery and ajax to set session variable in PHP

I'm using a session variable in PHP to manage the current language in a multi-language site. To achieve what I want I'm using a flag icon that when clicked (jQuery) it tells lang_json.php to switch the session variable to the new language.
I'm not getting errors on the jQuery side:
var sendData = 'en';
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "lang_json.php",
data: ({newLang: sendData}),
dataType: "json",
success: function (msg) {
alert('Success');
},
error: function (err){
alert('Error');
}
});
But the PHP file is not setting the session variable:
lang_json.php:
<?php
// Session variables
session_name('aklogin'); // Starting the session
session_start();
if( isset($_POST['newLang']) ){
$_SESSION['current_lan'] = $_POST['newLang'];
}else{
$_SESSION['current_lan'] = "Not Posting";
}
?>
The session variable is returning "Not Posting".
You claim you are sending the server JSON, but:
You aren't
The PHP isn't set up to receive JSON
Remove contentType: "application/json; charset=utf-8",, then jQuery will set the correct content-type and PHP will populate $_POST.
I kept playing with the jQuery side and this is what worked:
var sendData = 'en';
$.ajax({
type: 'POST',
url: 'app/pro/pro_lang_session_json.php',
data: {'newLang': sendData},
success: function (msg) {
alert(sendData);
},
error: function (err){
alert('Error');
}
});
The session variable sets to 'en' with this code.
Thank you for your help! #DelightedDOD

What is the right way of sending a var on AJAX

I have a javascript function that calls a Webmethod. I tried sending a regular string to the webmethod and it works. On var empid= $('#' + txtId).val() Im getting the right value of the text box. What is the right way of sending empid over ajax ? I have tried a few thing and they dont work. Any help would be appreciated. Thanks
.js
function toggle(txtId, lblname, txtcode) {
var empid = $('#' + txtId ).val();
$.ajax({
type: "POST",
url: "SearchEmpId.asmx/GetEmployeeName",
data: '{ id: empid }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
$('#' + lblname).html(data.d);
}
});
}
.asmx.vb (webmethod)
Public Function GetEmployeeName(ByVal id As String) As String
Return "It works"
End Function
This is a screen shoot when removing contentType
Instead of
data: '{ id: empid }',
use
data: { id: empid },
Its sending JSON
Use dataType:"json" for json data
$.ajax({
url: 'ajax.php', //This is the current doc
type: "POST",
dataType:'json', // add json datatype to get json
data: ({name: 145}),
success: function(data){
console.log(data);
}
});
Read Docs http://api.jquery.com/jQuery.ajax/
Also in PHP
<?php
$userAnswer = $_POST['name'];
$sql="SELECT * FROM <tablname> where color='".$userAnswer."'" ;
$result=mysql_query($sql);
$row=mysql_fetch_array($result);
// for first row only and suppose table having data
echo json_encode($row); // pass array in json_encode
?>
You can use like below:
var empid=$('#txtEmpId').val();
Pass empid in data as
data: { id: empid },
Check out the fiddle here: http://jsfiddle.net/gN6CT/103/

Categories