1

I built an event to change product name that mix up with ajax and json encode

<div class="new-product-name"></div>
 <div class="new-product-num"></div>

Then the script is

$(function(){
  $.ajax({
    method: "POST",
    url: "fetch-product.php",
    data: {keyword: 12}
  }).done(function(msg){
    $(".new-product-name").html(msg);

    $.getJSON("fetch-product.php", function(data) {
      $(".new-product-name").html(data.a);
      $(".new-product-num").html(data.b);         
    });
  });
});

in fetch-product.php

$query = "SELECT * FROM `product_details` WHERE id='". $_POST['keyword']."'";
$result = $conn->query($query);

if ($result->num_rows > 0) {
  $row = $result->fetch_assoc(); 
  $name=$row["p_name"];
  $num=$row["num"];
}

echo json_encode(array("a" =>  $name, $num));

Here product details is fetching correctly , even in $(".new-product-name").html(msg); it showing '{"a":"Product1", "b":"22"}', it is entering in to $.getJSON("fetch-product.php", function(data) { }

But data.a , data.b showing null.

why is data.a , data.b null ?I am spending too much time . Please help to solve this error .

4
  • Because you don't send the parameters again in the second query - so the second response is mostly empty. Why do you send two requests anyways? Commented May 8, 2017 at 9:36
  • in console.log(data) showing Object { a: null} Commented May 8, 2017 at 9:38
  • could you please explain in answer section . I didn't understand. Commented May 8, 2017 at 9:38
  • i have some appointments now. I'll write something later, if noone else did it in the mean time. Commented May 8, 2017 at 9:40

4 Answers 4

5

I see no reason to make 2 calls to the PHP script.

If you add the dataType:json parameter jQuery will expect a JSONString back from the PHP and msg will be automatically converted to a javascript object.

$(function(){
    $.ajax({
        method: "POST",
        dataType: "json",         // new param
        url: "fetch-product.php",
        data: {keyword: 12}
    })
    .done(function(msg){
        if ( msg.status == 1 ) {
            $(".new-product-name").html(msg.a);
            $(".new-product-num").html(msg.b); 
        } else {
             $(".new-product-name").html(msg.info);
        }
    });
});

The other issue with your call to $.getJSON("fetch-product.php",..... was that this would issue a GET request, and therefore fill the $_GET array with any parameters. Your PHP code is not looking for parameters passed in the $_GET array!

Your PHP code as it was, was vulnerable to SQL Injection, so I have amended it to use Parameterised & Prepared statements.

You also need to consider the possibility that nothing is found by your query and return something to let the javascript know about that.

$query = "SELECT * FROM `product_details` WHERE id=?";
$stmt = $conn->prepare($query);
$stmt->bind_param('i', $_POST['keyword']);
$result = $stmt->execute();

if ($result->num_rows > 0) {
    $row = $result->fetch_assoc(); 
    echo json_encode(array( 'status'=> 1,
                            'a'=>$row["p_name"], 
                            'b'=>$row["num"]);
} else {
    echo json_encode(array('status'=>0,
                            'info'=>'No data found');
}
Sign up to request clarification or add additional context in comments.

7 Comments

(y),, or by converting the response into javascript object manually
@hassan Yes you could do that, but I am lazy and if jQuery will do it all for me and all i have to do is add a parameter..... I take the easy way out :)
I meant to clarify all the possible ways :-), specially that a lot of people mixing between different data-types.
@RiggsFolly I think there's a small typo - dateType: json should be dataType: json. That could be confusing the OP.
@ADyson Thanks for that. I have fixed it
|
4
$.ajax({
    method: "POST",
    url: "fetch-product.php",
    data: {keyword: 12}
  }).done(function(msg){
    $(".new-product-name").html(msg);

makes a POST to fetch-product and writes the value of msg into the product name element. Except that it should probably be msg.a since your code returns an object with the data inside the a property. You also need to set the dataType:json option so that jQuery knows the returned value from the server is an object and not a string.

However, you then make another request to the same URL, but using a GET request and without passing any parameters. Since your PHP tries to read values from POST requests only, this causes your query to return nothing, and thus your output of $name is empty. You then overwrite your product name element with this empty value.

Why you are making this second request to the same resource, but with the wrong settings, is a complete mystery. It is totally unnecessary. This code should do what you need in a single request:

$(function(){
  $.ajax({
    method: "POST",
    url: "fetch-product.php",
    data: {keyword: 12},
    dataType: "json"
  }).done(function(msg){
    $(".new-product-name").html(msg.a);
    $(".new-product-num").html(msg.b); 
  });
});

P.S. Your SQL is incredibly vulnerable to SQL Injection attacks. You should switch to using parameterised queries and prepared statements. Otherwise someone could send a malicious value in the "keyword" parameter and steal, destroy or otherwise corrupt your data. See http://bobby-tables.com/ for a humorous but very clear example of this sort of problem. Both the PDO and mysqli libraries for PHP provide easy ways to create prepared statements, and there are hundreds of examples of the syntax available online for you to follow.

Comments

2

As @Sirko already said, you are sending two requests:

$(function(){
  $.ajax({ // First request, as planned
    method: "POST",
    url: "fetch-product.php",
    data: {keyword: 12}
  }).done(function(msg){
    $(".new-product-name").html(msg);

    // This will send an additional GET request to fetch-product.php without any parameters
    $.getJSON("fetch-product.php", function(data) { 
      $(".new-product-name").html(data.a);    
    });
  });
});

Remove the second request or replace the first with the second, if GET method is applicable it should work fine. Because the second request returns null the html of everything with the class .new-product-name will be empty ("").

Comments

1

If You want to make two php calls , then try This:

fetch-product.php

<?php
    if($_SERVER['REQUEST_METHOD'] == 'GET' ){
    $keyword = $_GET['keyword'];
}else{
    $keyword = $_POST['keyword'];
}

$query = "SELECT * FROM `product_details` WHERE id='". $keyword."'";
$result = $conn->query($query);

if ($result->num_rows > 0) {
 $row = $result->fetch_assoc(); 
 $name=$row["p_name"];
 $num=$row["num"];
}

echo json_encode(array("a" =>  $name, $num));

?>   

Then the Script is

$(function(){ 
var data = {keyword: 12};

$.ajax({
 method: "POST",
 url: "fetch-product.php",
 data: data
}).done(function(msg){
$(".new-product-name").html(msg);

 $.getJSON("fetch-product.php",{keyword: 12}).done(function(data1) {
   $(".new-product-name").html(data1.a);    
  });
  });
});

3 Comments

But why issue 2 AJAX calls to got ONE ( the same ) piece of data?
Just to show how to use GET and PUT in same php file.
if($_SERVER['REQUEST_METHOD'] == 'GET' ){ $keyword = $_GET['keyword']; }else{ $keyword = $_POST['keyword']; } is pointlessly verbose. If you don't care about the HTTP method, just read directly from $_REQUEST["keyword"]. php.net/manual/en/reserved.variables.request.php And making two requests here is completely pointless. An example of how to do this might be good if it actually achieved something useful, but this just wastes bandwidth and users' time.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.