I'm validating my html form with Jquery/Ajax Call. It's process by Php. In php page its return all success result or error result after processing To Jquery Success method.
SO I want to receive another parameters in jquery success method (). Is there any way to received it ?
for example : in this following line code If $numSearch is == 0
elseif($numSearch === 0){
echo "<font color='red'>No Matches.</font>";
}
then I want to received another parameters in jquery success method so that I can load getDetails2(SearchValue); function. Now it's load when the value is integer. But it's should be check if value is Integer and result is showing something.
Php code :
require_once("corefile.php");
$search = (int) $_POST['data'];
$cdid = inputvalid($_POST['cdid']);
if($cdid == "ID"){
// if serach value is empty
if(empty($search)){
echo "<font color='red'>Search keyword required.</font>";
}
// if serach value is not empty
elseif(!empty($search)){
// start myqli_query to search
//$numserach
}
elseif($numSearch === 0){
echo "<font color='red'>No Matches.</font>";
}
}
Jquery Code:
$(document).ready(function() {
$("#cdid").click(function() {
var SearchValue = $('#txt_name').val();
var cdid = $('#cdid').val();
$("#loading-image").show();
$.ajax({ //create an ajax request to load_page.php
type: "POST",
url: "doSearch.php",
data : {
'data' : SearchValue,
'cdid' : cdid
},
dataType: "html", //expect html to be returned
success: function(response){
if(Math.floor(SearchValue) == SearchValue && $.isNumeric(SearchValue)){
getDetails2(SearchValue);
}
$("#showSearchResult").html(response);
$('#visiableaftersearch').hide();
document.getElementById('txt_name').value='';
document.getElementById('txt_given_name').value='';
$("#loading-image").hide();
}
});
});
});
It is possible, if you use JSON, so you can add more value as key value pair, in JSONObject such as:
{"key1":"value1","key2":"value2"}
Then using JSON.parse, parse the data from success method. Then loop it, to get the key & value separately.
success: function(response){
var json=JSON.parse(response);
jQuery.each(json, function(i, val) {
console.log("key : "+i+" value: "+val);
});
}
Yes it can be done, Use dataType: "json" in Ajax call(instead of HTML response), and send some flags for error & Success , based on that flags parse your Json response.
For eg,
The php file you are making an ajax request , should encode returning data in Json format, like(with the necessary flags)
//example
echo json_encode(array($con_info));
Related
i have a problem when parsing json from php to javascript
this is my example code :
//function
MethodAjax = function (wsFile, param) {
return $.ajax({
type: "POST",
dataType: "json",
url: '../proses/' + wsFile + ".proses.php",
data: 'param='+param,
error: function (msg) {
return;
},
});
};
//call function
$(document).ready(function() {
$('#getproduk').click(function(){
var param = {
ProdukId : '1',
ProdukName : 'test'
};
CallMethodWithAjax('try', JSON.stringify(param)).done(function(data){
$data = JSON && JSON.parse(data) || $.parseJSON(data);
});
});
//Simple Php code
<?php
$data = $_POST['param'];
$data = (json_decode($data));
$data1['name'] = $data->ProdukName;
$data1['id'] = $data->ProdukId;
$data1['test'] = 'test';
echo json_encode($data1);
?>
//post, response and error at console
response : {"name":"test","id":"1","test":"test"}
post : param {"ProdukId":"1","ProdukName":"test"}
error : SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data
how to solve this probled, i have try the solution that i found at SO and google, but still cannot solve this problem
please someone help
thanks
jQuery's $.ajax() function will yield a JavaScript object if the response is JSON so I believe the error you're seeing is a result of trying to parse a JavaScript object and not a string as you're expecting. In the callback you're providing to the done function, inspect data and you'll find that it's an object and there is no need to JSON.parse the result.
I was wondering if you could help. I am attempting to pass a variable to a PHP file, then run a SQL query, using that variable, then pass back the result as a variable to the javascript. Currently, I have successfully received the PHP back to the javascript using Ajax, but not able to sending the ServiceName to the PHP File. It is essential that the files stay separate. Also just to clarify I have replaced certain sections for privacy, however, they are correct and working in the code. I have also used a $_GET method already, however, I could only get the javascript to access a new window and not return the PHP variable.
My current code is as follows:
// If the user changes the ServiceID field.
if (sender.getFieldName() == 'ServiceID')
// Declare the value of the new Service name and save it in the variable A.
a = sender.getValue();
{
// if it equals a new variable.
if (sender.getValue() == a) {
// Place it within the URL, in order for it to be processed in the php code.
window.location.href = "http://IP/development/Query01.php?service=" + a;
// Attempted code
// echo jason_encode(a);
// $.ajax({var service = a;
// $.post('http://IP/development/Query01.php', {variable: service});
// }
//use AJAX to retrieve the results, this does work if the service name is hard coded into the PHP.
$.ajax({
url: "http://IP/development/Query01.php",
dataType: "json", //the return type data is jsonn
success: function(data) { // <--- (data) is in json format
editors['Contact2'].setValue(data);
//alert(data);
//parse the json data
}
});
}
}
}
<?php
$serverName = "SeverIP"; //serverName\instanceName, portNumber (default is 1433)
$connectionInfo = array( "Database"=>"DatabaseName", "UID"=>"Username", "PWD"=>"Password
$conn = sqlsrv_connect( $serverName, $connectionInfo);
$service = $_GET['service'];
if ($conn)
{
//echo "Connection established.<br />";
}
else
{
echo "Connection could not be established.<br />";
die( print_r( sqlsrv_errors(), true));
}
$sql = ("SELECT DefaultContact2 FROM tblServices WHERE ServiceName = '$service'");
$stmt = sqlsrv_query($conn, $sql);
if ($stmt === false)
{
die( print_r( sqlsrv_errors(), true));
}
while ($row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC))
{
$dC2 = $row['DefaultContact2'];
}
echo json_encode ($dC2);
sqlsrv_free_stmt( $stmt);
?>
Any help would be greatly appreciated.
You could send data using your Ajax request like so.
$.ajax({
url: "http://IP/development/Query01.php",
method: "POST" // send as POST, you could also use GET or PUT,
data: { name: "John", location: "Boston" }
dataType: "json",
success: function(data) {
editors['Contact2'].setValue(data);
}
});
Then in PHP access the sent data:
<?php
print_r($_POST);
/*
[
"name" => "John",
"location" => "Boston"
]
*/
?>
You cannot pass the javascript's variable to php on same page.
You can do this with ajax call with POST or GET method, and then you can send the manipulated data back to you browser and store it in your javascript's object or variable.
You can do it in a single Ajax call.
Remove from your code this line:
window.location.href = "http://IP/development/Query01.php?service=" + a;
And modify a bit the Ajax call
$.ajax({
type: 'GET'
data : {
service: sender.getValue();
},
url: "http://IP/development/Query01.php",
dataType: "json", //the return type data is jsonn
success: function(data){ // <--- (data) is in json format
editors['Contact2'].setValue(data);
//alert(data);
//parse the json data
}
});
I put the same variable name for the Get in the Ajax call. But I don't know if your query01.php should accept to do now both actions in the same call.
Thank you guys for your help. Just thought it would be useful, if I posted of what I went with in the end, regardless of whether it is the right way, it certainly done the job.
// If the user changes the ServiceID field.
if (sender.getFieldName() == 'ServiceID')
{
// Variable Declaration
serviceName = sender.getValue();
{
// Use JQuery.Ajax to send a variable to the php file, and return the result.
$.ajax({
// Access the PHP file and save the serviceName variable in the URL, to allow the $_GET..
// method to access the javascript variable to apply it within the SQL Query.
url: "http://ServerName/development/DefaultContact1.php?service=" + serviceName,
// retrieve the result, using json.
dataType: "json", // the return type data is jsonn
success: function(data)// <--- (data) is in json format
{
// pre-fill the contact1 field with the result of the PHP file.
editors['Contact1'].setValue(data);
}
// End of Ajax Query
});
// End of function to prefill Contact1 field.
Thank again for your responses!
I am trying to get customer details in a Laravel POS application. I am sending customer cell number via AJAX to serch and returning details from controller. When ever I am trying to apply JSON.parse on returned data from server I am getting:
Uncaught SyntaxError: Unexpected token s in JSON at position 0
I cant find errors in my code. I have searched product in exact same way from the server which works fine. Below is my code sample:
My Ajax Function
function customersearch(){
var token=$('input[name=_token]').val();
var baseUrl=document.getElementById("baseUrl").value;
var url=baseUrl+"/sales/searchcustomer";
var id=document.getElementById("customercell").value;
console.log(id);
$.ajax({
type: "GET",
headers: {'X-CSRF-TOKEN': token},
url:url,
data: {id:id},
datatype:'json',
success: function(data) {
var returndata =JSON.parse(data);
console.log(returndata);
var id=returndata[0].id;
if(id == "undefined") {
alert("No Customer found");
}
else {
document.getElementById("cname").value = returndata[0].fname;
document.getElementById("cid").value = returndata[0].id;
}
}
});
}
My Controller Function:
public function searchcustomer(Request $request){
$searchingkey = $request->input( 'id' );
//var_dump($searchingkey);
$customer = DB::table('customers')
->where('cellno', $searchingkey)
->get(['id','fname']);
var_dump($customer);
if (count($customer) == 0) {
$data = "No data returned"; // empty result
}
else {
$data = $customer;
}
return json_encode($data);
}
Response of var_dump($customer) in Network XHR
array(1) {
[0]=>
object(stdClass)#221 (2) {["id"]=>string(1) "1"
["fname"]=>string(5) "Ahnaf"}}
[{"id":"1","fname":"Ahnaf"}]
IF I dont apply JSON.parse on the returned data in ajax Function and just print the data variable like:
var returndata =data;
console.log(returndata);
this gives output in the consol like:
array(1) {
[0]=>
object(stdClass)#221 (2) {
["id"]=>string(1) "1"
["fname"]=>string(5) "Ahnaf"
}
}
[{"id":"1","fname":"Ahnaf"}]
The jquery docs for the ajax function say that the dataType parameter is spelled with a capital T.
You have this:
datatype:'json'
Try changing it to this:
dataType:'json'
and see if that helps.
You can try first() instead of get().
That should solve this.
You should use echo rather than return for ajax response
My Controller Function:
echo json_encode($data);
Also dataType must be
dataType: "json" // but remove this line because your already have JSON.parse(data);
I'm using Jquery's ajax method, and I need help parsing data coming back from backend server.
server response will be either "valid" or "not valid.
Currently my "if statement logic is not working, this is what I have tried so far).
$.ajax({
url: 'php/phone-valid.php',
type: 'POST',
data: {userid: $.trim($('#userid').val())},
success: function(data) {
console.log(data);
if (result.indexOf("not valid")) {
("#mustbevalid").val("You must validate your phone number");
console.log("Phone hasn't been validated");
e.preventDefault();
};
}
});
Your help is highly appreciated.
You're checking result.indexOf, but your response data is in data not result. Additionally, indexOf returns the position, which could be 0. So change to:
if(data.indexOf("not valid") > -1) {
Side note: this method of checking a result is error-prone and usually undesirable. It would be better for you to output a JSON object with a success property.
Example success response:
echo json_encode(array('success' => true));
// Outputs: {"success":true}
Example error response:
echo json_encode(array('success' => false));
// Outputs: {"success":false}
Now, you can parse the JSON:
$.ajax({
...
dataType : 'json', // <-- tell jQuery we're expecting JSON
success: function(data) {
if (data.success) {
// success
} else {
// error
};
}
});
indexOf will return the position in the string. So use this instead:
if(data.indexOf("not valid") == 0)
(Secondary title): ajax array recieved as json encoded PHP array not behaving as javascript array
For some reason, my PHP array gets sent over to JavaScript just fine, but when I try to access an individual key of the array, it doesn't return anything, or it returns some other value which doesn't correspond. I am of course using json_encode() in the corresponding PHP file (echoClientData.php):
$id = $_GET['selected_id'];
$id = str_replace("clientSel","",$id);
$getclientinfo = "SELECT * FROM `clients` WHERE `ClientID` = $id";
if ($result = $Database->query($getclientinfo))
{
$row = $result->fetch_row();
$output = $row;
}
echo json_encode($output);
This code works fine:
$.ajax(
{
url: "echoClientData.php?selected_id=" + HTMLid,
type: 'GET',
success: function(data)
{
test = data;
$('#client-detail-box').html(test);
}
});
And returns an array into the #client-detail-box div, e.g.
["1566","","Adrian","Tiggert","","","","","","","","","","","","0000-00-00","0000-00-00","0.00","","0","","","102","Dimitri Papazov","2006-02-24","102","Dimitri Papazov","2006-02-24","1","0","0"]
However, when I do
$.ajax(
{
url: "echoClientData.php?selected_id=" + HTMLid,
type: 'GET',
success: function(data)
{
test = data[3]; // should be "Tiggert"
$('#client-detail-box').html(test);
}
});
}
It returns
5
You may need to do one of two things when returning JSON from PHP.
Either set your content type in PHP before echoing your output so that jQuery automatically parses it to a javascript object or array:
header('Content-type: application/json');
or specify that jQuery should treat the returned data as json:
$.ajax(
{
url: "echoClientData.php?selected_id=" + HTMLid,
type: 'GET',
dataType: 'json',
success: function(data)
{
var test = data[3]; // should be "Tiggert"
$('#client-detail-box').html(test);
}
});
Be aware, that in your current PHP script, in the event that your query fails, you will be json_encodeing an undefined variable.
Also, your PHP code is entirely open to SQL injection. Make sure you sanitize your $id, either by casting it to (int) or by escaping it before sending it through in your query.
Have you tried using JSON.parse on the value you are getting back from PHP?
e.g.
$.ajax(
{
url: "echoClientData.php?selected_id=" + HTMLid,
type: 'GET',
success: function(data)
{
test = JSON.parse(data); // should be "Tiggert"
$('#client-detail-box').html(test[3]);
}
});
That seems like it would be a fix.